/*
	
	Project Name Global Javascript Functions
	By  - ISITE Design

*/

// jquery no conflict. use $j or jQuery outside of ready function
var $j = jQuery.noConflict(); 


// jQuery document ready
jQuery(function($) {

	// JS enabled
	$('html').addClass('js');
	$("#tertiary ul.events").find("li:first").addClass('first');
	$("#tertiary ul.events").find("li:last").addClass('last');
	$("ul#nav ").find("li:last").addClass('last');
	$(".copyright").find("li:last").addClass('last');
	
	// Pull the label, make lowercase, set as default value and hide it
	$("#search-form input").inputSetter(1);
	
	// Reset all form elements to default, clear the fields 
	$("#clear").click(function(){
		$("form").each(function() {
		this.reset();
		});
	});
	
	// Few setups for IE6
	if(document.all){
		//add class to drop downs and buttons 
	    $('#nav li, button').hover(
			function() { $(this).addClass('over'); },
			function() { $(this).removeClass('over'); }
	    );
	}// if document.all
	
	// activate tabs
	$('.tabs').IX_tabs();
		
	// faq expand/collapse
	AU.enableExpand("dl.collapsible");
	
	// activate slider
	AU.enableSlider(".slider");
	
	// activate accordion
	AU.enableAccordion("#accordion");
	
	// activate accordion
	AU.enableFilter(".content-filter");
	
	
	//$("a[@href$=pdf]").addClass("pdf");
	$("a[href$='.pdf']").addClass("pdf");

	//Add .external to link in order to display icon & to add target="_blank" 
	$('a').filter(function() {
		//Compare the anchor tag's host name with location's host name
	    return this.hostname && this.hostname !== location.hostname;
	  }).addClass("external").attr("target", "_blank");
	//You might also want to set the _target attribute to blank
	/*
	$('a').filter(function() {
		//Compare the anchor tag's host name with location's host name
	    return this.hostname && this.hostname !== location.hostname;
	  }).addClass("external").attr("target", "_blank");
	*/



});// document ready

// application logic
var AU = {
	// create open/close. receives dl.
	enableExpand : function(el) {
		
		if(!$j(el).length) { return; }
		
		$j(el).find("dd").hide();
		$j(el).find("dt").prepend('<span class="state">+</span> ').wrapInner('<a href="#"></a>').click(function(){
			var textinsert = $j("span.state",this).text() == "+" ? "-" : "+";
			$j(this).toggleClass("open").next("dd").slideToggle("fast").end().find("span.state").text(textinsert);	
			return false;
		});	
		
		var showtext = { show : "Show All", hide : "Hide All" };
		$j('<a class="revealer show" href="#">'+showtext.show+'</a>').insertBefore(el).click(function(){		
			var action = $j(this).is(".show");
			$j(this).next("dl.collapsible").find(action ? "dt:not(.open)" : "dt.open").click().end().end().toggleClass("show").toggleClass("action-hide").text(showtext[action ? "hide" : "show"]);	
			return false;
		});
		
	},
	
	// create create sliders. receives a div selector.
	enableSlider : function(el) {
		
		if(!$j(el).length) { return; }
		
		var	maxitems = 7,
			$obj = $j(el),
			moveList = function(e) {
			
						// action bound to click of prev/next buttons
						// items stored in $slider.data are set in the initialization code outside of this function			
						var $this = $j(this),
							next = $this.is('.next'), // bool to determine which way we are going
							$slider = $this.parents('.slider');
							$ul = $slider.find('.slider-tabs ul');
							current = $slider.data('screen'); 
						
						// bail if nowhere to go or busy already
						if($this.is('.disabled') || $ul.queue().length > 0) { return false; }
											
						var width = $slider.data('clip-width'),
							position = parseInt($ul.css('left')),
							gotopos; // placeholder for conditional result
							
							// set new position and current screen based on which direction moving
							if(next) {
								gotopos = (position - width)+'px';
								current++;
							} else {
								gotopos = (position + width)+'px';
								current--;
							}
					
						$slider.data('screen',current);	
											
						$ul.animate({left:gotopos},400,'swing',function(){
											
							var $next = $slider.find('.next'),
								$prev = $slider.find('.previous');
							
							// if last screen
							if(current==$slider.data('screens')) {
								$next.addClass('disabled');
								$prev.removeClass('disabled');
							}
							// if first screen
							if(current==1) {
								$prev.addClass('disabled');
								$next.removeClass('disabled');
							}
							// if not first and not last
							if(current!=1 && current!=$slider.data('screens')) {
								$next.removeClass('disabled');
								$prev.removeClass('disabled');								
							}
						
						});	
						
						// activate first tab in visible screen
						$slider.find('.slider-tabs a').eq((current-1)*maxitems).click();
						
						return false;
					},				
			$btn = $j('<a href="#"></a>').addClass('btn-nav').bind('click',moveList); // previous/next button obj
			
		// set up each slider
		$obj.each(function() {
						  
			var $this = $j(this);
									
			// make all the content blocks the same height before invoking tabs
			var autoheight = AU.maxHeight($this.find('div.item'));
			$this.find('div.item').css({height:autoheight+"px"});
			
			// activate tabs
			$this.find('.slider-tabs ul').IX_tabs();
						  
			// add prev/next nav if needed and calculate screen data			  
			if($this.find('.slider-tabs li').length > maxitems) {
				$this.find('.slider-tabs').append($btn.text('Previous').addClass('previous').addClass('disabled')).append($btn.clone(true).text('Next').addClass('next').removeClass('previous disabled'));
			
				// store the width of element holding list, used for distance to slider on each click
				// store number of screens, used for disable/enable btns
				// set default screen to first	
				var	width = $this.find('.slider-tabs-clip').width(),
					screens = Math.ceil($this.find('.slider-tabs li').length / maxitems);
				
				$this.data('clip-width',width);	
				$this.data('screens',screens);	
				$this.data('screen',1);	
				
				// make ul wide enough for all items to fit on one line
				$this.find('.slider-tabs-clip ul').css('width',width*screens+'px');						
			}	
		});
	},
	
	enableAccordion : function(el) {
		
		if(!$j(el).length) { return; }
		
		var $obj = $j(el), // accordion wrapper
			$detail = $obj.find('div.accordion-detail'), // each slide item
			cookie = getCookie('home-accordion'), // remember last panel
			show = cookie !== null && $obj.find('div.accordion-detail:eq('+cookie+')').length ? cookie : "0", // either show the last viewed or the first one
			queue = 0, // prevent over clicking by tracking if anything is being animated
			autoheight = AU.maxHeight($detail), // make all the content blocks the same height before invoking accordion
			pinned = $detail.length-1 != show ? " pinned" : ""; // don't add pinned class if showing last item

				
		// corner and shadow decor
		$obj.append('<span class="corner tr"></span><span class="corner tl"></span><span class="corner bl"></span><span class="corner br"></span>');
		$detail.wrapInner('<div class="inner"></div>');	
		// set default height
		var padding = { top: parseInt($detail.find('.inner').css('paddingTop')), bottom: parseInt($detail.find('.inner').css('paddingBottom')) }; // padding of inner to add to outer's height
		$obj.find('div.accordion-detail .inner,h3.hdr-accordion').css({height:autoheight+"px"});
		$obj.css({height:autoheight+padding.top+padding.bottom+"px"});
		
		// initialize
		$obj.find('div.accordion-detail').not(':eq('+show+')').hide(); 	// hide all but one panel
		$obj.find('h3.hdr-accordion').eq(show).addClass('open');
		$obj.find('div.accordion-detail:last').addClass('last pinned'); // pinned locks the last one to the right edge during others' animation
		$obj.find('h3.hdr-accordion:last').addClass('last'+pinned); 	// the last panel should always be pinned to prevent float drops, the last header should only be pinned if it is not open
				
		$obj.find('h3.hdr-accordion').click(function(){
			
			var $this = $j(this);
			if(queue==0 && !$this.is('.open')) {
				queue = 1;
				
				// close any open ones that are in the parent
				// if it's the last one, re-pin h3 to the end			
  				var $close = $obj.find("h3.hdr-accordion.open").removeClass("open").next();
				
				$this.addClass("open").removeClass("pinned").next().add($close).animate({width:'toggle'},700,'swing',function(){
					// re-pinned the last one
					$j('h3.hdr-accordion.last').not('.open').addClass('pinned');
					queue = 0;				
				}); 				
			}
			
			// set cookie to remember this panel
			setCookie('home-accordion',$this.parent().children('h3.hdr-accordion').index($this),32000);
			
		});
		
	},
	
	enableFilter : function(el) {
		
		var $obj = $j(el);
		
		if(!$obj.length || !$obj.find('.filter-list').length || !$obj.find('.filter-options').length) { return; }
		
		var $list = $obj.find('.filter-list'),
			$lis = $list.find('li'),
			$options = $obj.find('.filter-options'),
			$inputs = $options.find('input');			
		
		// clear out from page refresh
		$inputs.find('.default').attr("checked","checked").end().not('.default').removeAttr("checked");
		
		// bind input change
		$options.find('input[type=checkbox]').live('click',filter);
		
		// bind tooltip
		$lis.each(function(){
			var content = $j('.profile',this).html();
			$j(this).qtip({
				content: content,
				show: { delay: 100 },
				position: {
					target: 'mouse',
					corner: {
						target: 'topMiddle',
						tooltip: 'bottomMiddle'
					},
					adjust: { mouse: true }
				},
				style: { 
					width: 200,
					padding: 0,
					background: '#ffffff',
					border: {
						width: 5,
						radius: 0,
						color: '#76271A'
					},				  
					tip: 'bottomMiddle'
				},
				api: { beforeShow: function(){ if($j(this.elements.target).is('.off')) { return false; } } } // don't show tooltips for disabled items
			});
		});
		
		function filter() {
		
			var $this = $j(this),
				selector = "";
		
			// toggle checkboxes
			if($this.is('.default') && $this.is(':checked')) {
				$inputs.not($this).removeAttr("checked");
			}
			else if($this.is('.default')) {
				$this.attr("checked","checked");
			}
			else if($this.is(':checked')) {
				$inputs.filter('.default').removeAttr("checked");
			} else if(!$inputs.filter(':checked').length) {				
				$inputs.filter('.default').attr("checked","checked");
			}
			
			// reset
			$list.find('li').removeClass('off');
			
			// create list to hide
			$inputs.not(":checked,.default").each(function(){ 
				selector += "." + $j(this).attr("value") + ",";											  
			});
			
			// fade items. if default is checked, show them all. otherwise use selector
			// off class is used to determine if tooltip is enabled or not
			if($inputs.filter('.default').is(':checked')) {
				$lis.fadeTo('fast',1).removeClass('off').qtip('enable');
			} else {
				$lis.filter(selector).addClass('off').fadeTo('fast',0.35);
				$lis.not(selector).removeClass('off').fadeTo('fast',1);
			}		
			
			
		}
	},
	
	// get max height of set of $elements
	maxHeight : function($els) {
		var h = 0;
		$els.each(function(){ h = h < parseInt($j(this).height()) ? parseInt($j(this).height()) : h; });		
		return h;
	}
};

// jQuery plugins

// pull label and insert as field. clear with click
// optional lower param if == 1, string toLowerCase
jQuery.fn.inputSetter = function(lower) {	
	return this.each(function() {
		var $input = jQuery(this);
		var $label = jQuery("label[for='"+$input.attr("id")+"']");
		var labeltext = <!-- lower && lower==1 ? $label.text().toLowerCase() : --> 
		$label.text();
		$label.hide();	
		$input.val(labeltext);		
		$input.focus(function() { if (this.value == labeltext) { this.value = ""; }	})
			  .blur(function() { if (!this.value.length) { this.value = labeltext; } });		
	});
};

jQuery.fn.IX_tabs = function(tab) {	
	return this.each(function() {
		var $container = jQuery(this), 
			$tabs = jQuery("a", this),
	 		panes = new Array();
		$tabs.each(function () {
			var $this = jQuery(this);		
			var pane = $this.attr('href');
			if (pane.indexOf("#") != 0) {return true;};
		 	panes.push(pane);
			$this.bind("click", function(){
				jQuery(panes.join(",")).hide();
				$container.find('.active').removeClass('active');
				$this.parent("li").addClass("active");
				jQuery(pane).show();
				return false;
			});
		});
		var show = jQuery('a.default',$container).length ? $tabs.index(jQuery('a.default')) : tab || 0;
		$tabs.eq(show).length ? $tabs.eq(show).click() : $tabs.eq(0).click();
	});
};

// etc
// Cookies get/set/delete
function getCookie( name ) {
	var start = document.cookie.indexOf( name + "=" );
	var len = start + name.length + 1;
	if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) { return null;	}
	if ( start == -1 ) return null;
	var end = document.cookie.indexOf( ";", len );
	if ( end == -1 ) end = document.cookie.length;
	return unescape( document.cookie.substring( len, end ) );
}
function setCookie( name, value, expires, path, domain, secure ) {
	var today = new Date();
	today.setTime( today.getTime() );
	if ( expires ) { expires = expires * 1000 * 60 * 60 * 24; }
	var expires_date = new Date( today.getTime() + (expires) );
	document.cookie = name+"="+escape( value ) +
		( ( expires ) ? ";expires="+expires_date.toGMTString() : "" ) + //expires.toGMTString()
		( ( path ) ? ";path=" + path : "/" ) +
		( ( domain ) ? ";domain=" + domain : "" ) +
		( ( secure ) ? ";secure" : "" );
}
function deleteCookie( name, path, domain ) {
	if ( getCookie( name ) ) document.cookie = name + "=" +
			( ( path ) ? ";path=" + path : "/") +
			( ( domain ) ? ";domain=" + domain : "" ) +
			";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}
// end cookies


// clean console.log
function cl(){ if(window.console&&window.console.firebug) { var args = [].splice.call(arguments,0); console.log(args.join(" ")); } }//cl()
// example: cl("If you use cl() instead of console.log(), it won't break IE when you forget to take it out.");


// IE6 fixes
// make sure IE has the abbr and acronym tag
if(document.all){
	document.createElement("abbr");
	document.createElement("acronym");
}
// prevent IE6 flicker
try { document.execCommand('BackgroundImageCache', false, true); } catch(e) {}

function ddOpenC(ddID){
document.getElementById(ddID).style.display = "block";
}
function ddCloseC(ddID){
document.getElementById(ddID).style.display = "none";
} 
