/* ----------------------------------------------------------
title: REC Framework

version: 1.0
author: Matt Grimm
created: 12/17/07
last updated: 02/12/08
-------------------------------------------------------------
change history
-------------------------------------------------------------
02/12/2008 dharadheer prathipati  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 = 600000; //60000=1min

$(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();
	  },
	  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);




function parseXML() {
var strToAppend = '';
	//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() {
		strToAppend += '<tr>';
		strToAppend += '<td>' + $("County",this).text() + '</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="/";
}

// 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" ), "");
		}
	}
}
