/*! Global JS - isader */
if (!window['HN']) { window.ND = {}; }

(function($) {

    window.ND = ND = {};
    /* 2008/01/14 - ND.anchors v0.99 - Glenn Baker - Support for, external, popup:XXX:XXX, close, and print. Includes PopupWindow(url,n,w,h,sc) */
    ND.anchors = { storage: { external: function() { var ex = window.open(this.href); return !ex; }, popup: function() { var dims = arguments && arguments.length == 2 ? arguments : window.__popupDims; popupWindow(this.href, 'name', dims[0], dims[1], 'yes'); return false; }, close: function() { window.close(); return false; }, print: function() { window.print(); return false; } }, init: function() { if (this != ND.anchors) { return ND.anchors.init(); } window.popupWindow = this.popupWindow; if (!window.__popupDims) window.__popupDims = [619, 380]; var atype = window.__aType ? window.__aType : "rel"; if (document.getElementsByTagName && document.getElementById) { var anchors = document.getElementsByTagName("a"); for (i = 0; i < anchors.length; i++) { var attr = String(atype == "class" ? anchors[i].className : anchors[i].getAttribute(atype)); if (attr) { var matches = attr.match(/([^\s])+/g); for (var j = 0; j < matches.length; j++) { var match = matches[j].replace(/^([\w]*)[:|][^,\s]+([,]?[^,\s]+)*$/i, "$1"); var args = (matches[j].replace(match, "")).match(/[^,|:\s]+/g); if (this.storage[match]) { anchors[i].onclick = this.Bind(this.storage[match], args); } } } } } }, popupWindow: function(url, n, w, h, sc) { var sw = screen.availWidth; var sh = screen.availHeight; lp = (sw) ? (sw - w) / 2 : 0; tp = (sh) ? (sh - h) / 2 : 0; se = 'height=' + h + ',width=' + w + ',top=' + tp + ',left=' + lp + ',scrollbars=' + sc + ',resizable=yes'; win = window.open(url, n, se); win.focus(); }, add: function(rel, fn) { if (!this.storage[rel]) this.storage[rel] = fn; else throw ("Behaviour already exisits for '" + rel + "'"); }, setPopupDimensions: function(w, h) { window.__popupDims = [w, h]; }, setAttrType: function(a) { window.__aType = a; }, Bind: function(fn) { var args = []; if (arguments.length > 1) { args = (new String(arguments[1])).split(","); } return function() { return fn.apply(this, args); }; } };

    jQuery.fn.extend({
        hoverFocus: function(fnOver, fnOut) {
            return this.mouseenter(fnOver).mouseleave(fnOut).focus(fnOver).blur(fnOut);
        }
    });

    // Primary Navigation dropdown menus
    ND.primaryNav = function() {
        function over() {
            $(this).addClass("dropped");
        };

        function out() {
            $(this).removeClass("dropped");
        };
        $("#nav LI.dropdown").not("#nav LI LI").hoverIntent({ interval: 0, sensitivity: 2, timeout: 0, over: over, out: out });
    };

    ND.secondaryNav = function() {
        $(".side-nav LI.expandable A").not(".side-nav LI LI A").bind("click", function() {
            $(this).parent().toggleClass("expanded");
            return false;
        });
    };

    // Adds LI:hover functionality to IE6
    ND.ieHover = function() {
        if ($.browser.msie && $.browser.version.substr(0, 3) == "6.0") {
            var ul_array = $("ul");
            for (var i = 0; i < ul_array.length; i++) {
                if ($(ul_array[i].parentNode).hasClass("hoverable")) {
                    //Add 'hover' classes
                    var listItems = $(ul_array[i]).children("li");
                    for (var k = 0; k < listItems.length; k++) {
                        $(listItems[k]).hoverFocus(function() { $(this).addClass("hover"); }, function() { $(this).removeClass("hover"); });
                    }
                    //Fix for multiple class issue in primary-nav
                    var currentDropdowns = $(listItems).filter(".dropdown.current");
                    for (var j = 0; j < currentDropdowns.length; j++) {
                        $(currentDropdowns[j]).removeClass("dropdown").removeClass("current").addClass("dropdown-current");
                    }
                }
            }
        }
    };

    // Tabbed Containers
    ND.tabbedContainers = {
        init: function() {
            var tabbedContainers = $(".tabbed-containers");
            $(tabbedContainers).find(".tabs a[href]").click(function() {
                // Set tab status
                var parentLi = $(this).parents("li");
                $(parentLi).siblings(".current").removeClass("current");
                $(parentLi).addClass("current");
                // Hide currently visible container
                $(tabbedContainers).find(".container:not(.accessible)").addClass("accessible");
                // Show selected container
                var containerId = $(this).attr("href");
                $(containerId).removeClass("accessible");
                return false;
            });
        }
    };

    ND.anchors.setAttrType("class");
    ND.anchors.add("opener", function() {
        if (window['opener']) {
            window.opener.location.href = this.href;
            window.close();
            return false;
        }
    });

    ND.formatPlaylist = function() {
        var itemWidth = $("DIV.playlist UL LI").width();
        var itemCount = $("DIV.playlist UL LI").size();
        var minWidth = itemWidth * itemCount;
        $("DIV.playlist UL").width(minWidth);
    };

    /** Find out the heighest section is each row and apply its height to 
    the other section in the same row
    **/
    ND.sitemapSectionHeight = function() {
        var lists = $("DIV.sitemap DIV.section").children("UL");
        var itemsPerRow = 4;
        var counter = 1;
        var items = new Array();
        var heighest = 0;
        lists.each(function(i) {
            var height = $(this).height();
            heighest = (heighest > height) ? heighest : height;
            items.push(this);
            if (counter == itemsPerRow || counter == lists.size()) {
                for (var j = 0; j < items.length; j++) {
                    $(items[j]).height(heighest);
                }
                heighest = 0;
                items = new Array();
            }
            counter++;
        });
    };

    ND.galleryControls = function() {
        var thumbnails = $("DIV.multimedia-gallery .gallery .thumbnails");
        var playlist = $("DIV.multimedia-gallery .playlist");
        var ulWidth = 0;
        var liWidth = 0;
        var ulHeight = 0;
        var liHeight = 0;
        var thumbsDisabled = false;
        var buttonDisabled = false;
        init();

        function init() {
            if (thumbnails.size() > 0) {
                thumbnailsInit();
            }
        };

        function thumbnailsInit() {
            thumbnailsEvents();
            showCaption($(".caption").text());
        };

        function thumbnailsEvents() {
            $("UL LI A", thumbnails).bind("click", function() {
                if (!thumbsDisabled) {
                    thumbsDisabled = true;
                    var caption = $("IMG", this).attr("alt");
                    var imagePath = $(this).attr("href");
                    $("UL LI", thumbnails).removeClass("selected").find("A SPAN.overlay").appendTo(this);
                    $(this).parent().addClass("selected");
                    showImage(imagePath, caption);
                    showCaption(caption);
                }
                return false;
            });
        };

        function showImage(path, caption) {
            var viewImage = $("DIV.view-image");
            var currentPath = $("IMG", viewImage).attr("src");
            //$(viewImage).css("background-image","url("+currentPath+")");
            $("IMG", viewImage).attr("src", path).hide();
            $("IMG", viewImage).show();
        };

        function showCaption(caption) {
            var viewImage = $("DIV.view-image");
            $("P.caption", viewImage).text(caption);
            var height = $("P.caption", viewImage).height();
            $("P.caption", viewImage).hide();
            $("DIV.opacity", viewImage).animate({ height: height - 10 }).animate({
                opacity: 0.6,
                height: height + 20
            }, 500).animate({ opacity: 0.7 }, 100, null, function() {
                $("P.caption", viewImage).fadeIn("slow");
                thumbsDisabled = false;
            }
			);

        };
    };

    $(function() {
        $("DIV.row").each(function() {
            var highest = 0;
            $("DIV.block-container", this).each(function(i) {
                var height = $(this).height();
                if (highest < height) {
                    highest = height;
                }
            });
            if (jQuery.browser.msie && jQuery.browser.version == "6.0") {
                $("DIV.block-container", this).height(highest);
            }
            else {
                $("DIV.block-container", this).css("min-height", highest);
            }
        });
    });

    ND.fontResizer = function() {
        var selectClass = "selected";
        var fontSize = {
            small: 62.9,
            medium: 72.9,
            large: 82.9
        }
        init();

        function init() {
            injectController();
            checkTextSize();
            wireEvent();
        };

        function injectController() {
            // ND.text.textSize is defined on the page, so it can be translated into another language
            var controllerMarkup = '<div class="font-resizer"><span class="label">' + ND.text.textSize + ':</span><ul><li><a href="#" class="large" title="large">A</a></li><li><a href="#" class="medium" title="medium">A</a></li><li class="selected"><a href="#" class="small" title="small">A</a></li></ul></div>';
            $("#header DIV.search").after(controllerMarkup);
        };

        function wireEvent() {
            $("DIV.font-resizer LI A").live("click", function() {
                var thisClass = $(this).attr("class");
                resizeText(thisClass);
            });
        };

        function resizeText(thisSize) {
            var resizerContainer = $("DIV.font-resizer");
            for (var key in fontSize) {
                if (thisSize == key) {
                    $("body").css("font-size", fontSize[thisSize] + "%");
                    $("LI.selected", resizerContainer).removeClass(selectClass);
                    $("." + thisSize, resizerContainer).parent("LI").addClass(selectClass);
                    $.cookie("fontCookie", thisSize);
                    return;
                } else {
                    $("body").css("font-size", fontSize['small'] + "%");
                }
            }
        };

        function checkTextSize() {
            var fontCookieValue = $.cookie("fontCookie");
            if (fontCookieValue != null) {
                resizeText(fontCookieValue);
            }
        };
    };


	ND.mainBannerRotatorLoader = function()
	{
		var $imageCount = $('.feature-image IMG').length;
		if($imageCount > 1)
		{
	  		setInterval("ND.mainBannerRotator()",8000);	
	    }
	}
	ND.mainBannerRotator = function(){
		var $active = $('.feature-image IMG.active');
	    if ( $active.length == 0 )
	    {
			$active = $('#slideshow IMG:last');
		}
	    // use this to pull the images in the order they appear in the markup
	    // Iterate through the images, if the 'next' image is NULL or 0, start at the first image
	
		var $next;
		if($active.next().hasClass("hero-image-border"))
		{
			$next =  $('.feature-image IMG:first');
		}
		else if ($active.next().length > 0)
		{
			$next = $active.next();
		}
		else
		{
			$next =  $('.feature-image IMG:first');
		}
	
	
	    // uncomment the 3 lines below to pull the images in random order
	    
	    // var $sibs  = $active.siblings();
	    // var rndNum = Math.floor(Math.random() * $sibs.length );
	    // var $next  = $( $sibs[ rndNum ] );
	
	
	    $active.addClass('last-active');
	
	    $next.css({opacity: 0.0}).addClass('active').animate({opacity: 1.0}, 4000, "linear", 
	    	function() {
	        $active.removeClass('active last-active');
	    });
	};

    //slider banner in homepage
    ND.sliderbanner = {
        init: function() {

            var slideritem = jQuery(".hp-slider");
            var len = jQuery(".hp-slider").length - 1;

            var randomitem = jQuery(".feature-image .random input").val() - 1;

            var index = 0;
            var next = 1;
            var pre = len;

            jQuery(slideritem).eq(randomitem).css({ 'display': 'block', 'z-index': 99 })
            //if(len != 0){
            jQuery(".feature-image").mouseover(function() {
                jQuery(".feature-image .btn a").css("display", "block");
            });
            jQuery(".sliderwrap").mouseout(function() {
                jQuery(".feature-image .btn a").css("display", "none");
            });
            //}

            jQuery(".feature-image .btn a.next").click(function(e) {

                jQuery(slideritem).eq(index).fadeOut(5000).css('z-index', 98);
                jQuery(slideritem).eq(next).css('z-index', 99).fadeIn(5000);
                index = index + 1;
                next = next + 1;
                if (index == len) {
                    next = 0;
                };
                if (index > len) {
                    index = 0

                };
                e.preventDefault();

            });

            jQuery(".feature-image .btn a.prev").click(function(e) {
                jQuery(slideritem).eq(index).fadeOut(5000).css('z-index', 98);
                jQuery(slideritem).eq(pre).css('z-index', 99).fadeIn(5000);
                index = index - 1;
                pre = pre - 1;
                if (index == 0) {
                    pre = len;
                };
                if (index < 0) {
                    index = len;

                };
                e.preventDefault();
            });
            //slide autoplay
            setTimeout(ND.sliderbanner.autoplay, 2000);

        },
        //slide autoplay
        autoplay: function() {
            jQuery(".feature-image .btn a.next").trigger('click');
            setTimeout(ND.sliderbanner.autoplay, 5000);

        }

    };

    // On load
    $(function() {
        //ND.secondaryNav();
        ND.sliderbanner.init();
        ND.ieHover();
        ND.anchors.init();
        ND.tabbedContainers.init();
        ND.formatPlaylist();
        ND.sitemapSectionHeight();
        ND.galleryControls();
        ND.fontResizer();
		ND.mainBannerRotator();
		ND.mainBannerRotatorLoader();
        $('a.lightbox').lightBox({
            imageLoading: '/global/lightbox/lightbox-ico-loading.gif',
            imageBtnClose: '/global/lightbox/lightbox-btn-close.gif',
            imageBtnPrev: '/global/lightbox/lightbox-btn-prev.gif',
            imageBtnNext: '/global/lightbox/lightbox-btn-next.gif'
        });
    });

})(jQuery);
