/* ----------------------------------------------------------
title: REC Framework

version: 1.0
author: M. Grimm – Lockheed Martin Energy
created: 12/17/07
last updated: 02/12/08
-------------------------------------------------------------
change history
-------------------------------------------------------------
02/12/2008 dharadheer prathipati – Lockheed Martin Energy - modified to add autorefresh for outage summary data

---------------------------------------------------------- */


/*
 * Superfish v1.4.8 - jQuery menu widget
 * Copyright (c) 2008 Joel Birch
 *
 * Dual licensed under the MIT and GPL licenses:
 * 	http://www.opensource.org/licenses/mit-license.php
 * 	http://www.gnu.org/licenses/gpl.html
 *
 * CHANGELOG: http://users.tpg.com.au/j_birch/plugins/superfish/changelog.txt
 */

;(function($){
	$.fn.superfish = function(op){

		var sf = $.fn.superfish,
			c = sf.c,
			$arrow = $(['<span class="',c.arrowClass,'"> &#187;</span>'].join('')),
			over = function(){
				var $$ = $(this), menu = getMenu($$);
				clearTimeout(menu.sfTimer);
				$$.showSuperfishUl().siblings().hideSuperfishUl();
			},
			out = function(){
				var $$ = $(this), menu = getMenu($$), o = sf.op;
				clearTimeout(menu.sfTimer);
				menu.sfTimer=setTimeout(function(){
					o.retainPath=($.inArray($$[0],o.$path)>-1);
					$$.hideSuperfishUl();
					if (o.$path.length && $$.parents(['li.',o.hoverClass].join('')).length<1){over.call(o.$path);}
				},o.delay);	
			},
			getMenu = function($menu){
				var menu = $menu.parents(['ul.',c.menuClass,':first'].join(''))[0];
				sf.op = sf.o[menu.serial];
				return menu;
			},
			addArrow = function($a){ $a.addClass(c.anchorClass).append($arrow.clone()); };
			
		return this.each(function() {
			var s = this.serial = sf.o.length;
			var o = $.extend({},sf.defaults,op);
			o.$path = $('li.'+o.pathClass,this).slice(0,o.pathLevels).each(function(){
				$(this).addClass([o.hoverClass,c.bcClass].join(' '))
					.filter('li:has(ul)').removeClass(o.pathClass);
			});
			sf.o[s] = sf.op = o;
			
			$('li:has(ul)',this)[($.fn.hoverIntent && !o.disableHI) ? 'hoverIntent' : 'hover'](over,out).each(function() {
				if (o.autoArrows) addArrow( $('>a:first-child',this) );
			})
			.not('.'+c.bcClass)
				.hideSuperfishUl();
			
			var $a = $('a',this);
			$a.each(function(i){
				var $li = $a.eq(i).parents('li');
				$a.eq(i).focus(function(){over.call($li);}).blur(function(){out.call($li);});
			});
			o.onInit.call(this);
			
		}).each(function() {
			var menuClasses = [c.menuClass];
			if (sf.op.dropShadows  && !($.browser.msie && $.browser.version < 7)) menuClasses.push(c.shadowClass);
			$(this).addClass(menuClasses.join(' '));
		});
	};

	var sf = $.fn.superfish;
	sf.o = [];
	sf.op = {};
	sf.IE7fix = function(){
		var o = sf.op;
		if ($.browser.msie && $.browser.version > 6 && o.dropShadows && o.animation.opacity!=undefined)
			this.toggleClass(sf.c.shadowClass+'-off');
		};
	sf.c = {
		bcClass     : 'sf-breadcrumb',
		menuClass   : 'sf-js-enabled',
		anchorClass : 'sf-with-ul',
		arrowClass  : 'sf-sub-indicator',
		shadowClass : 'sf-shadow'
	};
	sf.defaults = {
		hoverClass	: 'over',
		pathClass	: 'overideThisToUse',
		pathLevels	: 1,
		delay		: 400, // was 800 in original download
		//animation	: {opacity:'show'},
		animation	: {opacity:'show', height:'show'},
		speed		: 'fast', //'normal',
		autoArrows	: false,
		dropShadows : true,
		disableHI	: false,		// true disables hoverIntent detection
		onInit		: function(){}, // callback functions
		onBeforeShow: function(){},
		onShow		: function(){},
		onHide		: function(){}
	};
	$.fn.extend({
		hideSuperfishUl : function(){
			var o = sf.op,
				not = (o.retainPath===true) ? o.$path : '';
			o.retainPath = false;
			var $ul = $(['li.',o.hoverClass].join(''),this).add(this).not(not).removeClass(o.hoverClass)
					.find('>ul').hide().css('visibility','hidden');
			o.onHide.call($ul);
			return this;
		},
		showSuperfishUl : function(){
			var o = sf.op,
				sh = sf.c.shadowClass+'-off',
				$ul = this.addClass(o.hoverClass)
					.find('>ul:hidden').css('visibility','visible');
			sf.IE7fix.call($ul);
			o.onBeforeShow.call($ul);
			$ul.animate(o.animation,o.speed,function(){ sf.IE7fix.call($ul); o.onShow.call($ul); });
			return this;
		}
	});

})(jQuery);


$(document).ready(function(){
		$("ul#primary-nav").superfish();
	});




// Zebra tables
//***************************************************
$(document).ready(function(){
	zebraTable();
});

function zebraTable() {
	$(".zebra tbody tr").mouseover(function() {$(this).addClass("over");}).mouseout(function() {$(this).removeClass("over");});
	$(".zebra tbody tr:even").addClass("alt");
}


// Forms
//***************************************************
$(document).ready(function(){
	//generate required and optional field helpers
	$(".required-field").siblings("label").append(' <em class="required-label">(required)</em>');
	$(".optional-field").siblings("label").append(' <em class="optional-label">(optional)</em>');
});


// Open new windows
//***************************************************
$(document).ready(function(){
	setNewWindowLinks();
});

function setNewWindowLinks() {	
	//open links in new windows 
	//(attribute selectors are written like their XPath counter-parts - in that all attributes should begin with an @ symbol - jquery 1.1.x)
		
	$("a[@href$='.pdf']").click(openWin);
	$("a[@href^='http']").click(openWin);

	// if not IE - add our classes to show external links and document links
// commented out by Dale Williams on 10/14/2008	
//	if (! $.browser.msie) {
//		$("a[@href$='.pdf']").addClass("document-link");
//		$("a[@href^='http']").addClass("external-link");
//	}
}
	
/* wonderful little function taken from Roger Johansson's JSTarget www.456bereastreet.com */
function openWin(e) {
var event = (!e) ? window.event : e;
	if (event.shiftKey || event.altKey || event.ctrlKey || event.metaKey) { return true; }
	else {
		var xhref = String(this.getAttribute('href'));
		var loc = window.location.host;
		if ( xhref.indexOf(loc) == -1  || // e.g. subnav, outage map link does not open new window
			 xhref.search(/.pdf$/) > 0    // all pdf files need new window
		   ) 
		{
			var oWin = window.open(this.getAttribute('href'), '_blank');
			if (oWin) {
				if (oWin.focus) {oWin.focus();}
				return false;
			}
		}
	oWin = null;
	return true;
	}
}



// Sample Bill ui
//***************************************************
//ie6 needs this because it does not support :hover on anything but anchor elements (also helps opera out)

$(document).ready(function(){

	$("#sample-bill #bill-sections li").hover(function(){
	  		$(this).addClass("over");
			},function(){
	  		$(this).removeClass("over");
	});

});


// NEW Sample Bill ui 2009-06-10
//***************************************************
//ie6 needs this because it does not support :hover on anything but anchor elements (also helps opera out)

$(document).ready(function(){

	$("#sample-bill-new #bill-sections-new li").hover(function(){
	  		$(this).addClass("over");
			},function(){
	  		$(this).removeClass("over");
	});

});



// Outage Summary
//***************************************************
var xmlDataSet;
var summaryrefreshtime = 60000; //60000=1min
var footSummHTML = '<div id="outage-summ-footer" >' + 
				 '<strong>This information is updated about every ten minutes. It is for information purposes only and is based on the best available information.</strong>' + 
				 '</div>';;
var distOutSummHTML = '<div id="district-summary"></div>';
var xmlTS1 = "";

$(document).ready(function(){

loadsummaryTable();

});// end doc ready

function loadsummaryTable(){
// check to make sure the outage table exists first
if ($("table#outage-summary").length > 0) {	   
    var date = new Date();
    var timestamp = date.getTime();
	//create loading message
	$("table#outage-summary tbody").empty().html('<tr><td colspan="3"><h4>Loading&hellip;</h4></td></tr>');
	// load xml file	
	$.ajax({
	  type: "GET",
	  url: "/outagexml/outagexmldata.xml?time="+timestamp,
	  dataType: "xml",
	  ifModified: true,
	  success: function(xmlData) {
			xmlDataSet = xmlData;
			parseXML();
			parseDistrictOutage();
			parseMarquee();
	  }, complete: function(XMLHttpRequest, textStatus)	{
		   xmlTS1 = new Date(XMLHttpRequest.getResponseHeader("Last-Modified")).toLocaleString();
		   if (textStatus == "success") {
 			 // Summary footer	   
			 $('#outage-summ-footer').text('');
			 footSummHTML = '<div id="outage-summ-footer" >' + 
			 			 '<strong>This information is updated about every ten minutes. It is for information purposes only and is based on the best available information.</strong>' + 
			 			 ' (Last updated: ' + formatDateStr(xmlTS1) + ')' +
			 			 '</div>';
			 $('#outage-summary').after(footSummHTML);
		   }
	  }, error: function () {
		  $("table#outage-summary tbody").empty().html('<tr><td colspan="3"><p class="error">There was an error retrieving the outage data. Try refreshing the page. If you continue to see this message, try again in a few moments or <a href="/feedback/">tell us about it</a>.</p></td></tr>');
	  }	  
	});
}
}

//refresh every 10 minutes
setInterval("loadsummaryTable()",summaryrefreshtime);


// e.g. Last updated: July 29, 11:33 AM
function formatDateStr (iDate){
	var m_names = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
	var aDate = new Date(iDate);
	var MON = m_names[aDate.getMonth()];
	var DD = aDate.getDate();
	var hh = aDate.getHours();
	var	mm = aDate.getMinutes();
	var	ap = "AM";
	if (hh < 12) {ap = "AM";}
	else {ap = "PM";}
	if (hh == 0) {hh = 12; }
	if (hh > 12) { hh = hh - 12; }
	mm = mm + "";
	if (mm.length == 1) { mm = "0" + mm; }
	return (MON + ' ' + DD + ', ' + hh + ':' + mm + ' ' + ap);
}

function trimNumber(s) { return s.replace(/^0+/, ''); } 


function parseMarquee() {
	if ($("OutageMarquee",xmlDataSet).length > 0) {	
		// Outage Marquee Message
		$("#outage-summary-marquee").remove(); 
		var marquee = xmlDataSet.getElementsByTagName("OutageMarquee");
		if (marquee.length == 1) {
			var isActive = xmlDataSet.getElementsByTagName("Active")[0].firstChild.nodeValue;
			if (isActive == 'Y') {
				var omCreateDt = xmlDataSet.getElementsByTagName("CreatedDT")[0].firstChild.nodeValue;		
				var omText1 = xmlDataSet.getElementsByTagName("MarqueeText1")[0].firstChild.nodeValue;
				var omText2 = xmlDataSet.getElementsByTagName("MarqueeText2")[0].firstChild.nodeValue;
				var omText3 = xmlDataSet.getElementsByTagName("MarqueeText3")[0].firstChild.nodeValue;
				var omDt = xmlDataSet.getElementsByTagName("ExpiredDT")[0].firstChild.nodeValue;
				var omHr = xmlDataSet.getElementsByTagName("ExpiredHR")[0].firstChild.nodeValue;
				var omMi = xmlDataSet.getElementsByTagName("ExpiredMI")[0].firstChild.nodeValue;
				// var omExDt = omDt + ' ' + omHr + ':' + omMi;
				var temp = new Array();
				temp = omDt.split('/');
				var expireDT = new Date(trimNumber(temp[2]), (trimNumber(temp[0])-1), trimNumber(temp[1]), trimNumber(omHr), trimNumber(omMi), 0)
				var currentDate = new Date();
				if(expireDT > currentDate) {
					var marqueeHTML1 = '<div id="outage-summary-marquee" style="text-align:center;color:#993300;background-color:#FFFFCC;font-size:12px;font-weight:bold;margin-bottom:10px;">' + 
									  '<MARQUEE SCROLLDELAY=200 SCROLLAMOUNT=10 width="90%">' +
									  '[' + formatDateStr(omCreateDt) + '] REC is experiencing outages ' + omText1 + ' caused by ' + omText2 + 
									  '. We are working to restore service ' + omText3 + '.' + '</MARQUEE>' +
									  '<br/>' + 'Please call 1-800-552-3904 to report an outage.' + '</div>';	
					$('#page-title').after(marqueeHTML1);	
				}
			}
		}
	}
}

function parseDistrictOutage() {
	if ($("DistSummMsg",xmlDataSet).length > 0) {	
		$("#district-summary").remove(); 
		if (xmlDataSet.getElementsByTagName("DistSummMsg")[0].firstChild.nodeValue != 0) {
			$("#district-summary").remove(); 
			$('#district-summary').text('');
			distOutSummHTML = '<div id="district-summary">' + xmlDataSet.getElementsByTagName("DistSummMsg")[0].firstChild.nodeValue + '</div>';
			$('#outage-summary').before(distOutSummHTML);
		}		
	}
}



function parseXML() {
var strToAppend = '';
var strCtyLoc = '';
	//make sure our xml has the outage summary data in it
	if ($("OutageSummary",xmlDataSet).length > 0) {		
		$("Totals",xmlDataSet).eq(0).each( function() { 
			if ($("table#outage-summary tbody#outage-totals").length > 0) {
				$("table#outage-summary tbody#outage-totals").remove();
			}
			var totalHTML=  '<tbody id="outage-totals"><tr class="outage-total">' +
			 '<td>' + $("TitleDescr",this).text() + '</td>' +
			 '<td>' + $("TotCustAffected",this).text() + '</td>' +
			 '<td>' + $("TotCustServed",this).text() + '</td>' +
			 '</tr></tbody>';
			$(totalHTML).insertBefore("table#outage-summary tbody");
		});

		$("OutageSummary OutageData",xmlDataSet).each( function() {
			switch($("County",this).text())
			{
			case "Albemarle County": strCtyLoc="?ll=629404a3-8598-4330-9961-02122ff5a6a8"; break;
			case "Caroline County": strCtyLoc="?ll=fa5c4daa-bd53-4c50-a762-1a62d85c249d"; break;
			case "Clarke County": strCtyLoc="?ll=0a5867f3-2a64-451e-98ce-e52a19064ef4"; break;
			case "Culpeper County": strCtyLoc="?ll=8c8fec19-dcc2-4481-9859-1789973e4df3"; break;
			case "Essex County": strCtyLoc="?ll=b79c5355-a618-4272-822d-6c3d000768df"; break;
			case "Fauquier County": strCtyLoc="?ll=231af318-17bd-4bff-9b68-b06c9285d04d"; break;
			case "Frederick County": strCtyLoc="?ll=2f0e9f60-e7ec-411a-a810-964cffd3017f"; break;
			case "Goochland County": strCtyLoc="?ll=50fba687-e16d-4869-acb2-5313f28828f4"; break;
			case "Greene County": strCtyLoc="?ll=fadcbee1-cb65-4400-849c-0c8d09ff4e66"; break;
			case "Hanover County": strCtyLoc="?ll=c7029bdb-503c-4463-b6b0-8fa590ec0498"; break;
			case "King & Queen County": strCtyLoc="?ll=259644bc-b66f-4662-b369-b9da0ab20f8d"; break;
			case "King William County": strCtyLoc="?ll=aaf9463c-e45c-4414-be92-89910122180c"; break;
			case "Louisa County": strCtyLoc="?ll=3fbc5e80-7981-4528-b589-5ded682f6d2c"; break;
			case "Madison County": strCtyLoc="?ll=fe2a9eff-5691-4c42-b3e2-7eb8b3b3000f"; break;
			case "Orange County": strCtyLoc="?ll=46596c45-66da-46a2-acb2-897f36250561"; break;
			case "Page County": strCtyLoc="?ll=30fbba3d-d3ee-4bfc-afad-2280ef599be6"; break;
			case "Rappahannock County": strCtyLoc="?ll=70ddcdce-ac8e-4d6e-847f-ab53470e1a1e"; break;
			case "Rockingham County": strCtyLoc="?ll=b8bdb1c8-8e6c-4279-9811-e96585fbac59"; break;
			case "Shenandoah County": strCtyLoc="?ll=c820c0fd-c34b-47b3-a52d-eba956be7cfb"; break;
			case "Spotsylvania County": strCtyLoc="?ll=a2a1a752-336a-456f-9137-11651d4f6287"; break;
			case "Stafford County": strCtyLoc="?ll=89a5dff3-66bd-43c9-940d-912f2ca120bc"; break;
			case "Town of Berryville": strCtyLoc="?ll=8ea41eb1-d8df-4bce-b7e3-562d4ff99f03"; break;
			case "Town of Bowling Green": strCtyLoc="?ll=749603d8-6e12-4cf1-8a9b-dc4187daf209"; break;
			case "Town of Boyce": strCtyLoc="?ll=b2b9d1e5-9087-4284-ab5c-2a07990da91a"; break;
			case "Town of Culpeper": strCtyLoc="?ll=273c8139-4856-4de3-8302-7abd0dbfcdaf"; break;
			case "Town of Front Royal": strCtyLoc="?ll=b7d0f33c-a027-4627-a517-ffaecab4bc3a"; break;
			case "Town of Madison": strCtyLoc="?ll=938253d2-0c22-4c5c-82aa-cf0a85b3f130"; break;
			case "Town of Middletown": strCtyLoc="?ll=8cfa719b-9d72-4b5e-a995-c27d2dfad1dc"; break;
			case "Town of Stanardsville": strCtyLoc="?ll=90d52bf6-6b2b-4d1c-960a-70a9956edff5"; break;
			case "Town of Stephens City": strCtyLoc="?ll=6a5e5a3c-d5a6-4b2f-b141-ad8d70c67f39"; break;
			case "Town of Washington": strCtyLoc="?ll=36582ef2-3d8b-4b6f-a97f-1e7bca01af55"; break;
			case "Warren County": strCtyLoc="?ll=9f19b8d9-bb7b-423f-b338-b80ae260c41f"; break;
			default: strCtyLoc="";
			}
			strToAppend += '<tr>';
			strToAppend += '<td><a target="_blank" href="outage-map.cfm' + strCtyLoc + '">' + $("County",this).text() + '</a></td>';
			strToAppend += '<td>' + $("CustAffected",this).text() + '</td>';
			strToAppend += '<td>' + $("CustServed",this).text() + '</td>';
			strToAppend += '</tr>';															
		});	
	} else {	
		strToAppend += '<tr><td colspan="3">Outage Data currently unavailable.</td></tr>';
		//outage summary data missing from xml	
	}
	
	$("table#outage-summary tbody#outage-summary-data").empty().html(strToAppend);	
	sortTable();
}


function sortTable() {

    var myTable = $("table#outage-summary");
	$('th', myTable).each(function(column) {
      var findSortKey;
	  if ($(this).is('.sort-numeric')) {
        findSortKey = function($cell) {
          var key = parseFloat($cell.text());
          return isNaN(key) ? 0 : key;
        };
      }
      if (findSortKey) {		  
          var rows = myTable.find('tbody#outage-summary-data > tr').get();
          $.each(rows, function(index, row) {
            row.sortKey = findSortKey($(row).children('td').eq(column));
          });
          rows.sort(function(a, b) {
            if (a.sortKey < b.sortKey) return 1;
            if (a.sortKey > b.sortKey) return -1;
            return 0;
          });
          $.each(rows, function(index, row) {
            myTable.children('tbody#outage-summary-data').append(row);
            row.sortKey = null;
          });         
        }
      });
	
$("table#outage-summary tbody tr").removeClass('alt');
zebraTable(); //refreshes all tables on screen currently 
}


// Error Redirect
//***************************************************
$(document).ready(function(){
	//make sure error-page id exists
	if ($("#error-page").length > 0) {	
	redirectTimer = setTimeout("redirectUser()",20000);
	}
});

function redirectUser() {
	clearTimeout(redirectTimer);
	window.location="/";
}

// SmartGrid Redirect (1/31 - 3/27)
//***************************************************
$(document).ready(function(){
	if ($("#smartgrid-redirect-page").length > 0) {	
	redirectSmartgridTimer = setTimeout("redirectSmartgridUser()",15000);
	}
});

function redirectSmartgridUser() {
	clearTimeout(redirectSmartgridTimer);
	window.location="/residential/services/water-heater-load-management.cfm";
}

// max length for textarea
//***************************************************
function textLimit(field, maxlen) {
	if (field.value.length > maxlen + 1)
		alert('Your input has exceeded our limit.!');
	if (field.value.length > maxlen)
		field.value = field.value.substring(0, maxlen);
} 

// remove special characters
//***************************************************
function removeSpecialChar(field) {
	var iChars = "<>#%~";
	for (var i = 0; i < field.value.length; i++) {
		if (iChars.indexOf(field.value.charAt(i)) != -1){
			field.value = field.value.replace(new RegExp(field.value.charAt(i), "gi" ), "");
		}
	}
}

