$j(document).ready(function(){	
	$j(".nav ul li").hover(
		function(){
		$j(this).addClass("hover")
		},
		function(){
		$j(this).removeClass("hover")	
		}							
	);
	$j("div#header .search .text").focus(function(){
		if ($j(this).val() == "Search"){
			$j(this).val("");
		}											 
	});
	$j("div#header .search .text").blur(function(){
		if ($j(this).val() == ""){
			$j(this).val("Search");
		}											 
	})
	$j(".print").click(function(){
		window.print();									 
	})
	function jumpMenu(targ,selObj,restore){ 
	  eval(targ+".location='"+selObj.options[selObj.selectedIndex].value+"'");
	  if (restore) selObj.selectedIndex=0;
	}
	$j(".quicklink select").change(function(){
		jumpMenu('parent',this,0)								   
	})
	
	$j('#items').cycle({
		fx: 'fade',
		pager: '.pages'
	});

	// video elements Homepage
	$j("#videoListHomePage").each(function(){
	    $j(this).children(".item:even").each(
    	    function(){
    	     $j(this).wrap('<div class="row"></div>')
	    });
	    $j(this).children(".item").each(
    	    function(){
    	     $j(this).appendTo($j(this).prev(".row"))
	    });
	});
	
	// video elements details page
	$j("#contentVideo").each(function(){
	    $j(this).children(".item:even").each(
    	    function(){
    	     $j(this).wrap('<div class="row"></div>')
	    });
	    $j(this).children(".item").each(
    	    function(){
    	     $j(this).appendTo($j(this).prev(".row"))
	    });
	});
	
	// video elements details page
	$j("#videoresultpanel").each(function(){
	    $j(this).children(".item:nth-child(3n+1)").wrap('<div class="row"></div>');
	    $j(this).children(".item").each(
    	    function(){
    	     $j(this).appendTo($j(this).prev(".row"))
	    });
	    $j(this).children(".item").each(
    	    function(){
    	     $j(this).appendTo($j(this).prev(".row"))
	    });
	});
	
	
	
	$j("#videoListHomePage .image").hover(
		function(){
			$j(this).addClass("hover");
			$j(this).next().children('a').addClass("hover");
		},
		function(){
			$j(this).removeClass("hover");
			$j(this).next().children('a').removeClass("hover");
		}
	);
	
	$j("#videoListHomePage .about a").hover(
                function(){
                        $j(this).addClass("hover");
                        $j(this).parent().prev().addClass("hover");
                },
                function(){
                        $j(this).removeClass("hover");
                        $j(this).parent().prev().removeClass("hover");
                }
        ); 

	$j("#content .latestvideos .detail .caption").hover(
                function(){
                        $j(this).find("p a").addClass("hover");
                        $j(this).find("h4 a").addClass("hover");
                },
                function(){
                        $j(this).find("p a").removeClass("hover");
                        $j(this).find("h4 a").removeClass("hover");
                }
        ); 
		
	$j("body").addClass("has-js");
	
	/*ajax news items behaviours*/
	if(document.getElementById("auto-ajax-page"))
	{
		
		inaction = false;
		timeRefresh = parseInt($j("#auto-ajax-page").attr("rel") * 1000);
		
		//set up for viewall and meltwater text fade ability
		var initID = $j("#auto-ajax-page div.tabs div.tab-items ul li.active a").attr("href").replace("#", "");
		if(initID == "vichealthnews")
		{
			$j("#auto-ajax-page div.ctas a.viewall").addClass("active");
			$j("#auto-ajax-page div.ctas p.neg-mar-top").css("display", "none");
		}
		else
		{
			$j("#auto-ajax-page div.ctas p.neg-mar-top").addClass("active");
			$j("#auto-ajax-page div.ctas a.viewall").css("display", "none");
		}
		
		//set up white overlay box for fade
		var initwidth = $j("#auto-ajax-page div.tab-containers").width();
		var initheight = $j("#auto-ajax-page div.tab-containers").height();
		$j("#auto-ajax-page div.tab-containers").css("position", "relative");
		$j("#auto-ajax-page div.tab-containers").prepend("<div class='overlay'></div>");
		$j("#auto-ajax-page div.tab-containers div.overlay").css("position", "absolute").css("top", "0").css("left", "0").css("width", initwidth+"px").css("height", initheight+"px").css("background-color", "white").css("display", "none");
		
		
		//tab behaviour
		$j("div.latest div.tabs div.tab-items ul li a").click(
			function()
			{			
				//if not in action and not clicked on the already active tab
				if(inaction == false && !($j(this).parents("li").attr("class").match("active")))
				{
					inaction = true;
					id = $j(this).attr("href").replace("#", "");
					
					var path = $j("div.ajax-paging ul li."+id+":first a").attr("href").replace("#", "");
					
					//add active class to the correct paging element
					$j("div.ajax-paging ul li").removeClass("active");
					$j("div.ajax-paging ul li."+id+":first").addClass("active");
					
					//display the correct tab header
					$j(this).parents("ul").children("li").removeClass("active");
					$j(this).parents("li").addClass("active");					
					
					//add active class to vichealth news view all link
					$j("div.controls div.ctas a.viewall").removeClass("active");
					$j("div.controls div.ctas a."+id).addClass("active");
					
					ajaxPageChange(path, id);
										
				}
					
				return false;
			}
		);
		
		//paging behaviour
		$j("div.latest div.ajax-paging ul li a").click(
			function()
			{
				//makesure current clicked paging element isn't already 'active'
				if((!($j(this).parents("li").attr("class").match("active"))) && inaction == false)
				{	
					inaction = true;					
					var path = $j(this).attr("href").replace("#", "");
					
					//add active class to the correct paging element
					$j(this).parents("ul").children("li").removeClass("active");	
					$j(this).parents("li").addClass("active");
					
					//display the right tab header
					//get the tab name from the paging element li
					tab = '#' + $j(this).parents("li").attr("class").replace("active", "").replace(" ", "");
					$j("#auto-ajax-page .tab-items ul li").removeClass("active");					
					$j("#auto-ajax-page .tab-items ul li a").each(
						function()
						{
							if($j(this).attr("href").match(tab))
							{
								$j(this).parents("li").addClass("active");
							}
						}
					);				
					
					var id = $j(this).parents("li").attr("class").replace("active", "").replace(" ", "");
										
					ajaxPageChange(path, id);
				}
					
				return false;
			}
		);
		
		intID = setTimeout("ajaxPageRefresh()", timeRefresh);
	}
	
	
	if(document.getElementById("home-scroll-set"))
	{
		//fix initial display
		$j("#home-scroll-set div.heading div").css("display", "none");
		$j("#home-scroll-set div.heading div:first").css("display", "block");
		//set all the elements outside of the scope expcept the first
		$j("#home-scroll-set div.detail div.set").css("position", "absolute").css("top", $j("#home-scroll-set div.detail div.scope").height()+"px");
		$j("#home-scroll-set div.detail div.set:first").css("top", "0px");
		$j("#home-scroll-set div.controls .playpause").addClass("playing");
		//get scroll pause time
		timeRefresh = $j("div#home-scroll-set").attr("rel") * 1000;
		direction = true;
		logosCurrItem = $j("#home-scroll-set div.detail div.set:first").attr("id");
		
		logosIntID = setTimeout("scrollSet("+timeRefresh+", "+direction+")", timeRefresh);
		
		//assign button behaviours
		$j("#home-scroll-set div.controls .next").click(
			function()
			{
				scrollSet(timeRefresh, true);
				return false;
			}
		);
		
		$j("#home-scroll-set div.controls .prev").click(
			function()
			{
				scrollSet(timeRefresh, false);
				return false;
			}
		);
		
		$j("#home-scroll-set div.controls .playpause").click(
			function()
			{
				if($j(this).attr("class").match("playing"))
				{
					//pause the control
					clearTimeout(logosIntID);
					$j(this).removeClass("playing").addClass("paused");
				}
				else //should be paused so start to play again
				{
					logosIntID = setTimeout("scrollSet("+timeRefresh+", "+direction+")", timeRefresh);
					$j(this).removeClass("paused").addClass("playing");
				}
				
				return false;
			}
		);
		
	}
	
	// hide the side menu when no items
	$j("DIV#sideMenu:not(:has(li))").hide();
	
}); 

//homepage partners vars
var logosinaction = false;
var logosIntID;
var logosCurrItem;

function scrollSet(refreshTime, direction)
{
	if(logosinaction == false)
	{
		//reset the page refresh timeout
		clearTimeout(logosIntID);
		
		logosinaction = true;
		h = $j("#home-scroll-set div.detail div.scope").height();
		if(direction == true)
		{
			//next action to be taken - scroll up
			currItem = logosCurrItem;
			nextItem = $j("#"+currItem).next().attr("id");
			if(!nextItem)
			{
				nextItem = $j("#home-scroll-set div.detail div.set:first").attr("id");
			}
			//make sure the items are at the correct position
			$j("#"+currItem).css("top", "0px");
			$j("#"+nextItem).css("top", h+"px");
			//animate the items
			$j("#"+currItem).animate({top: '-'+h+'px'}, 1000, function(){});
			$j("#"+nextItem).animate({top: '0px'}, 1000,  
				function(){
					logosinaction = false;	
					dir = true;
					if($j("#home-scroll-set div.controls .playpause").attr("class").match("playing"))
					{
						logosIntID = setTimeout("scrollSet("+refreshTime+", "+dir+")", refreshTime);
					}
				}
			);
			//fade in the right heading
			$j("#home-scroll-set div.heading div."+currItem).fadeOut(1000);
			$j("#home-scroll-set div.heading div."+nextItem).fadeIn(1000);
			
			logosCurrItem = nextItem;
		}
		else if(direction == false)
		{
			//prev action to be taken - scroll down
			currItem = logosCurrItem;
			nextItem = $j("#"+currItem).prev().attr("id");
			if(!nextItem)
			{
				nextItem = $j("#home-scroll-set div.detail div.set:last").attr("id");
			}
			//make sure the items are at the correct position
			$j("#"+currItem).css("top", "0px");
			$j("#"+nextItem).css("top", "-"+h+"px");
			//animate the items
			$j("#"+currItem).animate({top: h+'px'}, 1000, function(){});
			$j("#"+nextItem).animate({top: '0px'}, 1000, 
				function(){
					logosinaction = false;	
					dir = true;
					if($j("#home-scroll-set div.controls .playpause").attr("class").match("playing"))
					{
						logosIntID = setTimeout("scrollSet("+refreshTime+", "+dir+")", refreshTime);
					}				
				}
			);
			//fade in the right heading
			$j("#home-scroll-set div.heading div."+currItem).fadeOut(1000);
			$j("#home-scroll-set div.heading div."+nextItem).fadeIn(1000);
			
			logosCurrItem = nextItem;
		}
	}
}


//autoajax pages refresh vars
//handler for if the paging is in animation or not
var inaction;
//the timeout id
var intID;
var timeRefresh;

function ajaxPageChange(path, id)
{
	//reset the page refresh timeout
	clearTimeout(intID);
	//change the page displayed
	//set the height of the news item news listing - getting ready for the animate
	h = $j(".news-listing").height();					
	$j(".news-listing").height(h);
	
	//fade out the news
	$j(".tab-containers .overlay").fadeIn(1500, function(){
		$j(".news-listing .listing").load(path+" #markup", function(){
			//on data return grow shrink the news section as per the height of the new items coming in to display
			var nh = $j(".news-listing .listing").height();
			$j(".tab-containers .overlay").animate({height: nh+'px'}, 1000, function(){});
			$j(".news-listing").animate({height: nh+'px'}, 1000, function(){
				//fade in the news
				$j(".tab-containers .overlay").fadeOut(1500, function(){
					inaction = false;
					intID = setTimeout("ajaxPageRefresh()", timeRefresh);
				});	
			});
		});
	});
	
	
	
	
	if(id == "vichealthnews")
	{
		//if not already displaying do the fade
		if(!($j("#auto-ajax-page div.ctas a.viewall").attr("class").match("active")))
		{
			$j("#auto-ajax-page div.ctas a.viewall").fadeIn(1500, function(){});
			$j("#auto-ajax-page div.ctas p.neg-mar-top").fadeOut(1500, function(){});
		}
	}
	else
	{
		if(!($j("#auto-ajax-page div.ctas p.neg-mar-top").attr("class").match("active")))
		{
			$j("#auto-ajax-page div.ctas p.neg-mar-top").fadeIn(1500, function(){});
			$j("#auto-ajax-page div.ctas a.viewall").fadeOut(1500, function(){});
		}
	}
			
}

function ajaxPageRefresh(id)
{
	inaction = true;
	//get the path of the new news to be displayed
	var path;
	var el;
	if($j(".paging ul li.active").next().length > 0)
	{
		el = $j(".paging ul li.active").next();
	}
	else
	{
		el = $j(".paging ul li:first");
	}
	path = el.children("a").attr("href").replace("#", "");
	$j(".paging ul li").removeClass("active");
	el.addClass("active");
	
	//display the correct tab
	tab = '#' + el.attr("class").replace("active", "").replace(" ", "");
	$j("#auto-ajax-page .tab-items ul li").removeClass("active");					
	$j("#auto-ajax-page .tab-items ul li a").each(
		function()
		{
			if($j(this).attr("href").match(tab))
			{
				$j(this).parents("li").addClass("active");
			}
		}
	);			
	var id = el.attr('class').split(' ').slice(0,1);
    $j("div.controls div.ctas a.viewall").removeClass("active");
	$j("div.controls div.ctas a."+id).addClass("active");
	ajaxPageChange(path, id);
	
}



if(!window.ND){window.ND={};window.NextDigital=window.ND;}
/* 2008/01/10 - ND.addLoadListener v0.82 - Glenn Baker */
ND.addLoadListener=function(fn){if(typeof window.addEventListener!='undefined'){window.addEventListener('load',fn,false);}else if(typeof document.addEventListener!='undefined'){document.addEventListener('load',fn,false);}else if(typeof window.attachEvent!='undefined'){ window.attachEvent('onload',fn);}else{var oldfn=window.onload;if(typeof window.onload!='function'){window.onload=fn;}else{window.onload=function(){oldfn();fn();};}}};
/* 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);};}};
/* 2007/12/05 - ND.classFunctions v0.92 - Glenn Baker - includes addClass, removeClass, hasClass, toggleClass and replaceClass */
ND.classFunctions={addClass:function(t, c){var p=new RegExp("(^|)"+c+"(|$)");if(!p.test(t.className)){if(t.className==""){t.className=c;}else{t.className+=" "+c;}}return true;},removeClass:function(t, c){var removedClass=t.className;var p=new RegExp("(^|)"+c+"(|$)");removedClass=removedClass.replace(p, "$1");removedClass=removedClass.replace(/$/, "");t.className=removedClass;return true;},replaceClass:function(t, prec, c){removeClass(t,prec);addClass(t,c);},toggleClass:function(t, c){if(hasClass(t,c)){removeClass(t,c);}else{addClass(t,c);}},hasClass:function(t, c){var p=new RegExp("(^|)"+c+"(|$)");return p.test(t.className);},init:function(){for(n in this){window[n]=this[n]}}};ND.classFunctions.init();

var	sumLiWidth = 0;
var numLi = 0;

var setIEHovers = function(list) {
	var listItems = list.getElementsByTagName("li");

	for(var k=0; k < listItems.length; k++) {
		if (hasClass(listItems[k],"first-nav")){
			var node = listItems[k];
			node.onmouseover=function() {this.className+=" hover";}
			node.onmouseout=function() {this.className=this.className.replace(" hover", "");}
		}
	}
}

var hoverIE = function() {
	// IE6 only
	//if(window.ActiveXObject && (window.XMLHttpRequest == undefined)) {
		var ul_array = document.getElementsByTagName("ul");
		for (var i=0; i < ul_array.length; i++) {
			if(ul_array[i].parentNode.className == 'navigation') {
				setIEHovers(ul_array[i]);
			}
		}
	//}
}

ND.anchors.setPopupDimensions(619,320);

/* Overlabels */
var hideLabel = function(field_id, hide){
	var field_for;
	var labels = document.getElementsByTagName('label');
	for (var i = 0; i < labels.length; i++) {
		field_for = labels[i].htmlFor || labels[i].getAttribute('for');
		if (field_for == field_id && hasClass(labels[i],"overlabel-apply")) {
			labels[i].style.textIndent = (hide) ? '-9999px' : '0px';
			return true;
		}
	}
};

var initOverLabels = function(){
	if (!document.getElementById) return;  	
	var labels, id, field;
	labels = document.getElementsByTagName('label');
	for (var i=0; i < labels.length; i++) {
	    if (labels[i].className == 'overlabel') {
			id = labels[i].htmlFor || labels[i].getAttribute('for');
			if (!id || !(field = document.getElementById(id))){continue;}
			labels[i].className = 'overlabel-apply';		
			if (field.value !== ''){hideLabel(field.getAttribute('id'), true);}
			field.onfocus = function(){
			    hideBothField(this.getAttribute('id'));
			    hideLabel(this.getAttribute('id'), true);
			};
			
			field.onblur = function(){
			    checkPassword(this.getAttribute('id'));
				if(this.value === ''){
					hideLabel(this.getAttribute('id'), false);
				}
			};
			labels[i].onclick = function(){
				var id, field;
				id = this.getAttribute('for');
				if(id && (field = document.getElementById(id))) {
					field.focus();
				}
			};
		}
	}
};

var checkPassword = function(currentFieldID)
{
    if(currentFieldID == emailID || currentFieldID == passwordID)
    {
        emailField = document.getElementById(emailID);
        passwordField = document.getElementById(passwordID);
        
        if(emailField.value != '')
        {
            hideLabel(emailField, true);
        }
        
        if(passwordField.value != '')
        {
            hideLabel(passwordField, true);
        }
        
        if(emailField.value == '' && passwordField.value == ''){
            hideLabel(passwordID, false);
            hideLabel(emailID, false);
        }
    }
};

var hideBothField = function(currentFieldID)
{
    if(currentFieldID == emailID || currentFieldID == passwordID)
    {
        hideLabel(emailID, true);
        hideLabel(passwordID, true);
    }
};

/*Boxes floated on home page*/
var floatedBox = function(){
if (!document.getElementById('boxes-variable')) return;

var div_array = document.getElementById('boxes-variable').getElementsByTagName('DIV');

// get the max height of boxes
var max_height = 0;
var height = 0;
for (i=0; i< div_array.length; i++) {
		height = div_array[i].offsetHeight;
		if (height > max_height)
			max_height = height;
}

for (i=0; i< div_array.length; i++) {
	div_array[i].style.height = max_height + 'px';
}

}


/* Change background color of webparts */

var webpartsHoverIE = function() {
	// IE6 only
	if(window.ActiveXObject && (window.XMLHttpRequest == undefined)) {
	    if (document.getElementById('web-parts') != null){
			var table_array = document.getElementById('web-parts').getElementsByTagName("table");
			for (var i=0; i < table_array.length; i++) {
				var node = table_array[i];
				node.onmouseover=function() {this.className+=" webpart-hover";}			
				node.onmouseout=function() {this.className=this.className.replace(" webpart-hover", "");}
			}
		}
	}
}

var myInit = function(){hoverIE();ND.anchors.init();initOverLabels();floatedBox();webpartsHoverIE();contentImg();tooltipImg();};
ND.addLoadListener(myInit);

function openLink(id)
{
    var ddlQuickLink = document.getElementById(id);
    var selectedIndex = ddlQuickLink.selectedIndex;
    var selectedValue = ddlQuickLink.options[selectedIndex].value;
    
    var tokens = selectedValue.split(";");
    
    if(tokens[0] == "i")
    {
        window.location = tokens[1];
    }
    else
    {
        window.open(tokens[1]);
    }
}

function onEnterpress(e, id)
{
    //define any varible
    var KeyPress 

    //if which property of event object is supported 
    if(e && e.which)
    {
        e = e
        //character code is contained in NN4's which property
        KeyPress = e.which
    }
    else
    {
        e = event
        KeyPress = e.keyCode
    }
    //13 is the key code of enter key
    if(KeyPress == 13)
    {
        $j(id)[0].click();
        return false    
    }
    else
    {
        return true
    }
}

var contentImg = function(){
                var div_array = document.getElementsByTagName("div");
                for (i=0; i<div_array.length; i++){
                                if(hasClass(div_array[i],"content-img")){
                                                if(div_array[i].getElementsByTagName("img")[0])
                                                    var width = div_array[i].getElementsByTagName("img")[0].offsetWidth;
                                                if(div_array[i].getElementsByTagName("p")[0])
                                                    div_array[i].getElementsByTagName("p")[0].style.width = width-20 +'px';
                                }
                }
}

var tooltipImg = function() {
var img = $j('img');
if(img != null)
	img.attr('title', function()
	{
		return $j(this).attr('alt');
	});
}


