/*!
 * XE scripts
 */


/* APPLY PRINT STYLESHEET TO PRINT LAYOUT */
	var isInIFrame = (window.location != window.parent.location) ? true : false;

	if(isInIFrame  && window.parent.isPrint){
		document.write('<link href="/staticfiles/xe/css/xe_print.css" rel="stylesheet"  media="all" type="text/css" />');	
	}
	
	
	
$(document).ready(function () {	
							

/* STATE COOKIE */

	var stateCookie = $.cookie("GeographicLocation");
	
	//if( stateCookie == null ){
	//	showStateSelection();
	//}
	
	
	for (var i=0; i<document.stateSelector.stateList.options.length; i++) {
		if (document.stateSelector.stateList.options[i].value == stateCookie)
			document.stateSelector.stateList.options[i].selected = true;
	}
	
	if($.cookie("notifications") == "true"){
		if($.cookie("hideAlerts") == "false" || $.cookie("hideAlerts") == "" || $.cookie("hideAlerts") == null){	

			$("#commonUtilAlert").css("display","none");//hide();
			$("#emergencyNotification").css("visibility","visible");//.show();
			$("#emergencyNotification").css("height","20px");
			$("#emergencyNotification").css("padding","5px 0");
			$("#emergencyNotification").css("margin","5px 0");		
		}
		else{
			$("#commonUtilAlert").css("display","inline");
		}
	}
	
	
							
/* SHOW JAVASCRIPT ITEMS HIDDEN BY CSS */

	$('#commonUtils').css('display','block');


	
/* TOP HOROZONTAL NAVIGATION */

	$("ul#nav li a").attr("title", "");

	function megaHoverOver1(){
		$(this).find(".subNav").stop().fadeTo('fast', 1).show();
			
		//Calculate width of all ul's
		(function($) { 
			jQuery.fn.calcSubWidth = function() {
				rowWidth = 0;
				//Calculate row
				$(this).find("ul").each(function() {					
					rowWidth += $(this).width(); 
				});	
			};
		})(jQuery); 
		
		if ( $(this).find(".row").length > 0 ) { //If row exists...
			var biggestRow = 0;	
			//Calculate each row
			$(this).find(".row").each(function() {							   
				$(this).calcSubWidth();
				//Find biggest row
				if(rowWidth > biggestRow) {
					biggestRow = rowWidth;
				}
			});
			//Set width
			$(this).find(".subNav").css({'width' :biggestRow});
			$(this).find(".row:last").css({'margin':'0'});
			
		} else { //If row does not exist...
			
			$(this).calcSubWidth();
			//Set Width
			$(this).find(".subNav").css({'width' : rowWidth});
			
		}
	}
	
	function megaHoverOver(){
		$(this).children("a:first").attr("class","active");
		//$(this).first('li a').attr("class","activeLIb");
		//$(this).parent().attr("class","active");
		$(this).find(".main-col").stop().fadeTo('fast', 1).show();
		
		var reposition = ((960 - $(this).position().left - $(this).find('.main-col').width()) < 0) ? 960 - $(this).position().left - $(this).find('.main-col').width() : 0 ;
			$(this).find('.main-col').css('left',reposition);

	}
	
	function megaHoverOut(){ 
		$(this).children("a:first").attr("class","");
		//$(this).first('li a').attr("class","");
		//$(this).parent().attr("class","");
		$(this).find(".main-col").stop().fadeTo('fast', 0, function() {
		  $(this).hide(); 
		});
	}
 
 
	var config = {    
		 sensitivity: 2, // number = sensitivity threshold (must be 1 or higher)    
		 interval: 100, // number = milliseconds for onMouseOver polling interval    
		 over: megaHoverOver, // function = onMouseOver callback (REQUIRED)    
		 timeout: 150, // number = milliseconds delay before onMouseOut    
		 out: megaHoverOut // function = onMouseOut callback (REQUIRED)    
	};
 
	$("ul#nav li .main-col").css({'opacity':'0'});
	//$("ul#nav li").hoverIntent(config);
	$("ul#nav li").hover(megaHoverOver, megaHoverOut);

	
	
/* ACCORDION */

	// choose text for the show/hide link - can contain HTML (e.g. an image)
	var showText='accordTitle selected';
	var hideText='accordTitle';
	
	// initialise the visibility check
	var is_visible = false;
	var classSelected = "accordTitle";

	$(".accordContent").animate({height: "toggle"}, "fast");

	
	// capture clicks on the toggle links
	$('.accordTitle a').click(function() {
		// switch visibility
		is_visible = ($(this).parent().attr("class") != "accordTitle selected") ? true : false ; //!is_visible;
		
		// change the link depending on whether the element is shown or hidden
		classSelected = (is_visible) ? showText : hideText;

		$(this).parent().next('.accordContent').animate({height: "toggle"}, "slow");
		$(this).parent().attr("class",classSelected);

		return false;
	
	});
	
	
	
	try {
		$('.accordContent').first('.accordContent').animate({height: "toggle"}, 100);
		$('.accordTitle').first('.accordTitle').attr("class","accordTitle selected");
	} catch(err) {
		//handle ((err && err.message) || err.toString())
	} 
	
	
/* EMAIL */

	// obfuscate the emails so bots won't spam them
	$('span.obfuscate').each(function () {
		var email = $(this).text().replace(/\s*\(.+\)\s*/,"@");
		var name = $(this).attr('title');
		
		if (name == '') name = email;
		
		$(this).after('<a href="mailto:'+ email +'" title="Send email to ' + name + '">'+ name +'</a>');
		$(this).remove();
	});
	
	
/* FONT SIZE */

	if( $.cookie("XEFontSize") == null || $.cookie("XEFontSize") == undefined || $.cookie("XEFontSize") == "" ){
		$.cookie("XEFontSize", $("body").css("font-size"), {path: "/"});
	}

	$("body").css('font-size', $.cookie("XEFontSize"));
	
	
	
/* INIT SHADOWBOX */

	Shadowbox.init({
		overlayColor: "#000",
		overlayOpacity: "0.8"
		//handleOversize:     "drag",
		//displayNav:         false,
		//autoplayMovies:     false
	});

/* ROTATION PHOTO GALLERY */
	
	var slider = $('#heroslider').bxSlider({
		mode: 'fade',							// 'horizontal', 'vertical', 'fade'
		pause: 5000,							// integer - in ms, the duration between each slide transition
		auto: true,								// true, false - make slideshow change automatically
		autoControls: true,						// true, false - show 'start' and 'stop' controls for auto show
		autoControlsSelector: '#gallery-play-pause',	// jQuery selector - element to contain the auto controls. ex: '#auto-controls'
		
		// pager //
		pager: true,							// true / false - display a pager
		pagerType: 'short',						// 'full', 'short' - if 'full' pager displays 1,2,3... if 'short' pager displays 1 / 4
		pagerShortSeparator: 'of',				// string - ex: 'of' pager would display 1 of 4
		pagerSelector: '#gallery-pager',				// jQuery selector - element to contain the pager. ex: '#pager'
		
		// Next Button //
		nextText: 'next',										// string - text displayed for 'next' control
		nextImage: '/staticfiles/xe/images/slideshow/heroArrowRight.gif',	// string - filepath of image used for 'next' control. ex: 'images/next.jpg'
		nextSelector: '#gallery-next',										// jQuery selector - element to contain the next control. ex: '#next'
		
		// Previous Button //
		prevText: 'prev',											// string - text displayed for 'previous' control
		prevImage: '/staticfiles/xe/images/slideshow/heroArrowLeft.gif',	// string - filepath of image used for 'previous' control. ex: 'images/prev.jpg'
		prevSelector: '#gallery-prev',											// jQuery selector - element to contain the previous control. ex: '#next'
			
		//startText: 'play',										// string - text displayed for 'start' control
		startImage: '/staticfiles/xe/images/slideshow/play.jpg',	// string - filepath of image used for 'start' control. ex: 'images/start.jpg'
		//stopText: 'pause',										// string - text displayed for 'stop' control
		stopImage: '/staticfiles/xe/images/slideshow/pause.jpg',		// string - filepath of image used for 'stop' control. ex: 'images/stop.jpg'
		
		onBeforeSlide: updateGalleryMenu
		
	});
	
		$('.menuItem a').click(function(){
            var thumbIndex = $('.menuItem a').index(this);
            slider.goToSlide(thumbIndex);
            $('.menuItem').removeClass('act');
            $(this).parent().addClass('act');
            return false;
        });
        
        $('.menuItem:first').addClass('act');
		
		var tempThumbWidth = 0;
		var tempThumbCss = 0; 
		
		if($('.thumbs').css("width")){
			tempThumbCss = parseInt($('.thumbs').css("width").substring(0,$('.thumbs').css("width").indexOf("px")));
		}
		
		$('.menuItem').each(function(){
			tempThumbWidth += parseInt($(this).outerWidth());
		});
		
		if(tempThumbCss > tempThumbWidth){
			$('.thumbs').css('width', parseInt(57 * parseInt($('.menuItem').size()))+'px');
			//$('#gallery-prev').css('display', 'none');
			//$('#gallery-next').css('display', 'none');
		}
		
		
		
		
	
	var slider2 = $('#emergencyslider').bxSlider({
		mode: 'horizontal',						// 'horizontal', 'vertical', 'fade'
		pause: 7000,							// integer - in ms, the duration between each slide transition
		auto: true,								// true, false - make slideshow change automatically
		autoControls: false,						// true, false - show 'start' and 'stop' controls for auto show
		//autoControlsSelector: '#emergency-play-pause',	// jQuery selector - element to contain the auto controls. ex: '#auto-controls'
		
		// pager //
		pager: true,							// true / false - display a pager
		pagerType: 'short',						// 'full', 'short' - if 'full' pager displays 1,2,3... if 'short' pager displays 1 / 4
		pagerShortSeparator: '/',				// string - ex: 'of' pager would display 1 of 4
		pagerSelector: '#emergency-pager',				// jQuery selector - element to contain the pager. ex: '#pager'
		
		// Next Button //
		nextText: 'next',										// string - text displayed for 'next' control
		nextImage: '/staticfiles/xe/images/slideshow/next.jpg',	// string - filepath of image used for 'next' control. ex: 'images/next.jpg'
		nextSelector: '#emergency-next',										// jQuery selector - element to contain the next control. ex: '#next'
		
		// Previous Button //
		prevText: 'prev',											// string - text displayed for 'previous' control
		prevImage: '/staticfiles/xe/images/slideshow/previous.jpg',	// string - filepath of image used for 'previous' control. ex: 'images/prev.jpg'
		prevSelector: '#emergency-prev',											// jQuery selector - element to contain the previous control. ex: '#next'
			
		//startText: 'play',										// string - text displayed for 'start' control
		startImage: '/staticfiles/xe/images/slideshow/play.jpg',	// string - filepath of image used for 'start' control. ex: 'images/start.jpg'
		//stopText: 'pause',										// string - text displayed for 'stop' control
		stopImage: '/staticfiles/xe/images/slideshow/pause.jpg'		// string - filepath of image used for 'stop' control. ex: 'images/stop.jpg'
		
	});
            

});

function updateGalleryMenu( current, total ){
	
	//alert('Size: ' + $('.menuItem a').size());
	
	$('.menuItem').removeClass('act');
	
	$('.menuItem a').each(function(index){
		if(index == current){
			$(this).parent().addClass('act');
		}
	});
	
	if($('.menuItem').eq(current)){
		var holderWidth = parseInt($('.thumbs').css("width").substring(0,$('.thumbs').css("width").indexOf("px")));
		var thumbsWidth = parseInt(57 * $('.menuItem').size());
		var slidePosition = parseInt($('.menuItem').eq(current).position().left);
		
		var moveLeft = 0;

		if(slidePosition > thumbsWidth - holderWidth ){
			moveLeft = parseInt(thumbsWidth - holderWidth);
		}
		else{
			
			moveLeft = parseInt(slidePosition);
		}


		$('.thumbs ul').animate({'left': -moveLeft}, 500);
	}
	
	
}

		


/* ACCORDION SHOW/HIDE ALL */
function showAllAccord(){
	
	//if (!jQuery) alert("Please wait for the page to load"); return;
	
	$(".accordContent").show();
	$(".accordTitle").attr("class","accordTitle selected");
}

function hideAllAccord(){
	$(".accordContent").hide();
	$(".accordTitle").attr("class","accordTitle");
}

function showAlerts(){
	$.cookie("hideAlerts", "false", {expires: 1, path: "/"});
	$("#commonUtilAlert").css("display","none");//hide();
	$("#emergencyNotification").css("visibility","visible");//.show();
	$("#emergencyNotification").css("height","20px");
	$("#emergencyNotification").css("padding","5px 0");
	$("#emergencyNotification").css("margin","5px 0");	
}
function hideAlerts(){
	$.cookie("hideAlerts", "true", {expires: 1, path: "/"});
	$("#commonUtilAlert").css("display","inline");
	$("#emergencyNotification").css("visibility","hidden");//.hide();
	$("#emergencyNotification").css("height","0");
	$("#emergencyNotification").css("padding","0");
	$("#emergencyNotification").css("margin","0");
}

function openToolBox(){
	
	alert("Open Toolbox");
}

function changeFontSize(){
	//if (!jQuery) alert("Please wait for the page to load"); return;
	
	switch( $.cookie("XEFontSize") ){
		
		case "13px":
			currentSize = "15px";
			break;
			
		case "15px":
			currentSize = "17px";
			break;
			
		case "17px":
			currentSize = "13px";
			break;
			
		default:
			currentSize = "13px";
	}
	
	$.cookie("XEFontSize", currentSize, {path: "/"});
	
	$("body").css('font-size', $.cookie("XEFontSize"));
	
}

function emailPage( page ){	
	//if (!jQuery) alert("Please wait for the page to load"); return;
	
	Shadowbox.open({
        content:    page,
        player:     "iframe",
        width:      760
    });
}

function printPage( page ){
	//if (!jQuery) alert("Please wait for the page to load"); return;

	isPrint = true; 
	
	Shadowbox.open({
		options: {onFinish: function () { setTimeout( "window.print()", 4000 ); }, onClose: function(){isPrint = false;}},
        content:    page, 
        player:     "iframe",
        width:      900
    });
	
	
}


/* Show / Hide Contacts */

function showContact( div ){
	$("#"+div).css('display', 'block');
}

function hideContact( div ){
	$("#"+div).css('display', 'none');
}


/* POLLS AND SURVEYS */
function submitPoll( surveyID, group, url ){

	var isChecked = $("input[name='"+group+"']:checked").val();
	
	if (isChecked == "" || isChecked == undefined) {
      //$("label#name_error").show();
      //$("input#name").focus();
      return false;
    }
	else{
		$.cookie(surveyID ,true, {expires: 1, path: "/"});
		//$('#survey').hide();
		//$('#surveyLoading').show();
		//$('#surveyResults').show();
	}
	
	/*var dataString = group+'='+ isChecked;
	
	$.ajax({
      type: "POST",
      url: url,
      data: dataString,
      success: function() {
		//alert("Success");
        $('#surveyLoading').hide();
        $('#surveyResults').show();
      }
    });	*/
    return true;

}

function showStateSelection(){
	$("#siteWrapper").css('display','none');
	$("#stateOverlayID").css('display','block');
}

function setStateLocation( choosenState ){
	
	$.cookie("GeographicLocation", choosenState, {expires: 365, path: "/"});
	document.stateSelector.action = window.location.href;
	document.stateSelector.submit();
	
	//$.cookie("state", location);
	
	//$("#stateOverlayID").css('display','none');
	//$("#siteWrapper").css('display','block');
}

function setQuovaStateLocation(choosenState){
	if (choosenState == "co") {
		choosenState = "/Geographic Location/Colorado";
	} else if (choosenState == "mi") {
		choosenState = "/Geographic Location/Michigan";
	} else if (choosenState == "mn") {
		choosenState = "/Geographic Location/Minnesota";
	} else if (choosenState == "nm") {
		choosenState = "/Geographic Location/New Mexico";
	} else if (choosenState == "nd") {
		choosenState = "/Geographic Location/North Dakota";
	} else if (choosenState == "sd") {
		choosenState = "/Geographic Location/South Dakota";
	} else if (choosenState == "tx") {
		choosenState = "/Geographic Location/Texas";
	} else if (choosenState == "wi") {
		choosenState = "/Geographic Location/Wisconsin";
	} else {
		choosenState = "";
	}
	
	// only set the cookie and redirect if there is a valid value
	if (choosenState != "") {
	    $.cookie("GeographicLocation", choosenState, {expires: 365, path: "/"});
	    if (window.location.href.indexOf("?") > -1) {
            window.location.href = window.location.href + "&stateSelected=true";
	    } else {
	    	window.location.href = window.location.href + "?stateSelected=true";
	    } 
	    //window.location.reload(false);
    }
}

	

/* SET THE CAPTION WIDTH */
$(window).load(function() {
   $(".imageCaption p.caption").each(function() {
      $(this).width($(this).siblings("img").width());
   });    
});




