/* Initialisation */
var $j = jQuery.noConflict();
$j(document).ready(function(){
    $j(".png").supersleight(); /* Fix transparency for pngs in IE6 */
    $j(".tab_component").tabs();
    $j(".vertical_tab_component").tabs();
    $j("table").formatTable();
    $j(".concertina_component").concertina();
    $j(".faq_component").concertina({
        showFirstDetailOnLoad: false
    });
    $j("div.detail_table").detailTable();
    $j(".masthead_component .search form").globalSearch({
        setInitialText: true
    });
    $j(".main_content form:has(.search)").globalSearch();
    $j(".toggleSet").toggleCheckboxes();
    $j(".utilities").utilities();
    $j(".flash").flash();
    $j(".news_list_component").news_list();
    $j(".masthead_component .quick_links:visible").quickLinks();
    $j(".nav").hoverFix(); /* Apply JS fix for IE6 not supporting :hover */
	$j.focusFirstInput(); /* Set the cursor focus to first input */
    /* Just for the Sitepublisher Edit mode to change the grey background color because iframes layout 
     * ignore the white background of the main layout. This will do nothing in other case than Edit mode */
    $j("body").changeBackground();
});
/* tablesorter settings */
$j.tablesorter.defaults.sortList = [[0, 1]]; //sort by first column descending
$j.tablesorter.defaults.widgets = ['zebra'];
$j.tablesorter.defaults.cssAsc = "ascending";
$j.tablesorter.defaults.cssDesc = "descending";
$j.tablesorter.addParser({
    id: 'ukdate',
    is: function(s){
        return false;
    },
    format: function(s){
        return new Date(s).getTime();
    },
    type: 'numeric'
});
/* end tablesorter settings */
/* globalSearch */
(function($){
$.fn.globalSearch = function(options){
    var defaults = {
        setInitialText: false,
        initialText: "Enter your search text",
        allowSubmit: true
    };
    var options = $.extend(defaults, options);
    return this.each(function(){
        var obj = $(this);
        var search_field = $(".search_field", obj);
        var button = $("input[type='submit']", obj);
        search_field.bind("keypress", function(e){
            var keycode = 0;
            if (e.charCode) {
                keycode = e.charCode;
            } else if (e.keyCode) {
                keycode = e.keyCode;
            } else if (e.which) {
                keycode = e.which;
            }
            if (keycode === 13) {
                e.preventDefault();
                button.trigger("click");
            }
        });
        obj.bind("submit", function(e){
            if (search_field.attr("value") == options.initialText) {
                search_field.attr("value", "");
            }
        });
        if (options.setInitialText) {
            search_field.bind("click", function(e){
                $(this).attr("value", "");
            });
            if (search_field.attr("value") == "") {
                search_field.attr("value", options.initialText);
            }
        }
    });
};
})(jQuery);
/* end globalSearch */
/* toggleCheckboxes */
(function($){
$.fn.toggleCheckboxes = function(){
    var fieldset = $(this).parents("fieldset:first");
    var relatedCheckboxes = $("input[type='checkbox']", fieldset).not(".toggleSet");
    $(this).bind("click", function(e){
        // Select all related boxes
        if (this.checked) {
            $.each((relatedCheckboxes), function(){
                $(this).attr("checked", true);
            });
        }
    });
    // Deselect toggle box if any related box touched
    $.each((relatedCheckboxes), function(){
        $(this).bind("click", function(e){
            var fieldset = $(this).parents("fieldset:first");
            $(".toggleSet", fieldset).attr("checked", false);
        });
    });
};
})(jQuery);
/* end toggleCheckboxes */
/* detailTable */
(function($){
$.fn.detailTable = function(){
    var defaults = {};
    var options = $.extend(defaults, options);
    return this.each(function(){
        var obj = $(this);
        $(".feature_component", obj).concertina({
            showFirstDetailOnLoad: true,
            clickToToggle: false
        });
        // need to trigger a click event on the appropriate toggle-classed element when any cell of the table is clicked
        var i = 0;
        $.each($("tbody > tr", obj), function(){
            var target = ".toggle:eq(" + i + ")";
            var row = $(this);
            $.each($("td", row), function(){
                var cell = $(this);
                cell.addClass("link");
                cell.bind("click", function(e){
                    $(target, obj).trigger("click");
                });
            });
            // set the contents of the first column to never wrap
            $.each($("td:eq(0)", row), function(){
                $(this).addClass("nowrap");
            });
            i++;
        });
    });
};
})(jQuery);
/* end detailTable */
/* concertina */
(function($){
$.fn.concertina = function(options){
    var defaults = {
        toggleCssClass: "toggle",
        collapsedCssClass: "inactive",
        clickToToggle: true,
        showFirstDetailOnLoad: true,
        collapseTitleText: "Click to collapse",
        expandTitleText: "Click to expand",
        addTitleText: true
    };
    options = $.extend(defaults, options);
    return this.each(function(){
        var obj = $(this);
        obj.collapseAll = collapseAll;
        obj.collapseAll();
        if (options.showFirstDetailOnLoad) {
            $("." + options.toggleCssClass + ":first", obj).parent().removeClass(options.collapsedCssClass);
        }
        $.each($("." + options.toggleCssClass, obj), function(){
            //collapse all layers then set selected layer to opposite of status when clicked
            $(this).bind("click", function(e){
                var collapsed = $(this).parent().hasClass(options.collapsedCssClass);
                obj.collapseAll();
                if (collapsed || !options.clickToToggle) {
                    $(this).parent().removeClass(options.collapsedCssClass);
                    if(options.addTitleText) {
                        $(this).attr("title", options.collapseTitleText);
                    }
                }
            });
        });
    });
    function collapseAll(){
        var obj = $(this);
        $.each($("." + options.toggleCssClass, obj), function(){
            $(this).parent().addClass("inactive");
            if(options.addTitleText) {
                $(this).attr("title", options.expandTitleText);
            }
        });
    };
    function makeAllLabelsInactive(){
        var obj = $(this);
        $.each($(".tablist li", obj), function(){
            $(this).removeClass(options.selectedCssClass);
        });
    };
};
})(jQuery);
/* end concertina */
/* tabs */
(function($){
$.fn.tabs = function(options){
    var defaults = {
        collapsedCssClass: "inactive",
        selectedCssClass: "selected",
        toggleCssClass: "toggle",
        vertTabClass: "vertical_tab_component",
        tabOverHang: 10,
        //Defaults used in Concertina
        clickToToggle: false,
        addTitleText: false
    };
    options = $.extend(defaults, options);
    return this.each(function(){
        var obj = $(this);
        var firstToggle = $(".tablist li:first", obj);
        firstToggle.addClass(options.selectedCssClass);
        //Store current toggle
        obj.selectedTogg = firstToggle;
        //Pass in all the options to the concertina as it will only use the relevant ones
        $(".tabs", obj).concertina(options);
        // need to trigger a click event on the appropriate toggle-classed element when the first column of the table is clicked
        $.each($(".tablist li", obj), function( iter ){
            var target = "." + options.toggleCssClass +":eq(" + iter + ")";
            $(this).bind("click", function(e){
                var togg = $(this);
                obj.selectedTogg.removeClass(options.selectedCssClass)
                togg.addClass(options.selectedCssClass);
                obj.selectedTogg = togg;
                var ele = $(target, obj);
                ele.trigger("click");
                if (obj.hasClass(options.vertTabClass)) {
                    var diff = $(this).outerHeight() + $(this).offset().top - $(this).css("border-bottom-width").replace("px", "") - ele.parent().offset().top - ele.parent().outerHeight() - $(".tabs", obj).css("padding-bottom").replace("px", "");
                    if (diff > 0) {
                        diff = diff + options.tabOverHang;
                        ele.parent().height(ele.parent().height() + diff);
                    }
                }
            });
        });
        $(".tablist li:first", obj).trigger("click");
    });
};
})(jQuery);
/* end tabs */
/* utilities component: Adds the below functionality to the site publisher component
 * - onclick for Print 
 * - Builds up mailto subject and body and adds to link
 * - onclick for bookmark functionality
 * */ 
(function($){
$.fn.utilities = function(){
    var defaults = {};
    var options = $.extend(defaults, options);
    return this.each(function(){
        var obj = $(this);
        $(".printLink", obj).bind("click", function(e){
            window.print();
        });
        $(".emailLink", obj).attr("href", "mailto:?subject=" + encodeURIComponent(document.title) + "&body=" + window.location.href);
        $(".bookmarkLink", obj).bind("click", function(e){
            var url = window.location.href;
            var title = document.title;
            if (window.sidebar) {
                window.sidebar.addPanel(title, url, "");
            } else if (document.all) {
                window.external.AddFavorite(url, title);
            } else {
                alert("Sorry, your browser doesn't support bookmark links");
            }
        });
    });
};
})(jQuery);
/* end utilities */
/* flash */
(function($){
$.fn.flash = function(){
    return this.each(function(){
        var obj = $(this);
        if (DetectFlashVer(9, 0, 0)) {
            $(".flash_content", obj).addClass("inactive");
        } else {
            $("object", obj).addClass("inactive");
        }
    });
};
})(jQuery);
/* end flash */
/* news_list */
(function($){
$.fn.news_list = function(){
    var defaults = {};
    var options = $.extend(defaults, options);
    return this.each(function(){
        var obj = $(this);
        // Declare available functions
        obj.populateAvailableYearsInSelect = populateAvailableYearsInSelect;
        obj.drawLines = drawLines;
        // Call functions
        obj.populateAvailableYearsInSelect();
        obj.drawLines('');
        $(".news_table thead > tr:first > th:eq(1)", obj).unbind("click");
        $(".news_table thead > tr:first > th:eq(2)", obj).unbind("click");
        // trigger sort twice to get around IE7 rendering bug
        $(".news_table thead > tr:first > th:eq(0)", obj).trigger("click");
        $(".news_table thead > tr:first > th:eq(0)", obj).trigger("click");
        $(".news_table", obj).removeClass('inactive');
        $(".selected_year", obj).bind("change", function(e){
            var selectedDate = $('.selected_year option:selected', obj).val();
            obj.drawLines(selectedDate);
        });
    });
    function populateAvailableYearsInSelect(obj){
        var obj = $(this);
        var allDates = new Hash();
        $.each($(".news_table tbody tr", obj), function(){
            var obj = $(this);
            $("td:eq(0)", obj).addClass("nowrap");
            var firstCell = $("td:eq(0)", obj)[0];
            var dateFull = new Date(firstCell.innerHTML);
            allDates.setItem(dateFull.getFullYear(), dateFull.getFullYear());
        });
        var sortedAvailableDates = new Array();
        for (var yearDate in allDates.items) {
            sortedAvailableDates.push(yearDate);
        };
        sortedAvailableDates.sort(function(a, b){
            return b - a;
        });
        $(".selected_year > option:first", obj).attr("value", "");
        //TODO: Review if 'i += 1' is correct or if its a typo
        for (var i = 0; i < sortedAvailableDates.length; i += 1) {
            var option = document.createElement('option');
            option.value = sortedAvailableDates[i];
            option.innerHTML = sortedAvailableDates[i];
            $(".selected_year", obj).append(option);
        };
    };
    function drawLines(selectedYear){
        var obj = $(this);
        var myDate = new Date();
        var limitDate = new Date();
        limitDate.setMonth(myDate.getMonth() - 6);
        
        $.each($(".news_table tbody  tr", obj), function(){
            var obj = $(this);
            var firstCell = $("td:eq(0)", obj)[0];
            var dateFull = new Date(firstCell.innerHTML);
            if (selectedYear.toLowerCase() == "") {
                if (limitDate.getTime() <= dateFull.getTime()) {
                    obj.show();
                    $(".news_description", obj).show();
                } else {
                    obj.hide();
                }
            } else {
                var dateFull = new Date(firstCell.innerHTML);
                if (dateFull.getFullYear() == selectedYear.toLowerCase()) {
                    obj.show();
                    $(".news_description", obj).hide();
                } else {
                    obj.hide();
                }
            }
        });
    };
    function Hash(){
        this.length = 0;
        this.items = new Array();
        for (var i = 0; i < arguments.length; i += 2) {
            if (typeof(arguments[i + 1]) != 'undefined') {
                this.items[arguments[i]] = arguments[i + 1];
                this.length++;
            }
        }
        this.removeItem = function(in_key){
            var tmp_value;
            if (typeof(this.items[in_key]) != 'undefined') {
                this.length--;
                var tmp_value = this.items[in_key];
                delete this.items[in_key];
            }
            return tmp_value;
        }
        this.getItem = function(in_key){
            return this.items[in_key];
        }
        this.setItem = function(in_key, in_value){
            if (typeof(in_value) != 'undefined') {
                if (typeof(this.items[in_key]) == 'undefined') {
                    this.length++;
                }
                this.items[in_key] = in_value;
            }
            return in_value;
        }
        this.hasItem = function(in_key){
            return typeof(this.items[in_key]) != 'undefined';
        }
    };
};
})(jQuery);
/* end news_list */
/* Quick links */
(function($){
$.fn.quickLinks = function(options){
    var defaults = {
        inactiveCssClass: "inactive",
        overlayCssClass: "overlay"
    };
    var options = $.extend(defaults, options);
    return this.each(function(){
        var obj = $(this);
        var header = $("h4", obj);
        var list = $("ul", obj);
        list.addClass(options.overlayCssClass);
        list.addClass(options.inactiveCssClass);
        header.bind("click", function(e){
            if (list.hasClass(options.inactiveCssClass)) {
                list.removeClass(options.inactiveCssClass);
            } else {
                list.addClass(options.inactiveCssClass);
            }
        });
    });
};
})(jQuery);
/* end quick links */
/* change background color in edit mode for sitePublisher pages */
(function($){
$.fn.changeBackground = function(){
    var defaults = {};
    var options = $.extend(defaults, options);
    return this.each(function(){
        var obj = $(this);
        var regexp = /pagePalette/i;
        if (document.referrer.match(regexp)) {
            obj.css("background", "#FFF");
        };
    });
};
})(jQuery);
/* end change background */
/* IE6 nav hover fix */
/* IE6 does not allow :hover to be used on tags other then <a> so need to simulate this using js */
(function($){
    $.fn.hoverFix = function(){
        return this.each(function(){
            var obj = $(this);
            $('li', obj).hover(function(){
                $(this).addClass('over');
            }, function(){
                $(this).removeClass('over');
            });
            $('li.active a', obj).addClass("active");
        });
    };
})(jQuery);
/* end IE6 nav hover fix */
/* set table banding and sorting */
(function($){
$.fn.formatTable = function(){
    var defaults = {};
    var options = $.extend(defaults, options);
    return this.each(function(){
        var obj = $(this);
        if (obj.hasClass("sortable")) {
            obj.tablesorter();
        } else {
            if ($("thead > tr", obj).length > 0) {
                var rows = $("tbody > tr", obj);
                $.each(rows, function(iter){
                    if (iter % 2 == 0) {
                        $(this).removeClass("alt");
                    } else {
                        $(this).addClass("alt");
                    }
                });
            } else {
                var rows = $("tr", obj);
                $.each(rows, function(iter){
                    if (iter % 2 == 0) {
                        $(this).addClass("alt");
                    } else {
                        $(this).removeClass("alt");
                    }
                });
            }
        }
    });
};
})(jQuery);
/* end set table banding and sorting */
/* Sets the focus to the first visible text or password input box */
(function($){
$.focusFirstInput = function(){
	var first = $(":text:visible:enabled:eq(0)");
	if (first.length < 1) {
		first = $(":password:visible:enabled:eq(0)");
	}
	if (first) {
		first.focus();
	}
}
})(jQuery);
(function($){
$.registerDisclaimerButtons = function() {
    var buttons = $(".seg_wiz_disclaimer span.action a");
    buttons.click(function() {
        closeModal($j(this).text());
    });
    function closeModal( result ) {
        top.closeDisclaimerModal(result);
    };
}
})(jQuery);
/*login from logged-in user disclaimer page*/
(function($){
$.login = function( event ){
	event.preventDefault();
    var linkLocation = event.target.href;
	var declineBtn   = $("span.action.decline");
	var userName     = $("#userName").val();
	var globalKey    = $("#globalKey").val();
	var globalPin    = $("#globalPin").val();
	var postBack     = $("#postBack").val();
	displayLoadingOverlay();
	initiateLogin();
	function displayLoadingOverlay(){
		var contentsId = "modalContents";
		var url = "TB_inline?height=100&width=250&inlineId=" + contentsId + "&modal=true";
	    tb_show(null, url, false);
	}
	function initiateLogin() {
        $.ajax({type: "POST", 
                 url: "/general/login/index.jhtml",
                 data: {userName:   userName,
                        globalKey:  globalKey,
                        globalPin:  globalPin,
                        postback:   postBack,
                        fromGlobal: "true"},
                 dataType: "json",
                 success: retrieveDynSessConf,
                 error: handleError 
             });
    }
	function retrieveDynSessConf( response ) {
        if(response && response.success) {
            $.ajax({type:"GET", 
                     url: "/general/accesscontrol.jhtml", 
                     dataType: "html",
                     success: completeLogin,
                     error: handleError
                    });
        } else {
            handleError(response, response.error);
        }
    }
    function completeLogin(response, textStatus) {
		response.match(/(.*)_dynSessConf=([-\d]*)"/);
        var dynSessConf = RegExp.$2;
        $.ajax({type: "GET", 
                 url: "/general/accesscontrol.jhtml", 
                 data: {_DARGS: "/general/fragment/accesscontrol.jhtml.1_A",
                        _DAV: "",
                        _dynSessConf: dynSessConf},
                 async: false, 
                 dataType: "html",
                 error: handleError,
				 success: function() {
				 	//Login successful so forward user onto the link on the accept button
                    window.location = linkLocation;
				 }
                });
    }
    function handleError(response, error) {
		jQuery("#TB_window").css("display", "none"); //This line is required so that the error box shows correctly
        jQuery("#TB_ajaxContent").remove(); //Remove the contents of the box so can be overwriten by the error message  
        //Make sure that the abnove line has had time to remove the contents before showing error message 
        window.setTimeout(function(){$.processError({callback:redirectToLogin})}, 0);
	}
    function redirectToLogin() {
        window.location = "/global/login/index.html";
    }
}
})(jQuery);
/**
 * Processes an error that occurs during an AJAX call
 * Once implemented will send erro notification via an AJAX call tot he server 
 */
(function($) {
$.processError = function( options ) {
	var defaults = {
        callback: null,
		errorMsg: "An unexpected error has occured"
    };
    options = $.extend(defaults, options);
	reportError();
	displayErrorOverlay();
	function displayErrorOverlay(){
        var contentsId = "errorNoticeContents";
        var url = "TB_inline?height=115&width=350&inlineId=" + contentsId;
        tb_show(null, url, false, options.callback);
    }
	function reportError() {
		//here do the AJAX call to the server to report the error
	}
	
}
})(jQuery);
/*End login from disclaimer page*/
/* Checks to see if a user is logged into the old site and forwards to already logged in screen if they are */
(function($){
$.checkIfLoggedIn = function(){
    $.ajax({
        type: "GET",
        url: "/general/is_transient.jhtml",
        async: false,
        dataType: "json",
        success: function(response){
            if (response && response.isTransient === false){
                window.location = "/general/already_logged_in.jhtml";
            }
        }
    });
};
})(jQuery);
/**
 * Force a redraw to fix browser redraw issues
 */
(function($){
$.fn.redraw = function(){
	var element = $(this);
	var n = document.createTextNode(' ');
	element.append(n);
	window.setTimeout(function(){n.parentNode.removeChild(n)}, 0);
	return element;
}
})(jQuery);