$(function(){
	browser(); 
	fontResizer();
	$('#nav > li').hover(function(){
		$(this).addClass('hover').children('ul').addClass('hover');
	},function(){
		$(this).removeClass('hover').children('ul').removeClass('hover');
	});
	
	// <select> that are graphics
	var graphicalSelect = $('select.graphical');
	if(graphicalSelect.length){gSelect();}
	
	//Tabs
	var tab = $('.theTabs');
	if(tab.length){tabs();}
	
	// fix float issues with margins and even columns heights audience portal
	var $thePortlets = $('#thePortlets');
	if($thePortlets.length){fixPortlets($thePortlets);}
		
	// Table of Contents scroller
	var $toc = $('#toc');
	if($toc.length){toc();}
	
	if($('#content').hasClass('noNav') == true){
		$('#backToTop').addClass('noNav');	
	}
	$('#backToTop').click(function(){scrollIt($('#top'));return false;});
	
	
	var $collapsable = $('#collapsable');
	if($collapsable.length){
		$('a.expandAll').click(function(){
			$('.toggleSection').slideDown();
			$('h3.main').addClass('opened').children('a').addClass('close');
			return false;
		});
		
		$('a.collapseAll').click(function(){
			$('.toggleSection').slideUp();
			$('h3.main').removeClass('opened').children('a').removeClass('close');
			return false;
		});
		
		$('a.toggleOpen').click(function(){
			if($(this).closest('h3').hasClass('opened') == true){
				$(this).removeClass('close').closest('h3').removeClass('opened').next('.toggleSection').slideUp();
			}else{
				$(this).addClass('close').closest('h3').addClass('opened').next('.toggleSection').slideDown();
			}
			return false;
		});
	}
	
	
	
	swapValues = [];
    $(".swap").each(function(i) {
        swapValues[i] = $(this).val();
        $(this).focus(function() {
            if ($(this).val() == swapValues[i]) {
                $(this).val("");
            }
        }).blur(function() {
            if ($.trim($(this).val()) == "") {
                $(this).val(swapValues[i]);
            }
        });
    });
	
	var $pp = $('a[rel^="prettyPhoto"]');
		if($pp.length){
			$pp.prettyPhoto({
				deeplinking: false,
				social_tools:false
			});
		}

	
	$('table tr:last-child').addClass('lastChild');
	$('h2.alt+div.portlet').addClass('portletAfterAlt');
	$('#nav1 li:first-child, #nav2 li:first-child,#nav3 li:first-child,#nav4 li:first-child,#nav5 li:first-child,#nav6 li:first-child,#nav7 li:first-child').addClass('fc');
	$('#nav1 li:last-child, #nav2 li:last-child,#nav3 li:last-child,#nav4 li:last-child,#nav5 li:last-child,#nav6 li:last-child,#nav7 li:last-child, #footer .links a:last-child').addClass('lc');
	$('.toc+.pagination').addClass('docPaginate');
	$('.toc a+a.title').addClass('n1Title');
	$('#searchResults .result:last').addClass('lastResult');
	$('#sectionNav ul li:last-child').addClass('lastChild');
	var $tableStandard = $('table.standard');
	if($tableStandard.length){
		$('table.standard tr td:first-child, table.standard tr th:first-child').addClass('first');
		$tableStandard.each(function(){
			
			if($(this).children('thead').length == 0){
				$(this).children('tbody').children('tr:first-child').addClass('noThead');	
			}
		});
	}
	var $theTools = $('#tools');
	$('a.emailPage', $theTools).click(function(){
		$('.stButton').trigger('click');
		return false;
	});
	$('a.printPage', $theTools).click(function(){
		window.print()
		return false;
	});
});

// Timers
jQuery.timer = function(time, func, callback) {
	var a = { timer: setTimeout(func, time), callback: null }
	if (typeof (callback) == 'function') { a.callback = callback; }
	return a;
};

jQuery.clearTimer = function(a) {
	clearTimeout(a.timer);
	if (typeof (a.callback) == 'function') { a.callback(); };
	return this;
};

//Table of Contents

function toc(){
	var $toc1a = $('.toc .col1 a');
	var $toc2a = $('.toc .col2 a');
	var $articles = $('#contents .article');
	
	var toc1L = $toc1a.length;
	var toc2L = $toc2a.length;
	var articlesL = $articles.length;
	
	
	$articles.eq(0).addClass('activeArticle');
	$toc1a.eq(0).addClass('current');	
	
	
	$('h2.toc a').click(function(){
		$(this).toggleClass('close').parent().next('.toc').slideToggle();
		return false;
	});
	var contents = $('#contents');
	$toc1a.click(function(){
		var $this = $(this);
		var which = $this.prevAll().length;
		$articles.eq(which).addClass('activeArticle').siblings().removeClass('activeArticle');
		$this.addClass('current').siblings().removeClass('current');
		$toc2a.removeClass('current');
		scrollIt(contents);
		return false;
		
	});
	
	$toc2a.click(function(){
		var $this = $(this);
		var which = $this.prevAll().length + toc1L;
		$articles.eq(which).addClass('activeArticle').siblings().removeClass('activeArticle');
		$this.addClass('current').siblings().removeClass('current');
		$toc1a.removeClass('current');
		scrollIt(contents);
		return false;
	});
	
	$('.pagination .prev').click(function(){
		var $current = $articles.filter('.activeArticle')
		var which = $current.prevAll().length;
		if(which == 0){
			$articles.last().addClass('activeArticle').siblings().removeClass('activeArticle');
		}else{
			$current.removeClass('activeArticle').prev().addClass('activeArticle');
		}
		var $whichCol = $('.col a').filter('.current');
		var whichOne = $whichCol.prevAll().length;
		if($whichCol.closest('.col').hasClass('col1') == true){
			var activeCol = 1;
		}else{
			var activeCol = 2;
		}
		
		if(whichOne == 0){
			$whichCol.removeClass('current');
			if(activeCol == 1){
				$toc2a.last().addClass('current');	
			}else{
				$toc1a.last().addClass('current');	
			}
		}else{
			$whichCol.prev().addClass('current').siblings().removeClass('current');
		}
		return false;
	});
	
	$('.pagination .next').click(function(){
		var $current = $articles.filter('.activeArticle')
		var which = $current.prevAll().length;
		var RA = articlesL -1;
		if(which == RA){
			$articles.eq(0).addClass('activeArticle').siblings().removeClass('activeArticle');
		}else{
			$current.removeClass('activeArticle').next().addClass('activeArticle');
		}
		var $whichCol = $('.col a').filter('.current');
		var whichOne = $whichCol.prevAll().length;
		
		if($whichCol.closest('.col').hasClass('col1')==true){
			if(whichOne == (toc1L-1)){
				$whichCol.removeClass('current');
				$toc2a.eq(0).addClass('current');	
			}else{
				$whichCol.next().addClass('current').siblings().removeClass('current');
			}
		}else{
			if(whichOne == (toc2L-1)){
				$whichCol.removeClass('current');
				$toc1a.eq(0).addClass('current');	
			}else{
				$whichCol.next().addClass('current').siblings().removeClass('current');
			}
		}
		
		return false;
	});
	
}


//Tabs
function tabs(){
	var url = window.location.toString();
	var theQuery = url.split('?');
	if(theQuery.length > 1){
		var whichTab = theQuery[1].split('activetab=');
		if(whichTab.length> 1){
			activeTab = whichTab[1] - 1;
			$('.theTabs a').eq(activeTab).addClass('current').siblings().removeClass('current').closest('.tabs').next('.tabContent').children('.tab').eq(activeTab).addClass('activeTab').siblings().removeClass('activeTab');
			
		}
	}
	$('.theTabs a').click(function(){
		var $this = $(this);
		var which = $this.prevAll().length;
		$this.addClass('current').siblings().removeClass('current').closest('.tabs').next('.tabContent').children('.activeTab').removeClass('activeTab').parent().children('.tab').eq(which).addClass('activeTab');
		
		return false
	});
}


//Smooth Scrolling
function scrollIt(where){
		$('html,body').animate(
			{scrollTop: where.offset().top},
			500
		  );	
	}



function gSelect(){
	var $gs = $('select.graphical')
	//var htmlString = '<div class="selectBox"><div class="selectArea"></div><div class="selectButton"></div><div class="optionsBottom"><div class="options"></div></div>'
	
	
	$gs.each(function(){
		
		var theString = "";
		var theTitle = "";
		var count = 0;
		$(this).children().each(function(){
			
			if(count === 0){
				theString += "<a href'#' class='selected'>"+$(this).text()+"</a>";
				theTitle = $(this).text();
			}else{
				theString += "<a href'#'>"+$(this).text()+"</a>";	
			}
			count += 1;
		});
		var htmlString = '<div class="selectBox"><div class="selectArea">'+ theTitle+'</div><div class="selectButton"></div><div class="optionsBottom"><div class="options">'+theString+'</div></div>'
		
			//alert($(this).children('option:selected').prevAll().length);	
		/*  */
		
		$(htmlString).insertAfter($(this));
		if($(this).children('option:selected').prevAll().length > 0){
		
		var oldSelected = 0;
		var newSelected = $(this).children('option:selected').prevAll().length;
		var diff = (oldSelected - newSelected) * 22.3;
		var $this = $(this).next('.selectBox').children('.optionsBottom').children('.options').children('a').eq(newSelected);
		
		$this.addClass('selected').siblings().removeClass('selected').closest('.selectBox').children('.selectArea').text($this.text()).addClass('selectAreaselected').removeClass('selextAreaOpen');
		$this.closest('.optionsBottom').hide().removeClass('open').animate({
			marginTop: '+='+diff
			}, 1000);
		
		whichSelect = $this.closest('.selectBox').prev('select');
		
		}
		/*  */
		
		
	});
	
	$('.selectBox').click(function(){
		$('.zindex').removeClass('zindex');
		$(this).addClass('zindex').parent().addClass('zindex');
	});
	
	$('.selectArea, .selectButton').click(function(){
		var whichOne = $(this).parent().children('.optionsBottom');
		var sa = $(this).parent().children('.selectArea');
		if(whichOne.hasClass('open')==true){
			whichOne.hide().removeClass('open');
			sa.removeClass('selextAreaOpen');
			$('.multiSelect').css('visibility', 'visible');	
		}else{
			whichOne.show().addClass('open');
			$('.selextAreaOpen').removeClass('selextAreaOpen').parent().children('.optionsBottom').removeClass('open').hide();	
			sa.addClass('selextAreaOpen');
			
			if($('html').hasClass('msie6') == true){
				$('.multiSelect').css('visibility', 'hidden');	
			}
		}
	});
	
	$('.optionsBottom a').click(function(){
		var $this = $(this);
		var oldSelected = $this.parent().children('.selected').prevAll().length;
		var newSelected = $this.prevAll().length;
		var diff = (oldSelected - newSelected) * 22.3;
		$this.addClass('selected').siblings().removeClass('selected').closest('.selectBox').children('.selectArea').text($this.text()).addClass('selectAreaselected').removeClass('selextAreaOpen');
		$this.closest('.optionsBottom').hide().removeClass('open').animate({
			marginTop: '+='+diff
			}, 1000);
		
		whichSelect = $this.closest('.selectBox').prev('select');
		whichSelect.children('option:selected').removeAttr('selected');
		whichSelect.children('option').eq(newSelected).attr('selected', 'selected');
		return false;
	});
	
	triggerIt = function(){
		
	}
}


function fixPortlets($thePortlets){
	var hasVideo = false;
	var $isVideo = $('.video', $thePortlets);
	var $portlets = $('.portlet', $thePortlets);
	if($isVideo.length){hasVideo = true;}
	if(hasVideo == true){
		var videoHeight = $isVideo.height();
		var theHeights = $portlets.eq(1).height() + $portlets.eq(2).height() + parseInt($portlets.css('margin-top'));
		if(videoHeight == theHeights){
			
		}else if(videoHeight<theHeights){
			var diff = theHeights-videoHeight;
			var vidPadding = parseInt($isVideo.children('.content').css('padding-bottom')) + diff - 1;
			$isVideo.children('.content').css('padding-bottom',vidPadding);	
		}else{
			var diff = videoHeight - theHeights;
			var portPadding = parseInt($portlets.children('.content').css('padding-bottom')) + (diff/2) ;
			$portlets.eq(1).children('.content').css('padding-bottom', portPadding);
			$portlets.eq(2).children('.content').css('padding-bottom', portPadding);
		}
		$portlets.eq(2).after('<div style="clear:both"></div>');
		
		$('.portlet').slice(3).filter(':odd').each(function(){
			makeItEqual($(this));
		});
	}else{
		$('.portlet:odd', $thePortlets).each(function(){
			//var $this = $(this);
			makeItEqual($(this));
		});
	}
}

function makeItEqual($this){
	$this.addClass('nrm');
	var myHeight = $this.height();
	var prevHeight = $this.prev().height();
	if(myHeight < prevHeight){
		var diff = prevHeight - myHeight;
		var pad = parseInt($this.children('.content').css('padding-bottom')) + diff;
		$this.children('.content').css('padding-bottom', pad);
	}else{
		var diff = myHeight - prevHeight;
		var pad = parseInt($this.prev().children('.content').css('padding-bottom')) + diff;
		$this.prev().children('.content').css('padding-bottom', pad);
	}
}




//adds classes to html and body for browser/version & os
(function($){$.browserTest=function(a,z){var u='unknown',x='X',m=function(r,h){for(var i=0;i<h.length;i=i+1){r=r.replace(h[i][0],h[i][1]);}return r;},c=function(i,a,b,c){var r={name:m((a.exec(i)||[u,u])[1],b)};r[r.name]=true;r.version=(c.exec(i)||[x,x,x,x])[3];if(r.name.match(/safari/)&&r.version>400){r.version='2.0';}if(r.name==='presto'){r.version=($.browser.version>9.27)?'futhark':'linear_b';}r.versionNumber=parseFloat(r.version,10)||0;r.versionX=(r.version!==x)?(r.version+'').substr(0,1):x;r.className=r.name+r.versionX;return r;};a=(a.match(/Opera|Navigator|Minefield|KHTML|Chrome/)?m(a,[[/(Firefox|MSIE|KHTML,\slike\sGecko|Konqueror)/,''],['Chrome Safari','Chrome'],['KHTML','Konqueror'],['Minefield','Firefox'],['Navigator','Netscape']]):a).toLowerCase();$.browser=$.extend((!z)?$.browser:{},c(a,/(camino|chrome|firefox|netscape|konqueror|lynx|msie|opera|safari)/,[],/(camino|chrome|firefox|netscape|netscape6|opera|version|konqueror|lynx|msie|safari)(\/|\s)([a-z0-9\.\+]*?)(\;|dev|rel|\s|$)/));$.layout=c(a,/(gecko|konqueror|msie|opera|webkit)/,[['konqueror','khtml'],['msie','trident'],['opera','presto']],/(applewebkit|rv|konqueror|msie)(\:|\/|\s)([a-z0-9\.]*?)(\;|\)|\s)/);$.os={name:(/(win|mac|linux|sunos|solaris|iphone)/.exec(navigator.platform.toLowerCase())||[u])[0].replace('sunos','solaris')};if(!z){$('html').addClass([$.os.name,$.browser.name,$.browser.className,$.layout.name,$.layout.className].join(' '));}};$.browserTest(navigator.userAgent);})(jQuery);
browser = function(){

            var OSName="Unknown OS";
            var browser = "";
            if (navigator.appVersion.indexOf("Mac")!=-1) OSName="Mac";
            if (navigator.appVersion.indexOf("Win")!=-1) OSName="PC";
            bodyClass = $.browser.className+OSName
            $("body").addClass(bodyClass);
//
}

function fontResizer(){
	var maxEnlarge = 5;
	var curEnlarge = 0;
	var baseSize = 62.5;
	var increaseSize = 2.5;
	
	/*
	function clearSelected() { 
		$("a#smallFont").removeClass("currFont"); 
		$("a.smaller").removeClass("currFont"); 
		$("a.larger").removeClass("currFont"); 
		$("body").removeClass("smallFont").removeClass("medFont").removeClass("largeFont");
	}
	*/

	function saveState(curSize) {	
		var date = new Date(); date.setTime(date.getTime()+(7*24*60*60*1000)); 
		var expires = "; expires="+date.toGMTString(); 
		document.cookie = "fontSizer"+"="+curSize+expires+"; path=/"; 
	}
	
	
	
	$("a.smaller").click(function(){ 
		if(curEnlarge > 0){
			curEnlarge--;
			setTheSize(curEnlarge);
		}
		 return false;
	});
	
	$("a.larger").click(function(){
		if(curEnlarge < maxEnlarge){
			curEnlarge++;
			setTheSize(curEnlarge);
		}		
		return false;
	});
	
	function setTheSize(theEnlarge){
		var theSize = ((theEnlarge * increaseSize) + baseSize) + "%";
		$('body').css('font-size', theSize);
		saveState(theEnlarge); 
	}

	function getCookie(c_name) { 
		if (document.cookie.length>0) { 
			c_start=document.cookie.indexOf(c_name + "="); 
			if (c_start!=-1) { 
				c_start=c_start + c_name.length+1; 
				c_end=document.cookie.indexOf(";",c_start); if (c_end==-1) c_end=document.cookie.length; 
				return unescape(document.cookie.substring(c_start,c_end)); 
			} 
		} 
		return ""; 
	}
	var savedSize = getCookie('fontSizer');
	if (savedSize!="") { 
		setTheSize(savedSize);
	}
}
