//*---------------------------------------------------
// ONLOAD
//--------------------------------------------------*/
 
/* Simon Willison's addLoadEvent function allows you to stack up 'window.onload' events 
without them stepping on each other's toes. 
It's explained here - http://www.sitepoint.com/blog-post-view.php?id=171578 */

function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      oldonload();
      func();
    }
  }
}


/* new accessible, unobtrusive popup code */

function windowLinks() {                      // create a new function called windowLink(); 
    if(!document.getElementsByTagName) {      // Only run the function on browsers that
         return;                              // understand 'getElementsByTagName' - new browsers
    }
	
    var anchors = document.getElementsByTagName("a"); // grab all links and pop them in an array called 'anchors'
    for (var i = 0; i < anchors.length; i++) {        // start a loop to work our way through 
         var anchor = anchors[i];                     // grab the next link & copy it to 'anchor' for working
         var classIndex = anchor.className;                   // get the value of it's 'class' attribute
		 if (classIndex) {                               // does it have a value for class?...
			if (classIndex == "lock") {
				anchor.title = "Launch a secure web page.";
			} else if (classIndex == "pdf") {
				anchor.title = "Launch an Adobe Acrobat PDF document.";
			} else if (classIndex == "popupteco") {
				anchor.title = "Launch a TECO Energy website in a new window.";
			} else if (classIndex == "popup") {
				anchor.title = "Launch a new window.";
			}
		}
	  }
} 

addLoadEvent(function() {
	windowLinks();	// run our new function as soon as the page loads. 
});




//*---------------------------------------------------
// MISC
//--------------------------------------------------*/
// Submits a form when dropdown changed
function dropSubmit(object) {
	if (object.value != "")
		object.form.submit();
}

//*---------------------------------------------------
// TOGGLES VISIBILITY
// INPUTS: object, vis, dis
//--------------------------------------------------*/

function toggle(object, vis, dis) {
  if (document.getElementById) {
	  document.getElementById(object).style.visibility = vis;
	  document.getElementById(object).style.display = dis;
  }

  else if (document.layers && document.layers[object] != null) {
	  document.layers[object].visibility = vis;
	  document.layers[object].display = dis;
  }

  else if (document.all) {
	  document.all[object].style.visibility = vis;
	  document.all[object].style.display = dis;
  }

  return false;
}


// Toggles a div if atleast one radio or checkbox is checked
function showDivIfChecked (list, div) {
	var checked = false;
	for (var i=0, n=list.length; i<n; i++) {
		if (list[i].checked) {
			checked = true;
			break;
		}
	}
	if (checked) {
		toggle(div,'visible','block');
	} else {
		toggle(div,'hidden','none');
	}
}



//*---------------------------------------------------
// ROLLOVERS
//--------------------------------------------------*/

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}



//*---------------------------------------------------
// TEXTAREA COUNTER
//--------------------------------------------------*/
function textCountDown (field, maxCount, targetDiv) {
	var countdown = maxCount - field.value.length;
	var target;
	if (document.getElementById) {
		target = document.getElementById(targetDiv);
	} else if (document.layers && document.layers[targetDiv] != null) {
		target = document.layers[targetDiv];
	} else if (document.all) {
		target = document.all[targetDiv];
	}
	if (field.value.length > maxCount) {
		field.value = field.value.substring(0, maxCount);
	} else {
		target.innerHTML = '(' + countdown + ' characters left)';
	}
}


//*---------------------------------------------------
// VALIDATION
//--------------------------------------------------*/

// Checks if a field is empty, alerts a message and focuses on the control
function isEmpty (field, msg) {
	if (field.value == '') {
		// Alert and focus if a message is defined
		if (msg != undefined) {
			alert(msg);
			field.focus();
		}
		return true;
	} else {
		return false;
	}
}

// Compares two field strings
function isEqual (InString1, InString2, msg) {
	if (InString1.value != InString2.value) {
		// Alert and focus if a message is defined
		if (msg != undefined) {
			alert(msg);
			InString1.focus();
		}
		return false;
	} else {
		return true;
	}
}

// Checks if a field is an email address, alerts a message and focuses on the control
function isEmail (field, msg) {
	var txt = field.value;
	var AtSym  = txt.indexOf('@');
	var Period = txt.lastIndexOf('.');
	var Space  = txt.indexOf(' ');
	var Length = txt.length - 1;				// Array is from 0 to length-1
	
	if ((txt.length == 0) ||				// Empty
		(AtSym < 1) ||						// '@' cannot be in first position
		(Period <= AtSym+1) ||				// Must be atleast one valid char btwn '@' and '.'
		(Period == Length ) ||				// Must be atleast one valid char after '.'
		(Space  != -1))						// No empty spaces permitted
		{
			// Alert and focus if a message is defined
			if (msg != undefined) {
				if (msg == 'default') {
					alert("Please enter a valid E-mail Address.");
				} else {
					alert(msg);
				}
				field.focus();
			}
			return false;
	}

	return true;
}

// Verifies complete phone number
function isPhone (phoneArea, phonePre, phoneSub, msg) {
	if (!mask(phoneArea.value,"###") || !mask(phonePre.value,"###") || !mask(phoneSub.value,"####")) {
		// Alert and focus if a message is defined
		if (msg != undefined) {
			alert(msg);
			phoneArea.focus();
		}
		return false;
	} else {
		return true;
	}
}

// mask() takes two parameters -- an input string and a mask string.  The function loops through each character of the mask string, then compares the same position char of the input against the mask (e.g., takes the 1st char of the mask and compares 1st char of input; 2nd char of mask, 2nd char of input; etc...) This forces the phone numbers to 3 and 4 digits, only allowing numbers to be used.
function mask (InString, Mask) {
	LenStr = InString.length;
	LenMsk = Mask.length;
	if ((LenStr==0) || (LenMsk==0))
		return(0);
	if (LenStr!=LenMsk)
		return(0);
	TempString = "";
	for (Count=0; Count<=InString.length; Count++) {
		StrChar = InString.substring(Count, Count+1);
		MskChar = Mask.substring(Count, Count+1);
		if (MskChar=='#') {
			if (!isNumber(StrChar))
				return(0);
		} else if (MskChar=='?') {
			if (!isAlphabeticChar(StrChar))
				return(0);
		} else if (MskChar=='!') {
			if (!isNumOrChar(StrChar))
				return(0);
		} else if (MskChar=='*') {
		} else {
			if (MskChar!=StrChar) 
				return(0);
		}
	}
	return (1);
}

// isAlphabeticChar() checks a single character to see if it is alpha.
function isAlphabeticChar (fieldOrStr, msg) {
	if (fieldOrStr.length != undefined) {
		InString = fieldOrStr;
	} else {
		InString = fieldOrStr.value;
	}
	var valid = true;
	if (InString.length != 1)
		valid = false;
	InString = InString.toLowerCase();
	RefString = "abcdefghijklmnopqrstuvwxyz";
	if (RefString.indexOf(InString.toLowerCase(), 0) == -1) 
		valid = false;
	// Alert and focus if a message is defined
	if (!valid && (msg != undefined)) {
		alert(msg);
		fieldOrStr.focus();
	}
	return valid;
}

// isNumber()
function isNumber (fieldOrStr, msg) {
	if (fieldOrStr.length != undefined) {
		InString = fieldOrStr;
	} else {
		InString = fieldOrStr.value;
	}
	if (parseInt(InString,10) != InString) {
		if (msg != undefined) {
			alert(msg);
			fieldOrStr.focus();
		}
		return false;
	}
	return true;
}

// isNumOrChar()
function isNumOrChar (fieldOrStr, msg) {
	if (fieldOrStr.length != undefined) {
		InString = fieldOrStr;
	} else {
		InString = fieldOrStr.value;
	}
	var valid = true;
	if (InString.length != 1) 
		valid = false;
	RefString = "1234567890abcdefghijklmnopqrstuvwxyz";
	if (RefString.indexOf(InString.toLowerCase(), 0) == -1) 
		valid = false;
	// Alert and focus if a message is defined
	if (!valid && (msg != undefined)) {
		alert(msg);
		fieldOrStr.focus();
	}
	return valid;
}

// Verify decimal
function isDecimal (fieldOrStr, msg) {
	if (fieldOrStr.length != undefined) {
		InString = fieldOrStr;
	} else {
		InString = fieldOrStr.value;
	}
//    if (InString.substring(0,1) == "0") {
//		InString = InString.substring(1,InString.length);
//	}
	if (("" + parseFloat(InString)) != InString) {
		if (msg != undefined) {
			alert(msg);
			fieldOrStr.focus();
		}
		return false;
	}
	return true;
}

// Verify Social Security Number
function isSSN (ssNo, msg) {
	if (!mask(ssNo.value,"###-##-####") && !mask(ssNo.value,"###-###-###")) {
		if (msg != undefined) {
			if (msg == 'default') {
				alert("Please enter your Social Security number in the format 999-99-9999 (US) or 999-999-999 (Can).");
			} else {
				alert(msg);
			}
			ssNo.focus();
		}
		return false;
	} else {
		return true;		 
	}
}

// Verify Social Security Number last three or four digits
function isSmSSN (ssNo, msg) {
	if (!mask(ssNo.value,"####") && !mask(ssNo.value,"###")) {
		if (msg != undefined) {
			if (msg == 'default') {
				alert("Please enter your the last part of your Social Security number in the format 9999 (US) or 999 (Can).");
			} else {
				alert(msg);
			}
			ssNo.focus();
		}
		return false;
	} else {
		return true;		 
	}
}

// Verify Federal Tax ID
function isTaxID (taxID, msg) {
	if (!mask(taxID.value,"##-#######")) {
		if (msg != undefined) {
			if (msg == 'default') {
				alert("Please enter your taxpayer ID in the format 99-9999999.");
			} else {
				alert(msg);
			}
			taxID.focus();
		}
		return false;
	} else {
		return true;		 
	}
}

// Checks for either Social Security Number or Federal Tax ID formatting
function isTaxIDOrSSN (taxID, msg) {
	if (!mask(taxID.value,"##-#######") && !mask(taxID.value,"###-##-####") && !mask(taxID.value,"###-###-###")) {
		if (msg != undefined) {
			if (msg == 'default') {
				alert("Please enter your Tax payer ID in the format 99-9999999 or your Social Security number in the format 999-99-9999 (US) or 999-999-999 (Can).");
			} else {
				alert(msg);
			}
			taxID.focus();
		}
		return false;
	} else {
		return true;		 
	}
}

// Checks for zipcode
function isZip(zipCode, msg) {
	if (!mask(zipCode.value,"#####") && !mask(zipCode.value,"#####-####") && !mask(zipCode.value,"???###")) {
		if (msg != undefined) {
			if (msg == 'default') {
				alert("Please enter the zip code in the format 99999 or 9999-9999 (US) or AAA999 (Can).");
			} else {
				alert(msg);
			}
			zipCode.focus();
		}
		return false;
	} else {
		return true;		 
	}
}

// Verifies radio or checkbox set has at least one item checked
function isChecked (list, msg) {
	var checked = false;
	for (var i=0, n=list.length; i<n; i++) {
		if (list[i].checked) {
			checked = true;
			break;
		}
	}
	// Alert and focus if a message is defined
	if (!checked && (msg != undefined)) {
		alert(msg);
		list[0].focus();
	}
	return checked;
}

// Verifies dropdown menu has at least one item selected
function isSelected (list, msg) {
	var selected = false;
	if ((list.selectedIndex != 0) || (list.value != '')) {
		selected = true;
	}
	// Alert and focus if a message is defined
	if (!selected && (msg != undefined)) {
		alert(msg);
		list.focus();
	}
	return selected;
}

// Validates mm/dd/yy and mm/dd/yyyy dates
function isDate (datefield, msg) {
	if (!dateCheck(datefield.value)) {
		if (msg != '') {
			alert(msg);
			datefield.focus();
		}
		return false
	}
	return true;
}
function dateCheck (dateval) {
	// Valid date check
	if (isNaN(new Date(dateval).getYear()))
		return (0);

	// Length check
	if ((dateval.length != 8) && (dateval.length != 10))
		return (0);

	// Formatting check
	a = dateval;
	
	slash1=a.indexOf("/");

	if ((slash1 == 0) || (slash1 == -1))
		return (0);

	d1 = slash1 + 1;
	
	slash2=a.indexOf("/", d1);
	
	if (slash2 == -1)
		return (0);
		
	y1 = slash2 + 1
	
	mm = a.substring(0, slash1)// month
	dd = a.substring(d1, slash2)// day
	if (dateval.length == 10) {
		yy = a.substr(y1+2, 2)// year
	} else {
		yy = a.substr(y1, 2)// year
	}
	
	if (yy.length != 2)
		return (0);

	//basic error checking
	if (mm<1 || mm>12) return (0);
	if (dd<1 || dd>31) return (0);
	if (yy<0 || yy>99) return (0);
	
	//advanced error checking

	// months with 30 days
	if (mm==4 || mm==6 || mm==9 || mm==11)
		{
		if (dd==31) return (0);
			}

	// february, leap year
	if (mm==2)
		{
		// feb
		var g=parseInt(yy/4,10)
		if (isNaN(g)) 
			{
			return (0);
			}

		if (dd>29) return (0);
		if (dd==29 && ((yy/4)!=parseInt(yy/4,10))) return (0);
		}

	return true;
}

// Validates mm/dd/yy date difference with today against maximum date span
function isWithinDateSpan (fieldOrStr, span, msg) {
	if (fieldOrStr.length != undefined) {
		InString = fieldOrStr;
	} else {
		InString = fieldOrStr.value;
	}
	if (!dateCheck(InString)) {
		return false
	}
	a = InString;
	slash1 = a.indexOf("/");
	d1 = slash1 + 1;
	slash2 = a.indexOf("/", d1);
	y1 = slash2 + 1
	mm = parseInt(a.substring(0, slash1),10) -1
	dd = a.substring(d1, slash2)
	yy = 20 + a.substr(y1, 2)
	
	Today = new Date();
	msTodayPlus = Today.getTime() + (span * 24 * 60 * 60 * 1000)
	CompareDate = new Date(yy,mm,dd);
	msCompareDate = CompareDate.getTime();
	msDiff = msTodayPlus - msCompareDate
	if (msDiff < 0) {
		if (msg != undefined) {
			alert(msg);
			if (fieldOrStr.length == undefined) {
				fieldOrStr.focus();
			}
		}
		return false;
	}
	return true;
}

// Validates mm/dd/yy date difference with today against minimum date span
function isOutsideDateSpan (fieldOrStr, span, msg) {
	if (fieldOrStr.length != undefined) {
		InString = fieldOrStr;
	} else {
		InString = fieldOrStr.value;
	}
	if (!dateCheck(InString)) {
		return false
	}
	a = InString;
	slash1 = a.indexOf("/");
	d1 = slash1 + 1;
	slash2 = a.indexOf("/", d1);
	y1 = slash2 + 1
	mm = parseInt(a.substring(0, slash1),10)-1
	dd = a.substring(d1, slash2)
	yy = 20 + a.substr(y1, 2)
	
	Today = new Date();
	msTodayPlus = Today.getTime() + (span * 24 * 60 * 60 * 1000)
	CompareDate = new Date(yy,mm,dd);
	msCompareDate = CompareDate.getTime();
	msDiff = msCompareDate - msTodayPlus;
	if (msDiff < 0) {
		if (msg != undefined) {
			alert(msg);
			if (fieldOrStr.length == undefined) {
				fieldOrStr.focus();
			}
		}
		return false;
	}
	return true;
}

// Verifies proper TEC meter number
function isMeterNum(meterNo) {
	if (!mask(meterNo.value,"!#####")) {
		alert("Please enter the meter number in the format '999999' or 'A12345'.");
		meterNo.focus();
		return false;
	} else {
		return true;		 
	}
}


// Verifies proper TEC account number
function isTECAcctNum(InTECAcctNo) {
	AcctNo="";

	for(x = 0; x < InTECAcctNo.length; x++)
	{
		if (InTECAcctNo.charAt(x)=="1" ||
		    InTECAcctNo.charAt(x)=="2" ||
			InTECAcctNo.charAt(x)=="3" ||
			InTECAcctNo.charAt(x)=="4" ||
			InTECAcctNo.charAt(x)=="5" ||
			InTECAcctNo.charAt(x)=="6" ||
			InTECAcctNo.charAt(x)=="7" ||
			InTECAcctNo.charAt(x)=="8" ||
			InTECAcctNo.charAt(x)=="9" ||
			InTECAcctNo.charAt(x)=="0" ||
			InTECAcctNo.charAt(x)==" " ||
			InTECAcctNo.charAt(x)=="-")
		{
			if (InTECAcctNo.charAt(x) != " " &&
			    InTECAcctNo.charAt(x) != "-")
			{
				AcctNo = AcctNo + InTECAcctNo.charAt(x);
			}
		}
		else
		{
		alert("The Tampa Electric account number you have entered is incorrect.");
		return false;
		}
	}
	
	if (AcctNo.length == 11)
	{
		if (AcctNo.substring(0,2) >= "01" && AcctNo.substring(0,2) <= 21)
		{
			if (AcctNo.substring(2,4) == "00" ||
				AcctNo.substring(2,4) == "01" ||
				AcctNo.substring(2,4) == "11" ||
				AcctNo.substring(2,4) == "12" ||
				AcctNo.substring(2,4) == "13" ||
				AcctNo.substring(2,4) == "16" ||
				AcctNo.substring(2,4) == "17" ||
				AcctNo.substring(2,4) == "20" ||
				AcctNo.substring(2,4) == "21" ||
				AcctNo.substring(2,4) == "25" ||
				AcctNo.substring(2,4) == "28" ||
				AcctNo.substring(2,4) == "30" ||
				AcctNo.substring(2,4) == "35" ||
				AcctNo.substring(2,4) == "37" ||
				AcctNo.substring(2,4) == "51" ||
				AcctNo.substring(2,4) == "61" ||
				AcctNo.substring(2,4) == "76" ||
				AcctNo.substring(2,4) == "77" ||
				AcctNo.substring(2,4) == "81" ||
				AcctNo.substring(2,4) == "82" ||
				AcctNo.substring(2,4) == "90" ||
				AcctNo.substring(2,4) == "91" ||
				AcctNo.substring(2,4) == "98")
			{
				MultByString = "432765432";
				ChecksumValue = 0;
				for(x = 0; x < 9; x++)
				{
					ChecksumValue = ChecksumValue + (MultByString.charAt(x) * AcctNo.charAt(x));
				}
				if (ChecksumValue % 11 == 0 ||
					ChecksumValue % 11 == 1)
				{
					CheckDigit = ChecksumValue % 11
				}
				else
				{
				CheckDigit = 11 - (ChecksumValue % 11)
				}
				if (AcctNo.charAt(9) != CheckDigit)
				{
				alert("The Tampa Electric account number you have entered is incorrect.");
				return false;
				}
			}
			else
			{
			alert("The Tampa Electric account number you have entered is incorrect.");
			return false;
			}
		}
		else
		{
		alert("The Tampa Electric account number you have entered is incorrect.");
		return false;
		}
	}
	else
	{
	alert("The Tampa Electric account number you have entered is incorrect.");
	return false;
	}

	return true;
}

// Verifies proper ABA number
function isAbaNum(InABANo) {
	for(x = 0; x < InABANo.length; x++) {
		if (InABANo.charAt(x)=="1" ||
			InABANo.charAt(x)=="2" ||
			InABANo.charAt(x)=="3" ||
			InABANo.charAt(x)=="4" ||
			InABANo.charAt(x)=="5" ||
			InABANo.charAt(x)=="6" ||
			InABANo.charAt(x)=="7" ||
			InABANo.charAt(x)=="8" ||
			InABANo.charAt(x)=="9" ||
			InABANo.charAt(x)=="0" )
		{
		} else {
			return false;
		}
	}
	
	if (InABANo.length != 9) {
		return false;
	}
	
	if (InABANo.charAt(0) != "0" &&
		InABANo.charAt(0) != "1" &&
		InABANo.charAt(0) != "2" &&
		InABANo.charAt(0) != "3") {
		return false;
	}
	
	return true;
}

// Prompts user to confirm their email address
function emailPrompt(email) { 
	if (!confirm("The e-mail address that you have entered is " + email.value  + "\nPlease check it for accuracy as we will be unable to complete your request if it is incorrect.\n\nClick the 'OK' button if the e-mail address is correct or use the 'Cancel' button to return to the form and make a correction.")) {
		email.focus();
		return false;
	}
	return true;
}

// trims leading or trailing spaces
function trim(str) { 
	str = str.replace(/^\s*/, '').replace(/\s*$/, ''); 
	return str;
}

/*
formatDollar() takes numerical input and formats it to have exactly two decimal places by adding trailing zeroes, if necessary (e.g., $3.5 this will be $3.50)
*/
function formatDollar (Val, DollarSign)  {
	Val=""+Val;
	if (Val.indexOf (".", 0)!=-1) {
		Dollars = Val.substring(0, Val.indexOf (".", 0));
		Cents = Val.substring(Val.indexOf (".", 0)+1, Val.indexOf (".", 0)+3);
		if (Cents.length==0) 
			Cents="00";
		if (Cents.length==1)
			Cents=Cents+"0";
	} else {
		Dollars = Val;
		Cents = "00";
	}

	if (DollarSign)
		return ("$"+Dollars+"."+Cents);
	else
		return (Dollars+"."+Cents);

}