$(document).ready(function() {

    // Function to allow an XHTML compliant way of making links open in a new window
    $("a[rel$='external']").click(function() {
        this.target = "_blank";
    });
    $("a[rel$='print']").click(function() {
        print();
        return false;
    });
    
    // Fields
    var isModal = false;
    var isIE6 = false;
    var isIE7 = false;
    var isIE = false;
    var equalHeightRowCss = ".row_eq_height";
    var equalHeightColCss = ".col_eq_height";

    // Check for IE6 
    if (jQuery.browser.msie && jQuery.browser.version < 7) {
		DD_belatedPNG.fix('a.arrow_left, ul.arrow_left li,ul.arrow_left_large li,#explore, #footer img, .top, .middle, .bottom, .rightcol_bg ul li, .carousel .carousel_paging ul li, .carousel .carousel_paging ul li.active, blockquote p, blockquote p span.rightquote, img, .carousel .carousel_paging ul li.active, .block_article_star');
        isIE6 = true;
    }
    // Check for IE7
    if (jQuery.browser.msie && jQuery.browser.version < 8) {
        isIE7 = true;
    }
    if (jQuery.browser.msie) {
        isIE = true;
    }

    // Set the heights of columns within rows
    $(equalHeightRowCss).each(function() {
        setColumnHeights($(this));
    });

    function setColumnHeights(container) {
        equalHeight($(equalHeightColCss, container));
    }

    function equalHeight(group) {
        var tallest = 0;
        group.each(function() {
            thisHeight = $(this).height();
            if (thisHeight > tallest) {
                tallest = thisHeight;
            }
        });

        // IE6 does not support the min-height property so apply standard height
        if (isIE6) {
            group.css("height", tallest.toString() + "px");
        } else {
            group.css("min-height", tallest.toString() + "px");
        }
    }

    // Set the heights of columns within rows
    $(".content_grid .expandable_row").each(function() {
        setExpandableColumnHeights($(this));
    });

    function setExpandableColumnHeights(container) {
        equalExpandableHeight($(".expandable .content", container));
    }

    function equalExpandableHeight(group) {
        var tallest = 0;
        group.each(function() {
            thisHeight = $(this).height();
            if (thisHeight > tallest) {
                tallest = thisHeight;
            }
        });
        group.data("animateHeight", tallest);
    }
    
    if ($(".toggled_text"))
    {
	    $(".toggled_text").hide();
    }
    $(".show_all").click(function(event) {
        $(".toggled_text", $(this).parent().parent()).slideToggle();
        var LinkText = $(this).html();
        if (LinkText == "Show summary") {
            $(this).addClass("hide_all");
            $(this).text("Hide summary");
        }
        else {
            $(this).removeClass("hide_all");
            $(this).text("Show summary");
        }
        return false;
    });

    // Scrolling content functionality
    if ($(".carousel .scrollable").length > 0) {
        initializeScrollable(".carousel", { navi: ".carousel .carousel_paging ul" });
        $(".carousel .carousel_paging ul li").filter(':first').addClass("active");
        $(".carousel .carousel_paging ul li img").addClass("hide");
    }

    function initializeScrollable(tag, options) {
        var defaults = { size: 1, circular: true, speed: 1000, leftOffset: 100, displayTop: true };
        var options = $.extend(defaults, options);
        if (options.navi.length > 0) {
            return $(".scrollable", tag).scrollable(options).autoscroll({ autoplay: true, interval: 5000 }).navigator({ api: true });
        }
        else {
            return $(".scrollable", tag).scrollable(options).autoscroll({ autoplay: true, api: true, interval: 5000 });
        }
    }

	// case study tabs
    if ($("#tabs_control").length != 0) {
		// hide the tabpanels
		$("#tabs_control #tab_content>div").hide();
		$("#tabs_control ul#tab_stubs li:nth-child(2)").removeClass("active").addClass("inactive");
		// sort out the top nav
        $("#tabs_control ul#tab_stubs li").each(function() {
			// defaults
			if ($(this).hasClass("active"))
			{
				$("#" + $("a",this).attr("rel")).show()
			}
			var li_current = $(this);
			$("a",this).click(function(){
				if (li_current.hasClass("inactive"))
				{
			        $("#tabs_control ul#tab_stubs li").removeClass("active");
			        $("#tabs_control ul#tab_stubs li").addClass("inactive");
			        li_current.removeClass("inactive");
			        li_current.addClass("active");
				}
				$("#tabs_control #tab_content>div").hide();
				$("#" + $(this).attr("rel")).show()
				return false;
			});
        });
		// sort out the bottom nav
        $("#tabs_control #tab_content .box_grey_shadow ul li").each(function() {
			var li_current = $(this);
			$("a",this).click(function(){
		        var li_current = $("#tabs_control ul#tab_stubs a[rel$='"+$(this).attr("rel")+"']").parent().parent().parent();
		        $("#tabs_control ul#tab_stubs li").removeClass("active");
		        $("#tabs_control ul#tab_stubs li").addClass("inactive");
		        li_current.removeClass("inactive");
		        li_current.addClass("active");
				$("#tabs_control #tab_content>div").hide();
				$("#" + $(this).attr("rel")).show();
				return false;
			});
        });
        
    }

    if ($("#nav_l1_container").length > 0) {
        loadPopupContent();
    }

    function loadPopupContent() {
        var popupSettings = new Array();
        popupSettings["case-studies"] = { navItem: "#nav_l1_container li.case-studies", innerContentWidth: 282, leftOffset: 65 };
        popupSettings["explore-hr-careers"] = { navItem: "#nav_l1_container li.explore-hr-careers", innerContentWidth: 282, leftOffset: 40 };

        popupContent = $("<div id='nav_popup_container'/>");
        popupContent.load("/publicsites/cScape.CIPD.HRCareers/static/l1nav.htm", function() {
        $("#nav_l1_container .nav_l1").append(popupContent);
            for (setting in popupSettings) {
                $(popupSettings[setting].navItem).navigationPopup({ innerContentWidth: popupSettings[setting].innerContentWidth, leftOffset: popupSettings[setting].leftOffset });
                $("#" + setting, this).transparentFrame({ topBorderWidth: popupSettings[setting].innerContentWidth, contentWidth: popupSettings[setting].innerContentWidth, bottomBorderWidth: popupSettings[setting].innerContentWidth, borderWidth: 10, popupClass: 'nav_popup' });
            }
        });
    }
});

// Navigation popup plugin
// Note: has dependency on transparentFrame plugin
(function($) {
    $.fn.extend({
        navigationPopup: function(options) {

            var defaults = {
                innerContentWidth: 802,
                leftOffset: 6
            };
            var options = $.extend(defaults, options);
            var hoverIntentConfig = {
                sensitivity: 1, // number = sensitivity threshold (must be 1 or higher)
                interval: 100, // number = milliseconds for onMouseOver polling interval
                over: tabHoverOver, // function = onMouseOver callback (REQUIRED)
                timeout: 500, // number = milliseconds delay before onMouseOut
                out: tabHoverOut // function = onMouseOut callback (REQUIRED)
            }

            function tabHoverOver() {
                var navItem = $(this);
                var section = navItem.attr('class').split(' ')[0];

                if (typeof (isModal) == 'undefined' || !isModal) {
                    // Ensure any currently opened navigation is closed
                    $("#nav_l1_container li>div").removeClass("over");

                    // Add css class to indicate the item is currently in the rollover state
                    $(">div:first-child", this).addClass("over");

                    // Only trigger the popup if the current item does not already contain the wrapper div
                    if ($("div.over").find(".wrapper").length == 0) {

						// if it is the current selected remove the spans
						if ($(this).hasClass("current"))
						{	
	                        $(">div>span>span>a", this).unwrap();
	                        $(">div>span>a", this).unwrap();
                        }

                        if ($(".wrapper").length != 0) {
                            $(".nav_l1>ul>li").each(function() {
                                $(">div>div>a", this).unwrap();
                                //alert("one");
                            });
                        }
                        $("div.over>a", this).wrap('<div class="wrapper"/>');
                        var pos = $(".wrapper", this).position();

                        var topLeft = (pos.top + $(this).height()) - 4;
                        var width = $(".over", this).width() + 12;

                        // Create a shim element that contains the joining curved corners
                        $shim = $("<div class='shim' style='top: " + topLeft + "px; left: " + (pos.left - 5) + "px; width: " + width + "px'/>");
                        $left = $("<div class='left'>&nbsp;</div>");
                        $middle = $("<div class='middle' style='width: " + ($(".over", this).width() - 2) + "px'>&nbsp;</div>");
                        $right = $("<div class='right'>&nbsp;</div>");

                        if ($(navItem).find(".shim").length == 0) {
                            $shim.append($left, $middle, $right);
                        }

                        if ($(".shim").length != 0) {
                            $(".shim").each(function() {
                                $(this).remove();
                            });
                        }
                        navItem.append($shim);

                        var shimPos = $shim.position();
                        var shimPoint = $shim.height();
                        var ee = shimPoint + shimPos.top;

                        if ($(navItem).find("#" + section).length == 0 && $(navItem).find(".shim").length > 0) {
                            $(navItem).append($("#" + section));
                        }

                        $(".nav_popup").hide();
                        $("#" + section, navItem).css({ position: "absolute", top: (ee - 3), left: (shimPos.left - options.leftOffset) }).show();
                    }
                }
            }

            function tabHoverOut() {
                var section = $(this).attr('class').split(' ')[0];

                $(">div", this).removeClass("over");
                $(">div>div>a", this).unwrap();
                $(this).find(".shim").remove();
                $("#" + section).hide();
   				// if it is the current selected remove the spans
				if ($(this).hasClass("current"))
				{	
	                $(">div>a", this).wrap("<span/>");
	                $(">div>span>a", this).wrap("<span/>");
                }
            }

            return this.each(function() {
                var o = options;
                var navItem = $(this);
                navItem.hoverIntent(hoverIntentConfig);
            });
        }
    });
})(jQuery);

//	Transparent frame plugin
// -- NOTE: you must specify the width of the content section in the css
(function($) {
    $.fn.extend({
        transparentFrame: function(options, callbackFunction) {

            var defaults = {
                borderWidth: 20,
                topBorderWidth: 200,
                contentWidth: 200,
                bottomBorderWidth: 200,
                popupClass: "popup"
            };
            var options = $.extend(defaults, options);

            return this.each(function() {
                var o = options;
                var obj = $(this);

                var $topBorder, $leftBorder, $rightBorder, $bottomBorder, $middleContainer;

                function $div(className) {
                    return $('<div class="' + className + '" />');
                }

                $wrap = $div(o.popupClass);
                $wrap.attr("id", obj.attr("id"));
                $content = $div("content_section");
                $content.append(obj.html());

                var interfaceWidth = o.contentWidth + o.borderWidth;

                $wrap.css("width", interfaceWidth);

                $wrap.append(
					$('<div class="top_container clearfix" />').append(
						$div("top_left"),
						$topBorder = $div("top_middle"),
						$div("top_right")
					),
					$middleContainer = $('<div class="middle_container clearfix" />').append(
						$leftBorder = $div("middle_left"),
						$content,
						$rightBorder = $div("middle_right")
					),
					$('<div class="bottom_container clearfix" />').append(
						$div("bottom_left"),
						$bottomBorder = $div("bottom_middle"),
						$div("bottom_right")
					)
				);

                $topBorder.css("width", o.topBorderWidth);
                $content.css("width", o.contentWidth);
                $bottomBorder.css("width", o.bottomBorderWidth);

                // Check for IE6 
                if (jQuery.browser.msie && jQuery.browser.version < 7) {
                    $leftBorder.css("height", obj.outerHeight(true));
                    $middleContainer.css("height", obj.outerHeight(true));
                    $content.css("height", obj.outerHeight(true));
                    $rightBorder.css("height", obj.outerHeight(true));
                } else {
                    $leftBorder.css("min-height", obj.outerHeight(true));
                    $middleContainer.css("min-height", obj.outerHeight(true));
                    $content.css("min-height", obj.outerHeight(true));
                    $rightBorder.css("min-height", obj.outerHeight(true));
                }

                // Workaround for Firefox Mac - 1 pixel height gap on left and right border
                if (obj.hasClass("height_fix")) {
                    jQuery.each(jQuery.browser, function(i, val) {
                        if (i == "mozilla" && navigator.appVersion.indexOf("Mac") != -1) {
                            $leftBorder.height(obj.outerHeight(true) + 1);
                            $rightBorder.height(obj.outerHeight(true) + 1);
                        }
                    });
                }

                $(this).replaceWith($wrap);

                // now call a callback function
                if (typeof callbackFunction == 'function') {
                    callbackFunction.call(this);
                }
            });
        }
    });
})(jQuery);

