/*

	Pacific Power Global Javascript
	ISITE Design

*/

// prototype with jquery. $ = prototype, $j = jquery.
// can still use $ for jQuery within the jQuery document ready function
var $j = jQuery.noConflict();

// prevent ie6 flicker
try { document.execCommand('BackgroundImageCache', false, true); } catch(e) {}

// sIFR 3
if(typeof sIFR != "undefined") {
	var gillsans = { src: '_resources/flash/GillSans_sIFR3.swf' };
	sIFR.activate(gillsans);

	sIFR.replace(gillsans, {
		selector: 'h1',
		css: '.sIFR-root { background-color: transparent; color: #000000; }',
		wmode: 'transparent',
		repaintOnResize: true
	});
}

var headerToggleText = {
	show : "<span>+</span> Show account info",
	hide : "<span>-</span> Hide account info"
}

// Dom loaded / jQuery
jQuery(function($) {

	// Pull the label, make lowercase, set as default value and hide it
	$("#sitesearch input").inputSetter(1);

	// ie6 special cases
	if($.browser.msie && parseInt($.browser.version) < 7){
		
		// add class to drop downs and buttons
	    $("#nav li, button, #lead2 a").hover(
			function() { var c = $(this).attr("class").split(" ")[1] || ""; $(this).addClass("over over-"+c); },
			function() { var c = $(this).attr("class").split(" ")[1] || ""; $(this).removeClass("over over-"+c); }
	    );		
		
		// fix elements over selects z-index issue
		// load script without ajax to avoid ActiveX requirement
		function loadScript(src, callback) {
			var script = document.createElement("script");		
			if(script.attachEvent) {
				script.attachEvent("onreadystatechange",
				function() { loadScript.callbackIE(callback); });
			}
			script.src = src;
			document.getElementsByTagName("head")[0].appendChild(script);
		}
		loadScript.callbackIE = function(callback) {
			var target = window.event.srcElement;
			if(target.readyState == "loaded")
			callback.call(target);
		};		
		callback = function() { $("#nav ul, .custom-select-list-wrapper").bgiframe(); };
		
		loadScript("_resources/js/jquery.bgiframe.min.js", callback);
	
	}// if ie6
		
	// show drops on focus
	$("#nav a").focus(function(){ $(this).parents("li").addClass("over"); })
				.blur(function(){ $(this).parents("li").removeClass("over"); });
	$("#nav>li").mouseover(function() { $("#nav>li").not($(this)).removeClass("over"); });

	// empower print
	$("a.print").click(function(){ window.print(); return false; });
	
	// popup help
	$("#header a.pop, #primary a.pop, #secondary a.pop, #footer a.pop").bind("click",showHelp);
	// external window
	$("#header a.external, #primary a.external, #secondary a.external, #footer a.external").bind("click",openExternal);
	
	// table row highlight
	// $("tbody tr").hover(function(){ $(this).toggleClass("highlight"); }, function(){ $(this).toggleClass("highlight"); });
	
	// select all : Add Electric Account Step 2
	$(".selectall").parents("tr.hide").removeClass("hide");
	$(".selectall .trigger").bind("click",toggleSelection);
	$("td input:checkbox").bind("click",toggleDisabled).bind("change",toggleDisabled);
	
	// enroll toggle
	$("fieldset.toggledisabled input:radio").bind("click",toggleDisabled).bind("change",toggleDisabled);
	
	// enroll toggle
	$("input.toggler:checkbox").bind("click",toggleDisabledSingle).bind("change",toggleDisabledSingle);
	
	// date picking
	if($(".date-picker").length>0) { 
		Date.firstDayOfWeek = 7;
		Date.format = 'mm/dd/yyyy';
		
		$(".date-picker").not(".future").datePicker({startDate:'01/01/2008',endDate: (new Date()).asString()});
		$(".date-picker.future").datePicker({startDate:(new Date()).asString()});
		
		$(".date-start").bind("dpClosed",function(e, selectedDates) {
											var d = selectedDates[0];
											if (d) {
												d = new Date(d);
												$(this).parents("fieldset").find(".date-end").dpSetStartDate(d.addDays(1).asString());					
											}
										});
		
		$(".date-end").bind("dpClosed",function(e, selectedDates) {
											var d = selectedDates[0];
											if (d) {
												d = new Date(d);
												$(this).parents("fieldset").find(".date-start").dpSetEndDate(d.addDays(-1).asString());
											}
										});		
	} // end date pick	
	
	// filter list multidate
	if($("li.filter-list-multidate").length){
		$(".form-filter-list .date-range").hide();
		
		var pickrange = false;
		var picktext = {
			single 	: ["date","date range"],
			range	: ["date range","single date"]
		};
		
		$("a.date-pick-type").click(function(){
		
			var $parent = $(this).parents("li");
		
			if(pickrange) {		
				$(".date-range",$parent).hide();
				$(".date-single",$parent).show();
				$("input.selectdaterange",$parent).val("false");
				$("label span",$parent).text(picktext.single[0]);
				$("label a",$parent).text(picktext.single[1]);
				pickrange = false;			
			} else {		
				$(".date-single",$parent).hide();
				$(".date-range",$parent).show();
				$("input.selectdaterange",$parent).val("true");
				$("label span",$parent).text(picktext.range[0]);
				$("label a",$parent).text(picktext.range[1]);
				pickrange = true;											
			}		
			return false;
		
		});	
	}
	
	
	// faq expand/collapse
	enableExpand("dl.faq,dl.collapsible");
	
	// sitemape expand/collapse
	enableTree(".sitemap ul");
	
	// toggle global header on account pages
	$("a.trigger-account").click(function(e){
		$("#globalheader div.columns").slideToggle("fast",function(){
			var html = $("#globalheader div.columns:visible").length == 0 ? headerToggleText.show : headerToggleText.hide;
			$("a.trigger-account").html(html).toggleClass("open");
		});
		var cookie = getCookie("accountinfo")=="hide" ? "show" : "hide";
		setCookie("accountinfo",cookie);
		if(typeof $.fn.customSelect != "undefined") {
			$.fn.customSelect.hideDrop();
		}
		return false;
	});
	if(getCookie("accountinfo")=="hide") {
		$("#globalheader div.columns").hide();
		$("a.trigger-account").html(headerToggleText.show).addClass("open");
	}
	
	// custom selector
	if(typeof $.fn.customSelect != "undefined") {
		$("select.custom").customSelect().change(function(){ $(this).parents("form").submit(); });
	}

	$("button.confirm").click(function(){ return confirm($(this).attr("title")); });
	
	// expand breadcrumb list
	$("#breadcrumb-expand a").click(function(){	
		$(this).parents("ul").find("li.hide").show().end().end().parent().remove();		
		return false;											 
	});
	
	// toggle extra form fields
	$("ol.collapsible li,ul.collapsible li").not(".toggler").not(".nohide").hide().end().end().end().find(".toggler input").click(function(){
		var val = $(":radio:checked",$(this).parents("fieldset")).val();
	
		// two radio toggle modes: one to match to class of selected value, other to show/hide all based on boolean
		if($(this).parents("li.match-class").length){
			$(this).parents(".collapsible").find("li").not(".toggler").not(".nohide").hide().end().end().end().find("li."+val).show();
		} else {
			if(!parseInt(val)) {			
				$(this).parents(".collapsible").find("li").show();
				if($(this).parents("li.fieldset").length){
					$(this).parents("fieldset").next("div.collapsible").show();
				}
			} else {			
				$(this).parents(".collapsible").find("li").not(".toggler").not(".nohide").hide();
				if($(this).parents("li.fieldset").length){
					$(this).parents("fieldset").next("div.collapsible").hide();
				}	
			}
		}
	}).end().find(".toggler select").change(function(){	
		var classname = $("option:selected",this).attr("class") || "select";
		$(this).parents(".collapsible").find("li").not(".toggler").not(".nohide").hide().end().end().end()
		.find("."+classname).show();	
	});
	$(".panel div.collapsible").hide();
	
});// document ready

// select all : Add Electric Account Step 2, Remove Account
var toggleSelection = function(){
	var $this = $j(this);
	var check = $this.parent().find("span:visible").is(".select");
	$this.parent().find("span").toggle();
	$this.parents("table").find(":checkbox").attr("checked",check).filter(":first").trigger("change");
	return false;											
};
var toggleDisabled = function(e){
	var $this = $j(this);
	if($this.parents("tbody").find("input:checked").length || $j(e.target).parents(".toggledisabled").find("input:checked").length) {
		$j(".btn-disabled").addClass("btn-enabled").removeClass("btn-disabled").removeAttr("disabled");
	} else {
		$j(".btn-enabled").addClass("btn-disabled").removeClass("btn-enabled").attr("disabled","disabled");	
	}
};

// generic enable/disable toggler for checkboxes
var toggleDisabledSingle = function(){
	var $this = $j(this);
	if($this.is(":checked")) {
		$j(".btn-disabled").addClass("btn-enabled").removeClass("btn-disabled").removeAttr("disabled");
	} else {
		$j(".btn-enabled").addClass("btn-disabled").removeClass("btn-enabled").attr("disabled","disabled");	
	}
};

// create help popup
var showHelp = function(){
	var w = screen.width || 800;
	var h = screen.height || 600;	
	var popW = 550, popH = 480;	
	var leftPos = (w-popW)/2, topPos = (h-popH)/2;
	var settings = "status=1,location=0,menubar=0,resizable=1,scrollbars=1,width="+popW+",height="+popH+",top="+topPos+",left="+leftPos;
	var newwindow = window.open($j(this).attr("href"),"help",settings);
	return false;
};

// external link
// ref: http://www.456bereastreet.com/archive/200610/opening_new_windows_with_javascript_version_12/
var openExternal = function(){
	var extwin = window.open($j(this).attr("href"), "_blank");
	if (extwin) {
		if (extwin.focus) extwin.focus();
		return false;
	}
	extwin = null;
	return false;
}

// create open/close. receives dl.
var enableExpand = function(el) {
		
	$j(el).addClass("expander").find("dd").hide().end()
		.find("dt").prepend('<a class="btn" href="#">+</a>').click(function(){
			var textinsert = $j("a.btn",this).text() == "+" ? "-" : "+";
			$j(this).toggleClass("open").next("dd").slideToggle("fast").end()
			.find("a.btn").text(textinsert);			
		}).hover(function(){
			$j("a",this).addClass("hover"); $j(this).addClass("hover"); }, function(){ $j("a",this).removeClass("hover"); $j(this).removeClass("hover");
		}).find("a.btn").click(function(){ $j(this).parents("dt").click(); return false; });		
};

// create open/close tree. receives ul.
var enableTree = function(el) {
		
	$j(el).addClass("expander").find("li li ul").hide();
	
	$j("li li",el).each(function(){							 
		if($j("li",this).length>0) {
			$j(this).prepend('<a class="btn" href="#">+</a>')
			$j("a.btn",this).click(function(){										   
				var textinsert = $j(this).text() == "+" ? "-" : "+";
				$j(this).text(textinsert).toggleClass("open").parent("li").find("ul:first").slideToggle("fast");				
				return false;			
			});
		}	
	});	
};

// 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; } });		
	});
};

// 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";
}