/*! Global JS - isader */
if(!window['ND']){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() {
	 if ($.browser.msie && $.browser.version.substr(0,3) == "6.0") {
		 	 
		 	function over() {
				$(this).addClass("hover");
			};
			
			function out() {
				$(this).removeClass("hover");
			};
			$("#nav LI.dropdown:has(UL li)").hoverIntent({interval:0, sensitivity:2, timeout:0, over:over, out:out});
			
		}
	
	};
	
	// 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.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();
			}
			if(playlist.size() > 0) {
				playlistInit();
			}
		};
		
		function thumbnailsInit() {
			var list = $(thumbnails).find("UL");
			$("DIV.multimedia-gallery").addClass("has-js");
			var isOverlay = $("UL LI.selected", playlist).find("SPAN.overlay").size();
			if(isOverlay <= 0) {
				$("LI.selected A.thumbnail", list).append('<span class="overlay"></span>');
			};
			$(thumbnails).removeClass("scroll").append('<div class="controls"><a class="prev" title="previous" href="#"><span class="accessible">Previous</span></a><a class="next" title="next" href="#"><span class="accessible">Next</span></a></div>').children("UL").wrap('<div class="thumbs-container"></div>');
			$(list).children("LI").each(function(i){
				if(i == 0) {
					liWidth = $(this).innerWidth();
				}
				ulWidth +=$(this).innerWidth();
			});
			$(list).width(ulWidth);
			thumbnailsEvents();
		};
		
		function thumbnailsEvents() {
			$(thumbnails).find("A.prev").bind("click", function(){
				if(!buttonDisabled) {
					buttonDisabled = true;
					scrollThumbnailsBy(100,4);
				}
				return false;
			});
			
			$(thumbnails).find("A.next").bind("click", function(){
				if(!buttonDisabled) {
					buttonDisabled = true;
					scrollThumbnailsBy(-100,4);
				}
				return false;
			});
			
			$("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);
					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}, 100).animate({
				opacity: 0.6,
				height: height+20},500).animate({opacity: 0.7}, 100, null, function(){
					$("P.caption", viewImage).fadeIn("slow");
					thumbsDisabled=false;
				}
			);
		};
		
		function scrollThumbnailsBy (gap, numberOfItemsShown) {
			var list = $(thumbnails).find("UL");
			var left = $(list).css("left");
			left = left.substr(0,left.indexOf('p'));
			var newPosition = (left * 1 + gap);
			$(list).animate({left:newPosition + "px"}, function(){
				var left = $(list).css("left");
				left = left.substr(0,left.indexOf('p'));
				var position = (ulWidth - (numberOfItemsShown * liWidth)) * -1;
				if(position >= left) {
					$(this).animate({left:position+"px"}, function(){buttonDisabled = false;});
					$(this).css("left","");
				}
				else if(newPosition >= 0) {
					$(this).animate({left:"0px"}, function(){buttonDisabled = false;});
				}
				else {
					buttonDisabled = false;
				}
			});
			$(list).css("right","");
		};
		
		function playlistInit() {
			$("DIV.list",playlist).removeClass("scroll");
			$(playlist).removeClass("scroll").children("H3").after('<div class="controls"><a class="prev" title="previous" href="#"><span class="accessible">Previous</span></a><a class="next" title="next" href="#"><span class="accessible">Next</span></a></div>').children("UL");
			var isOverlay = $("UL LI.selected", playlist).find("SPAN.overlay").size();
			if(isOverlay <= 0) {
				$("UL LI.selected A.album-thumbnail", playlist).append('<span class="overlay"></span>');
			};
			$("DIV.list UL",playlist).children("LI").each(function(i){
				if(i == 0) {
					liHeight = $(this).innerHeight();
				}
				ulHeight +=$(this).innerHeight();
			});
			$("DIV.list UL",playlist).height(ulHeight);
			playlistEvents();
		};
		
		function playlistEvents() {
			$(playlist).find("A.prev").bind("click", function(){
				if(!buttonDisabled) {
					buttonDisabled = true;
					scrollPlaylistBy(100,3);
				}
				return false;
			});
			
			$(playlist).find("A.next").bind("click", function(){
				if(!buttonDisabled) {
					buttonDisabled = true;
					scrollPlaylistBy(-100,3);
				}
				return false;
			});
		};
		
		function scrollPlaylistBy (gap,numberOfItemsShown) {
			var list = $(playlist).find("UL");
			var top = $(list).css("top");
			top = top.substr(0,top.indexOf('p'));
			var newPosition = (top * 1 + gap);
			$(list).animate({top:newPosition + "px"}, function(){
				var top = $(list).css("top");
				top = top.substr(0,top.indexOf('p'));
				var position = (ulHeight - (numberOfItemsShown * liHeight)) * -1;
				if(position >= top) {
					$(this).animate({top:position+"px"}, function(){buttonDisabled = false;});
					$(this).css("top","");
				}
				else if(newPosition >= 0) {
					$(this).animate({top:"0px"}, function(){buttonDisabled = false;});
				}
				else {
					buttonDisabled = false;
				}
			});
			$(list).css("right","");
			
			
		};
	};
	
	/** 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++;
		});
	};

	
	$(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.links").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.resetImgSpace = function() {
        $("DIV.primary DIV.mainContent IMG[hspace!='']").each(function(i, obj) {
            $(this).css("margin-right", $(this).attr("hspace") + "px");
        });
    }

	// On load
	$(function() {
		ND.primaryNav();
		//ND.secondaryNav();
		ND.ieHover();
		ND.anchors.init();
		ND.tabbedContainers.init();
		ND.galleryControls();
		ND.sitemapSectionHeight();
		ND.fontResizer();
        ND.resetImgSpace();
	});

})(jQuery);
