//------------------------------------------------------------------------
// Declarations 
//------------------------------------------------------------------------
var isNS = navigator.appName.indexOf("Netscape") >= 0
var isMinNS4 = (navigator.appName.indexOf("Netscape") >= 0 && (parseFloat(navigator.appVersion) >= 4 && parseFloat(navigator.appVersion) < 5)) ? 1 : 0;
var isMinNS6 = (parseFloat(navigator.appVersion) >= 5) ? 1 : 0;
var isMinIE4 = (document.all) ? 1 : 0;
var isMinIE5 = (isMinIE4 && navigator.appVersion.indexOf("5.")) >= 0 ? 1 : 0;
var wpopup;


var xMousePos = 0; // Horizontal position of the mouse on the screen
var yMousePos = 0; // Vertical position of the mouse on the screen
var xMousePosMax = 0; // Width of the page
var yMousePosMax = 0; // Height of the page

var gAutoPrint = true; // Flag for whether or not to automatically call the print function
var gAllowSubmit = false; //flag to indicate whther focus is on a button. if it is not and
						//enter clicked, stop the submit from ocurring.
//used when user enteres a load on temp load page that requires flicker
var gLoadEnteredWhichRequiresFlicker = false;
var pickAddressArray;

var InSiteTransfer = false;

var PermSvc = 0;
var TempSvc = 1;
var RelocSvc = 2;
var RemovalOfSvc=3;
var IncreaseInSvc=3;
//save the last input item with focus
var lastFocus = null;
// Set Netscape up to run the "captureMousePosition" function whenever
// the mouse is moved. For Internet Explorer and Netscape 6, you can capture
// the movement a little easier.
if (document.layers) { // Netscape
    document.captureEvents(Event.MOUSEMOVE);
    document.onmousemove = captureMousePosition;
} else if (document.all) { // Internet Explorer
    document.onmousemove = captureMousePosition;
} else if (document.getElementById) { // Netcsape 6
    document.onmousemove = captureMousePosition;
}

function SaveFocus(obj)
{
lastFocus = obj;
} 
//set global flag indicating whether to allow or disallow submit.
//to stop enter key from submitting
function SetupHandlersForEventKeySubmitCheck(obj)
{
     if (obj.type == "submit")
     {
     //use deactivate event because on blur for some reason ran after on focus!
       // obj.onfocus = function() {alert("alow true"); gAllowSubmit = true;}
       // obj.ondeactivate = function() {alert("alow false"); gAllowSubmit = false;}
        obj.onfocus = function() { gAllowSubmit = true;}
        obj.ondeactivate = function() { gAllowSubmit = false;}
         
     }  
     else
     //capture input item with last focus. must also set it to false again else
     //when they click enter twice in same field, second time let's
     //them thru.  id on't know why.
     obj.onfocus = function() {gAllowSubmit = false; SaveFocus(this);};


}
//Capture Mouse Position on the screen
function captureMousePosition(e) {
    if (document.layers) {
        // When the page scrolls in Netscape, the event's mouse position
        // reflects the absolute position on the screen. innerHight/Width
        // is the position from the top/left of the screen that the user is
        // looking at. pageX/YOffset is the amount that the user has 
        // scrolled into the page. So the values will be in relation to
        // each other as the total offsets into the page, no matter if
        // the user has scrolled or not.
        xMousePos = e.pageX;
        yMousePos = e.pageY;
        xMousePosMax = window.innerWidth+window.pageXOffset;
        yMousePosMax = window.innerHeight+window.pageYOffset;
    } else if (document.all) {
        // When the page scrolls in IE, the event's mouse position 
        // reflects the position from the top/left of the screen the 
        // user is looking at. scrollLeft/Top is the amount the user
        // has scrolled into the page. clientWidth/Height is the height/
        // width of the current page the user is looking at. So, to be
        // consistent with Netscape (above), add the scroll offsets to
        // both so we end up with an absolute value on the page, no 
        // matter if the user has scrolled or not.
        xMousePos = window.event.x;
        yMousePos = window.event.y;
        xMousePosMax = document.body.clientWidth+document.body.scrollLeft;
        yMousePosMax = document.body.clientHeight+document.body.scrollTop;
    } else if (document.getElementById) {
        // Netscape 6 behaves the same as Netscape 4 in this regard 
        xMousePos = e.pageX;
        yMousePos = e.pageY;
        xMousePosMax = window.innerWidth+window.pageXOffset;
        yMousePosMax = window.innerHeight+window.pageYOffset;
    }
}

//Load Pages
function HandleLoad(ctlCheck)
{
  window.close();
}

//Residential Single
function HandleRSProjectInfoDivs(serviceRequested, ctlCheck, ctlReloc, valRequiredSvcDate, valRequiredDesc)
{
   EnableAllAddressValidator(true);	
   switch(serviceRequested)
   {      
       case "Permanent":
		   EnablePermSvcValidators(false);//Disable all Perm svc validators
           if (document.getElementById(ctlCheck).checked == true)
           {
               ToggleDiv("_divNewHomeForPermanentAddressSpan", 1);
               ToggleDiv("_divSiteInformationForPermSvc", 1);
               SetHiddenField(PermSvc, '1');
               EnablePermSvcAsteriskValidators(true);
               EnablePermAddressValidator(true);
           }
           else{			  		
               ToggleDiv("_divNewHomeForPermanentAddressSpan", 0);
               ToggleDiv("_divSiteInformationForPermSvc", 0);
               ToggleDiv("_divMeterLocReqTownHouses", 0);
               SetHiddenField(PermSvc, '0');
               EnablePermSvcAsteriskValidators(false);
               EnablePermAddressValidator(false);
           }
           break;
           
       case "Temporary": 
           EnableTempSvcValidators(false); //Disable all temp svc validators
           
           if (document.getElementById(ctlCheck).checked == true)
           {
               ToggleDiv("_divTemporarySvcAddressSpan", 1);
               SetHiddenField(TempSvc, '1');
               EnableTempSvcAsteriskValidators(true);
               EnableTempAddressValidator(true);
           }
           else{
               ToggleDiv("_divTemporarySvcAddressSpan", 0);
               SetHiddenField(TempSvc, '0');
               EnableTempSvcAsteriskValidators(false);
               EnableTempAddressValidator(false);
           }
           break;
           
       case "Relocation":
           EnableRelocSvcValidators(false); //disable reloc validators
           if (document.getElementById(ctlCheck).checked == true)
           {
               ToggleDiv("_divRelocationSvcAddressSpan", 1);
               SetHiddenField(RelocSvc, '1');
               EnableReloSvcAsteriskValidators(true); //Enable Asterisk Validators
               EnableReloAddressValidator(true);
           }
           else{
               ToggleDiv("_divRelocationSvcAddressSpan", 0);
               SetHiddenField(RelocSvc, '0'); //set the selected service
               EnableReloSvcAsteriskValidators(false);
               EnableReloAddressValidator(false);
           }
           break;
           
       case "Removal":
           if (document.getElementById(ctlCheck).checked == true)
           {
               ToggleDiv("_divRelocationSvcAddressSpan", 1);
               SetHiddenField(RemovalOfSvc, '1');
           }
           else{
               ToggleDiv("_divRelocationSvcAddressSpan", 0);
               SetHiddenField(RemovalOfSvc, '0'); //set the selected service
           }
           break;
       default:
           break;
   }
   var str = document.frmMain._selectedServiceHidden.value;
   var obj = document.getElementById(ctlReloc);
   var checkState = obj.checked;
   //alert (obj.checked);
   //alert(str);
   if ((str.charAt(PermSvc) == '0') && (str.charAt(TempSvc) == '0'))
   { //Perm or Temp Not Selected, disable reloc
       obj.disabled = true;
       if (obj.checked)
       {
           obj.checked = false;
           //alert('Turn it off');
           ToggleDiv("_divRelocationSvcAddressSpan", 0);
           SetHiddenField(RelocSvc, '0'); //set the selected service
           EnableRelocSvcValidators(false);  
       }
   }
   else
   {
       obj.disabled = false;
       obj.checked = checkState;
   }
   //alert (obj.checked);
   
}


//Residential Development
function HandleRDProjectInfoDivs(serviceRequested, ctlCheck, valRequiredSvcDate, ctlTypeOfService, ctlSvcDate, ctlSvcDesc, ctlBtnCal)
{  
   EnableAllAddressValidator(true);
   switch(serviceRequested)
   {
       case "Permanent":
           if (document.getElementById(ctlCheck).checked == true)
           {
               SetHiddenField(PermSvc, '1');
           }
           else{
               SetHiddenField(PermSvc, '0');
           }
           break;
       case "Temporary":
		   EnableTempSvcValidators(false);
		   var chkTempSvc = GetElement(ctlCheck);
           //If Gas Service only, disable/deselect Temporary
		   var ctl = GetElement(ctlTypeOfService);
		   if (ctl != null){
		        var tempSvcDate = GetElement(ctlSvcDate);
		        var tempSvcPurpose = GetElement(ctlSvcDesc);
		        var calPopup = GetElement(ctlBtnCal);
				if (ctl.options[ctl.selectedIndex].value == "G"){
				   chkTempSvc.checked = false;
				   chkTempSvc.disabled = true;
				   tempSvcDate.disabled = true;
				   tempSvcDate.value = "";
				   tempSvcPurpose.disabled = true;
				   tempSvcPurpose.value = "";
				   calPopup.disabled = true;
				}
				else{
				    chkTempSvc.disabled = false;
				    tempSvcDate.disabled = false;
				    tempSvcPurpose.disabled = false;
				    calPopup.disabled = false;
				}
		   }
           if (chkTempSvc.checked == true)
           {
				
               ToggleDiv("_divTemporarySvcAddressSpan", 1);
               SetHiddenField(TempSvc, '1');
               //Enable asterisk Validators
               EnableTempSvcAsteriskValidators(true);
               EnableTempAddressValidator(true);
           }
           else{
				ToggleDiv("_divTemporarySvcAddressSpan", 0);
               SetHiddenField(TempSvc, '0');
               EnableTempSvcAsteriskValidators(false);
               EnableTempAddressValidator(false);
           }
           break;
       case "Relocation":
           EnableRelocSvcValidators(false);
           if (document.getElementById(ctlCheck).checked == true)
           {
			   ToggleDiv("_divRelocationSvcAddressSpan", 1);
               SetHiddenField(RelocSvc, '1');
               EnableRelocSvcAsteriskValidators(true);
               EnableRelocAddressValidator(true);
           }
           else{
               ToggleDiv("_divRelocationSvcAddressSpan", 0);
               SetHiddenField(RelocSvc, '0'); //set the selected service
               EnableRelocSvcAsteriskValidators(false);
               EnableRelocAddressValidator(false);
           }
           break;
       default:
           break;    
   }
}


//Residential Modification
function HandleRMProjectInfoDivs(serviceRequested, ctlCheck)
{   
   EnableAllAddressValidator(true);
   switch(serviceRequested)
   {
       case "Permanent":
           if (document.getElementById(ctlCheck).checked == true)
           {
               SetHiddenField(PermSvc, '1');
           }
           else{
               SetHiddenField(PermSvc, '0');               
           }
           break;
       case "Increase":
           if (document.getElementById(ctlCheck).checked == true)
           {
               SetHiddenField(IncreaseInSvc, '1');
           }
           else{

               SetHiddenField(IncreaseInSvc, '0');
           }
           break;
       case "Relocation":
           if (document.getElementById(ctlCheck).checked == true)
           {
               SetHiddenField(RelocSvc, '1');
           }
           else{
               SetHiddenField(RelocSvc, '0'); //set the selected service
           }
           break;
       default:
		   break;
   }
}


//Commercial and Industrial
function HandleCIProjectInfoDivs(serviceRequested, ctlCheck, valRequiredSvcDate)
{  
   EnableAllAddressValidator(true);	 
   switch(serviceRequested)
   {
       case "Permanent":
           EnablePermSvcValidators(false);
           if (document.getElementById(ctlCheck).checked == true)
           {
			   ToggleDiv("_divProjectAddressSpan", 1);
               SetHiddenField(PermSvc, '1');
               EnablePermSvcAsteriskValidators(true);
               EnablePermAddressValidator(true);
           }
           else{
               ToggleDiv("_divProjectAddressSpan", 0);
               SetHiddenField(PermSvc, '0');
               EnablePermSvcAsteriskValidators(false);
               EnablePermAddressValidator(false);
           }
           break;
       case "Temporary":
           EnableTempSvcValidators(false);
           if (document.getElementById(ctlCheck).checked == true)
           {
               ToggleDiv("_divTemporarySvcAddressSpan", 1);
               SetHiddenField(TempSvc, '1');
               EnableTempSvcAsteriskValidators(true);
               EnableTempAddressValidator(true);
           }
           else{
               ToggleDiv("_divTemporarySvcAddressSpan", 0);
               SetHiddenField(TempSvc, '0');
               EnableTempSvcAsteriskValidators(false);
               EnableTempAddressValidator(false);
           }
           break;
       case "Relocation":
           EnableReloSvcValidators(false);
           if (document.getElementById(ctlCheck).checked == true)
           {
               //ToggleDiv("_divRelocationSvcAddressSpan", 1);
               SetHiddenField(RelocSvc, '1');
               EnableReloSvcAsteriskValidators(true);
               EnableReloAddressValidator(true);
           }
           else{
               //ToggleDiv("_divRelocationSvcAddressSpan", 0);
               SetHiddenField(RelocSvc, '0'); //set the selected service
               EnableReloSvcAsteriskValidators(false);
               EnableReloAddressValidator(false);
           }
           break;
        case "Removal":
           EnableRemovalSvcValidators(false);
           if (document.getElementById(ctlCheck).checked == true)
           {
               //ToggleDiv("_divRelocationSvcAddressSpan", 1);
               SetHiddenField(RemovalOfSvc, '1');
               EnableRemovalSvcAsteriskValidators(true);
           }
           else{
               //ToggleDiv("_divRelocationSvcAddressSpan", 0);
               SetHiddenField(RemovalOfSvc, '0'); //set the selected service
               EnableRemovalSvcAsteriskValidators(false);
           }
           break;
       default:
           break;
   }
   
   var str = document.frmMain._selectedServiceHidden.value;
   if ((str.charAt(RelocSvc) == '0') && (str.charAt(RemovalOfSvc) == '0')){ //Removal or Relocation not checked
       ToggleDiv("_divRelocationSvcAddressSpan", 0);
   }
   else{
       ToggleDiv("_divRelocationSvcAddressSpan", 1);
   }
}

//If Relocation Only then calls the DisableEnableFacilityInfo Method to Disable the SquareFootage and Hours Of Operation. Else it will Enable them.
function HandleFacilityInfo(ChkBxPerm, ChkBxTemp, ChkBxRelo)	
{
  var CtlChkBxPerm = document.getElementById(ChkBxPerm);
  var CtlChkBxTemp = document.getElementById(ChkBxTemp);
  var CtlChkBxRelo = document.getElementById(ChkBxRelo);
  
  if ((CtlChkBxPerm.checked == false) && (CtlChkBxTemp.checked == false) && (CtlChkBxRelo.checked == true))
  {
     DisableEnableFacitlityInfo('Disable');
  }
  else
  {
	DisableEnableFacitlityInfo('Enable');
  }
}

//Disable SquareFootage and Hours of Operation in Facitlity Information in CI if the Service is RELO only.
function DisableEnableFacitlityInfo(EnableOrDisable)
{
   if (EnableOrDisable == 'Disable')
   {
	  FacilityArray[0].value = ''; 	
	  for (var i=1; i<FacilityArray.length; i++)
	  {
	     //FacilityArray[i].disabled = true;
	     FacilityArray[i].options.selectedIndex = 0;
	  }
	  for (var i=0; i<FacilityValidtrsArray.length; i++)
	  {
	    FacilityValidtrsArray[i].enabled = false;
	  }
	  for (var i=0; i<FacilityAsteriskArray.length; i++)
	  {
	    FacilityAsteriskArray[i].innerHTML = '';
	  }
   }
   
  if (EnableOrDisable == 'Enable')
  {
    /* for (var i=0; i<FacilityArray.length; i++)
	  {
	     FacilityArray[i].disabled = false;
	  }*/
	  for (var i=0; i<FacilityValidtrsArray.length; i++)
	  {
	    FacilityValidtrsArray[i].enabled = true;
	  }
	  for (var i=0; i<FacilityAsteriskArray.length; i++)
	  {
	    FacilityAsteriskArray[i].innerHTML = '*';
	  }
  }
 
}

//Common DIV routines
function HandleCommonDivs(sectionName, ctlCheck)
{
   switch(sectionName)
   {
       case "Townhouse":
           if (document.getElementById(ctlCheck).checked == true)
           {
               ToggleDiv("_divMeterLocReqTownHouses", 1);
           }
           else{
               ToggleDiv("_divMeterLocReqTownHouses", 0);
           }
           break;
           
       case "Attachments":
           if (document.getElementById(ctlCheck).checked == true)
           {
               ToggleDiv("_fileAttachmentDiv", 1);
           }
           else{
               ToggleDiv("_fileAttachmentDiv", 0);
           }
           break;
       default:
           break;
   }
}

//Show/Hide Div Tags
function ToggleDiv(szDivID, iState) // 1 visible, 0 hidden
{
    if(document.layers)	   //NN4+
    {
       document.layers[szDivID].visibility = iState ? "show" : "hide";
       document.layers[szDivID].display = iState ? "block" : "none";
    }
    else if(document.getElementById)	  //gecko(NN6) + IE 5+
    {
        var obj = document.getElementById(szDivID);
        obj.style.visibility = iState ? "visible" : "hidden";
        obj.style.display = iState ? "block" : "none";
    }
    else if(document.all)	// IE 4
    {
        document.all[szDivID].style.visibility = iState ? "visible" : "hidden";
        document.all[szDivID].style.display = iState ? "block" : "none";
    }
}

//Get Element
function GetElement(el) 
{
    if(document.layers)	   //NN4+
    {
       return document.layers[el];
    }
    else if(document.getElementById)	  //gecko(NN6) + IE 5+
    {
        return document.getElementById(el);
    }
    else if(document.all)	// IE 4
    {
        return document.all[szDivID];
    }
    return null;
}

function SetHiddenField(pos, fldValue)
{
    var i;
	var str = document.frmMain._selectedServiceHidden.value;
	var tempArray = new Array();
	var newStr;
	//alert('hiddy field' + str);
	newStr = "";
	for (i=0; i<4; i++)
	{
	    tempArray[i] = str.charAt(i);
	    if (i == pos){
	        tempArray[i] = fldValue;
	    }
	    newStr += tempArray[i];
	}
	//alert(newStr);
	document.frmMain._selectedServiceHidden.value = newStr;
}

//print the contents between two tags
function printContent(flHeaderOnly)
{
	if (document.getElementById != null)
	{
	    var i=0;
		var html = '<HTML>\n<HEAD>\n';

		if (document.getElementsByTagName != null)
		{
			var headTags = document.getElementsByTagName("head");
			if (headTags.length > 0){
			    html += headTags[0].innerHTML;			   
			}
		}
		
	
		//LCL added this for printing purposes. lessened width, made font size smaller so that
		//stuff not get cut off
		//because printer margins will be there and they are uncontrollable by our programs
		//as far as i know, and will cut it off
		html += "\n<LINK href=\"../styles/nubizprint.css\" type=text/css media=\"print\" rel=stylesheet>\n";
		html += '\n</HE' + 'AD>\n<BODY>' +  '\n';
		
		var printSectionHeader = document.getElementById("_divPrintHeader"); //First look for the PrintSection header
		var printSectionDetails = document.getElementById("_divPrintDetails"); //get detail section
		if (printSectionHeader != null && printSectionDetails != null)
		{
				html += printSectionHeader.innerHTML;
				if (!flHeaderOnly) //dont print details if header only flag
				    html += printSectionDetails.innerHTML;
				
		}
		else
		{
			alert("Can't print document.");
			return;
		}
			
		//lcl added table
		//html += '\n</TD></TR></TABLE></BODY>\n</HTML>';
		//html += '</DIV>';
		
		//var printWin = CenterWindow("TempPrintDialog", "Print", 650, 650)
		
		var sOption="toolbar=no,location=no,directories=no,menubar=no,"; 
		sOption+="scrollbars=yes,width=750,height=600,left=100,top=25"; 

		var printWin =window.open("","Print",sOption); 
		//alert("printWin = " + printWin);
		printWin.document.open();
		printWin.document.write(html);
		printWin.document.close(); //stop writing to the document
		if (gAutoPrint){
			{
			printWin.print();
			}	
		}
		
		//printWin.blur();
		//parent.focus();
	}
	else
	{
		alert("The print content feature is not supported on this browser.");
	}

}


// ****************************** General Utility Functions *******************/

//------------------------------------------------------------------------
function GetCookie (name) { 
    var arg = name + "=";  
    var alen = arg.length;  
    var clen = document.cookie.length; 
    var i = 0;  
    while (i < clen) {    
        var j = i + alen;    
        if (document.cookie.substring(i, j) == arg){      
            return GetCookieValue(j);    
        }
        i = document.cookie.indexOf(" ", i) + 1;    
        if (i == 0) break;   
    } 
    return null;
}


//------------------------------------------------------------------------
function SetCookie (name, value, expires, path, domain, secure) 
{  
    var defaultExpiration = new Date();
    defaultExpiration.setTime(defaultExpiration.getTime() + 1 * 24 * 60 * 60 * 1000);//Expire in 1 day
    var argv = SetCookie.arguments;  
    var argc = SetCookie.arguments.length;  
    var expires = (argc > 2) ? argv[2] : null;  
    if (expires == null)
        newExp = defaultExpiration;
    else
        newExp = expires;
    var path = (argc > 3) ? argv[3] : null;  
    var domain = (argc > 4) ? argv[4] : null;  
    var secure = (argc > 5) ? argv[5] : false;  
    document.cookie = name + "=" + escape (value) + 
        ((newExp == null) ? "" : ("; expires=" + newExp.toGMTString())) + 
        ((path == null) ? "" : ("; path=" + path)) +  
        ((domain == null) ? "" : ("; domain=" + domain)) +    
        ((secure == true) ? "; secure" : "");
}
//------------------------------------------------------------------------
function GetCookieValue (offset) 
{
    var endstr = document.cookie.indexOf (";", offset);
    if (endstr == -1)
        endstr = document.cookie.length;
    return unescape(document.cookie.substring(offset, endstr));
}
//------------------------------------------------------------------------
function DeleteCookie (name) {  
    var exp = new Date();  
    exp.setTime (exp.getTime() - 1);   
    var cval = GetCookie (name);  
    document.cookie = name + "=" + cval + "; expires=" + exp.toGMTString();
}
//------------------------------------------------------------------------
function PopSizable(sFile) {
	var sPlat = new String(navigator.platform);
	var sBrow = new String(navigator.appVersion);

	if (sPlat.indexOf("Mac")>=0 && sBrow.indexOf("MSIE")>=0) {
	} 
	else 
	{
		CloseWnd("wpopup");
	}
	//wpopup = CenterWindow("","w_popup","width=550,height=450,titlebar=yes,menubar=yes,scrollbars,status,resizable=yes,location=no,toolbar=yes");
	wpopup=window.open("","w_popup","width=550,height=450,titlebar=yes,menubar=yes,scrollbars=yes,status,resizable=yes,location=no,toolbar=yes");
	wpopup.location.href=sFile;
	if (wpopup.opener==null) wpopup.opener=window;
	wpopup.opener.name = "opener";
	wpopup.focus();
}       
//------------------------------------------------------------------------
function PopChild(sFile) {
	var sPlat = new String(navigator.platform);
	var sBrow = new String(navigator.appVersion);

	if (sPlat.indexOf("Mac")>=0 && sBrow.indexOf("MSIE")>=0){
	} 
	else 
	{
		CloseWnd("wpopup");
	}
	//wpopup=CenterWindow("","w_popup","width=550,height=400,titlebar=no,menubar=no,scrollbars,status");
	wpopup=window.open("","w_popup","width=550,height=400,titlebar=no,menubar=no,scrollbars=yes,status");
	wpopup.location.href=sFile;
	if (wpopup.opener==null) wpopup.opener=window;
	wpopup.opener.name = "opener";
	wpopup.focus();
}  
//------------------------------------------------------------------------
function CloseWnd(cName){
	var oWnd = eval(cName);
	var sPlat = new String(navigator.platform);
	var sBrow = new String(navigator.appVersion);
	if (sPlat.indexOf("Mac")>=0 && sBrow.indexOf("MSIE")>=0) {
			//if (typeof(oWnd)=="object") {
			//      oWnd.close();
			//}
	} else {                
		if (typeof(oWnd) != "undefined"){
			if (typeof(oWnd) == "object" || typeof(oWnd.name) == "string"){
				if (oWnd != null){
					if (typeof(oWnd.close) == "function" || typeof(oWnd.close) == "object")
					{
						oWnd.close();
					}
					eval(cName + "=null");
					oWnd = null;
				}
			}
		}
	}
}
//------------------------------------------------------------------------
function CloseWindow()
{
	window.close();
}
//------------------------------------------------------------------------
function CenterWindow(url, name, height, width) {
    var str = "height=" + height + ",innerHeight=" + height;
    str += ",width=" + width + ",innerWidth=" + width;
    if (window.screen) {
        var ah = screen.availHeight - 30;
        var aw = screen.availWidth - 10;

        var xc = (aw - width) / 2;
        var yc = (ah - height) / 2;

        str += ",left=" + xc + ",screenX=" + xc;
        str += ",top=" + yc + ",screenY=" + yc;
    }
    return window.open(url, name, str);
}
//Check to see if the string contains all-numeric characters
function isNumeric(strValue) 
{
    var valid = "0123456789";
    var ok = true;
    var temp;
    for (var i=0; i<strValue.length; i++) {
        temp = "" + strValue.substring(i, i+1);
        if (valid.indexOf(temp) == "-1"){
            ok = false;
        }
    }
	return ok;
}

function CheckNumeric(source, args) 
{
    if (args.Value.length < 1){
        args.IsValid = true;
        return;
    }
    if (isNumeric(args.Value))
    {
        args.IsValid = true;
    }
    else 
    {
        args.IsValid = false;
    }
}

function IsValidDate(source, args)
{
    if (args.Value.length < 1){
        args.IsValid = true;
        return;
    }
    if (isDate(args.Value)){
        args.IsValid = true;
    }
    else{
        args.IsValid = false;
    }
}

//Service Date must be in the future
function IsValidServiceDate(source, args)
{
    if (args.Value.length < 1){//allow blank date
        args.IsValid = true;
        return;
    }
    if (isDate(args.Value)){ //a valid date
        var dateEntered = new Date(args.Value);
        var currentDate = new Date();
        if (dateEntered > currentDate){
            args.IsValid = true;
        }
        else{
               args.IsValid = false;
               source.innerText = "Please enter a date greater than " + currentDate;
        }
    }
    else{
          args.IsValid = false; //Not a valid date
          source.innerText = "Please enter date in mm/dd/yyyy format.";
    }
}

//Permite Date Edit -- Must be a valid date in the past
function IsValidPermitDate(source, args)
{
    if (args.Value.length < 1){
        args.IsValid = true;
        return;
    }
    if (isDate(args.Value)){ //a valid date
        var dateEntered = new Date(args.Value);
        var currentDate = new Date();
        if (dateEntered < currentDate){
            args.IsValid = true;                                  
        }
        else{
            args.IsValid = false;
            source.innerText = "Please enter a valid Past Date.";
        }
    }
    else{
        args.IsValid = false; //Not a valid date
        source.innerText = "Please enter date in mm/dd/yyyy format.";
    }
}

function PopUpNumberOfLots(TxtNumOfLots)
{
   var CtlTxtNumOfLots = document.getElementById(TxtNumOfLots);
   if (CtlTxtNumOfLots.value < 5)
      alert('The Residential Development application is for 5 or more lots. You have indicated fewer lots. If you have less than 5 lots, please complete the Single Service Application.');
}

//Checks an entered for the typical date range for service (30 days from current date)
function normalDateRange(el, fieldName)
{
    var dt = el.value;
    if (dt.length < 1){
        return;
    }
    if (!isDate(dt)){
        return;
    }
    
    //Check for 30day range
    var thirtyDaysFromToday = new Date();
    var currentDate = new Date();
   // alert(thirtyDaysFromToday);
    thirtyDaysFromToday.setHours(24 * 30); //24 hours * 30 days
    
    var dateEntered = new Date(dt);
    if ((dateEntered > currentDate) && (dateEntered < thirtyDaysFromToday))
    {
        alert("The " + fieldName + " date you have selected for your project falls outside the typical turnaround time for BGE. Please select an alternate date or your BGE representative will discuss this date with you when they contact you about your project. You may proceed with this application for the date you have selected.");
    }
}



//Check for a valid date
function isDate(mmddyyyy)
{
	var reExp = /^\d{1,2}\/\d{1,2}\/\d{4}$/;
	var reg = new RegExp(reExp);
	if (reg.test(mmddyyyy)) 
	{
		var dArr = mmddyyyy.split("/");
		var d = new Date(mmddyyyy);
		return d.getMonth() + 1 == dArr[0] && d.getDate() == dArr[1] && d.getFullYear() == dArr[2];
	}
	else 
	{
		return false;
	}
}

//Was a service selected
function IsServiceSelected(source, args)
{ 
  	args.IsValid = false;
	var el;
	for (var i=0; i<svcCheckBoxArray.length; i++){
	    el = svcCheckBoxArray[i];
	    if (el.checked)
	    {
	        args.IsValid = true;
			SetCheckBoxesRequiredColor(svcCheckBoxArray, false);
			return;
	    }
	}
	SetCheckBoxesRequiredColor(svcCheckBoxArray, true);

}

//Required Phone Number client validation routine
function RequiredPhoneValidate(source, args){
    args.IsValid = false;
    var areaCode = "";
    var prefix = "";
    var suffix = "";
    //Get the values of the 3 fields that make up the phone number
    var ctl = source.id;
    if (ctl != null){
       var ctlName;
       var pos = ctl.indexOf("_PhoneRequired"); //Find the validator name
       if (pos >= 0){
           ctlName = ctl.substring(0, pos);
       }
       if (ctlName != null){
           areaCode = document.all[ctlName + "_PhoneAreaCode"].value;
           prefix = document.all[ctlName + "_PhonePart2"].value;
           suffix = document.all[ctlName + "_PhonePart3"].value;
		   if (areaCode.length > 0 || prefix.length > 0 || suffix.length > 0){
		       args.IsValid = true;
		   }
       }
    }   
}

//Valid Phone Number client validation
function ValidPhoneValidate(source, args){
    args.IsValid = false;
    var areaCode = "";
    var prefix = "";
    var suffix = "";
    //Get the values of the 3 fields that make up the phone number
    var ctl = source.id;
    if (ctl != null){
       var ctlName;
       var pos = ctl.indexOf("_PhoneValid"); //Find the validator name
       if (pos >= 0){
           ctlName = ctl.substring(0, pos);
       }
       if (ctlName != null){
           areaCode = document.all[ctlName + "_PhoneAreaCode"].value;
           prefix = document.all[ctlName + "_PhonePart2"].value;
           suffix = document.all[ctlName + "_PhonePart3"].value;
           //if blank, ok
           if (areaCode.length == 0 && prefix.length == 0 && suffix.length == 0){
               args.IsValid = true;
               return;
           }
           //if entered valid data in all fields
           if (isNumeric(areaCode) && areaCode.length==3 && isNumeric(prefix) && prefix.length==3 && isNumeric(suffix) && suffix.length==4){
		       args.IsValid = true;
		       return;
		   }
           //source.innerText = "Invalid";
		   if (!isNumeric(areaCode) ||!isNumeric(prefix) || !isNumeric(suffix)){
			source.innerText = "Invalid"
		   }else{
		   	source.innerText = "Incomplete Phone #"
		   }
		   return;
       }
    }   
}

//Valid Phone Number client validation
function ValidPhoneValidate1(source, args){
    args.IsValid = false;
    var areaCode = "";
    var prefix = "";
    var suffix = "";
    //Get the values of the 3 fields that make up the phone number
    var ctl = source.id;
    if (ctl != null){
       var ctlName;
       var pos = ctl.indexOf("_PhoneValid"); //Find the validator name
       if (pos >= 0){
           ctlName = ctl.substring(0, pos);
       }
       if (ctlName != null){
           areaCode = document.all[ctlName + "_PhoneAreaCode"].value;
           prefix = document.all[ctlName + "_PhonePart2"].value;
           suffix = document.all[ctlName + "_PhonePart3"].value;
           //if blank, ok
           if (areaCode.length == 0 && prefix.length == 0 && suffix.length == 0){
               args.IsValid = true;
               return;
           }
		   if (areaCode.length == 0 || (isNumeric(areaCode) && areaCode.length==3)){
			args.IsValid = true;
		   }else{
			args.IsValid = false;
			return;
		   }
		   if (prefix.length == 0 || (isNumeric(prefix) && prefix.length==3)){
			args.IsValid = true;
		   }else{
			args.IsValid = false;
			return;
		   }
		   if (suffix.length == 0 || (isNumeric(suffix) && suffix.length==4)){
		   	args.IsValid = true;
		   }else{
			args.IsValid = false;
			return;
		   }
       }
    }   
}

function IsApplianceSelectedGasLoad(source, args)
{ 
	args.IsValid = false;
	var el;
	for (var i=0; i<ApplianceCheckBoxArray.length; i++)
	{
	    el = ApplianceCheckBoxArray[i];
	    if (el.checked)
	    {
	        args.IsValid = true;
	         SetCheckBoxesRequiredColor(ApplianceCheckBoxArray,false);
	        return;
	    }
	}
	//else is error
	SetCheckBoxesRequiredColor(ApplianceCheckBoxArray,true);			

}

function IsApplianceSelectedElectricLoad(source, args)
{ 
	args.IsValid = false;
	var el;
	for (var i=0; i<ApplianceCheckBoxArrayElectricLoad.length; i++)
		{
	    el = ApplianceCheckBoxArrayElectricLoad[i];
	    if (el.checked)
			{
	         args.IsValid = true;
	         SetCheckBoxesRequiredColor(ApplianceCheckBoxArrayElectricLoad,false);
	         return;
			}
	    }
	//else is error. set class
	SetCheckBoxesRequiredColor(ApplianceCheckBoxArrayElectricLoad,true);			
	    
}
//set background yellow for checkbox fields athat AREN"T aspchecklist items
//(ie: are seperate checkboxes. if they are checklist, aps renders them with a span tag
//on the top , and when you set that span background, the checklist items become yellow. but,
//if they are seperate items, they don't have a surrounding span. also note that
//asp renders a checkbox's label, using the 'label' tag. why? i have no idea. but that fact combined with the
//fact that if you set the background color of a checkbox dynamically, it's text does NOT checngae to that color
//just the box), means we have to search for it's assocaited label and set the label's text
//to the require color. note that if you set a checkbox'es background color STATICALLY, not
//DYNAMICALLY, it DOES sert the associated label's text tot the background color. it only took me 4 hours
//to find out this ridiculous information.
function SetCheckBoxesRequiredColor(ctlArray, flag)
{
    var name;
    if (flag)
        name = "DataEntryErrorField";
    else
        name = "DataEntryField";
        
	for (var i=0; i<ctlArray.length; i++)
	{
	    var el = ctlArray[i];
	        
		el.className = name;
		//also set its label field
		var zeeLabel = FindCheckboxLabel(ctlArray[i].id);
		zeeLabel.className = name;	
		zeeLabel.className = "strong";
	}
}

function FindCheckboxLabel(ctlId)
{
	var LabelTags = document.getElementsByTagName("Label");
	for (var i=0; i < LabelTags.length; i++)
	{
		if (LabelTags[i].htmlFor == ctlId)
		   return LabelTags[i];	
	}
}

function IsElectricTypeSelectedElectricLoad(source, args)
{ 
	args.IsValid = false;
	var el;
	var e2;
	for (var i=0; i<ElectricTypeCheckBoxArrayElectricLoad.length; i++)
	{
	    el = ElectricTypeCheckBoxArrayElectricLoad[i];
	    if (el.checked)
	    {
		    args.IsValid = true;	      
	    }
	}
	
	if (args.IsValid)
	{
		for (var i=0; i<ElectricTypeCheckBoxArrayElectricLoad.length; i++)
		{
			e2 = ElectricTypeCheckBoxArrayElectricLoad[i];
			e2.className = "DataEntryField";
	    }	  
	}
	else
	{
		for (var i=0; i<ElectricTypeCheckBoxArrayElectricLoad.length; i++)
		{
			e2 = ElectricTypeCheckBoxArrayElectricLoad[i];
			e2.className = "DataEntryErrorField";
	    }
	}
	return;
}


//Is a checkboxlist control checked
function IsCheckBoxListSelected(ctl)
{ 
	var col = ctl.all;
	if ( col != null ) {
        for ( i = 0; i < col.length; i++ ){
            if (col.item(i).tagName == "INPUT"){
                if ( col.item(i).checked ){
                    return true;
                }
            }
        }
    }
    return false;
}

//Custom Validator Function -- Is a Checkbox Item selected
function IsTypeOfConstructionSelected(source, args)
{ 
	args.IsValid = false;
    var ctl = checkBoxListArray[0];//the checkbox control which is saved as an array on the form
	var col = ctl.all;
	if ( col != null ) {
        for ( i = 0; i < col.length; i++ ){
            if (col.item(i).tagName == "INPUT"){
                if ( col.item(i).checked ){
                    args.IsValid = true;
                    return;
                }
            }
        }
    }
}

//------------------------------------------------------------------------
function parseQueryString (str, item) 
{
    str = str ? str : location.search;
    if (str.length < 1){
        return "";
    }
    var query = str.charAt(0) == '?' ? str.substring(1) : str;
    var args = new Object();
    if (query) {
        var fields = query.split('&');
        for (var f = 0; f < fields.length; f++) {
            var field = fields[f].split('=');
            args[unescape(field[0].replace(/\+/g, ' '))] = unescape(field[1].replace(/\+/g, ' '));
        }
    }
    for (var arg in args) {
        if (arg == item){
            return args[arg];
        }
    }
    return "";
}

//------------------------------------------------------------------------
function Back()
{
    var howMany = GetCookie("GoBackHowMany");
    //alert(eval(howMany));
    SetCookie("GoBackHowMany", "-1");
    if (howMany != null){
        window.history.go(eval(howMany));
    }
    else{
        window.history.go(-1);
    }
    return;
}


//------------------------------------------------------------------------
//------------------------------------------------------------------------

function ResizeDiv(divId)
{
	var obj = document.getElementById(divId);
    var objStyle = document.getElementById(divId).style;
	obj.style.height = screen.availHeight-110;
	document.recalc(false);
}

//automatically tab to the next field if maxlength reached
function autoTab(input,len, e) 
{
    var keyCode = (isNS) ? e.which : e.keyCode; 
    var filter = (isNS) ? [0,8,9] : [0,8,9,16,17,18,37,38,39,40,46];
	if(input.value.length >= len && !containsElement(filter,keyCode)) 
	{
	    input.value = input.value.slice(0, len);
	    input.form[(getIndex(input)+1) % input.form.length].focus();
	}
}

function containsElement(arr, ele) 
{
	var found = false, index = 0;
	while(!found && index < arr.length)
	if(arr[index] == ele)
	    found = true;
	else
	    index++;
	return found;
}

function getIndex(input) 
{
	var index = -1, i = 0, found = false;
	while (i < input.form.length && index == -1)
	if (input.form[i] == input)index = i;
	else i++;
	return index;

	return true;
}

function PrintThisPage() 
{ 
	var sOption="toolbar=yes,location=no,directories=yes,menubar=yes,"; 
		sOption+="scrollbars=yes,width=750,height=600,left=100,top=25"; 

		var winprint=window.open("print.htm","Print",sOption); 

	winprint.focus(); 
}



function stopSubmit(){
	if (window.event.keyCode == 13){ 
		return false; 
	}
}

function PopupCalendar(ctl)
{
	var calPopup=null;
	var x = window.event.x+8;
	var y = window.event.y+92;
	settings='width=165,height=188,left=' + x + ',top=' + y + ',location=no,directories=no,menubar=no,toolbar=no,status=no,scrollbars=no,resizable=no,dependent=no';
	calPopup=window.open('../Includes/Calendar.aspx?_destTextBoxCtl=' + ctl, 'cal_win', settings);
	calPopup.focus();
}

//build the address listbox
function AddAddressesToList(addressCtl, strDesc)
{
    var pickAddressCtl = GetElement(addressCtl.id + "__lstPickAddress");
    if (pickAddressCtl == null){
        return;
    }
    BuildAddressArray();
    if (pickAddressArray == null || pickAddressArray.length < 1){
        return;
    }
    //remove items
    for (i=1; i<pickAddressCtl.length; i++){
        pickAddressCtl.options[i] = null;
    }
	
    for (i=0; i<pickAddressArray.length; i++)
    {        
        AddItemToList(pickAddressCtl, GetDisplayAddress(pickAddressArray[i]), i);
    }
}

//set form fields after address is selected
function AddressPickerOnSelect(addressCtl, listCtl)
{
    var el = GetElement(listCtl);
    var selected = el.selectedIndex;
    var arrIdx = el.options[selected].value;
    if (arrIdx >= 0){
        var displayArray = pickAddressArray[arrIdx].split("~");			
		var resultForm = document.forms[0];
		resultForm[addressCtl + '__streetNumber'].value = displayArray[0];
		resultForm[addressCtl + '__streetName'].value = displayArray[1];
		resultForm[addressCtl + '__city'].value = displayArray[2];
		resultForm[addressCtl + '__state'].value = displayArray[3];
		resultForm[addressCtl + '__Zip'].value = displayArray[4];
		resultForm[addressCtl + '__county'].value = displayArray[5];
		resultForm[addressCtl + '__streetSuffix'].value = displayArray[6];
//Swetha Peddi
//10/20/2005 
//POSTIMP1
		resultForm[addressCtl + '__designationList'].selectedIndex = 0;
		resultForm[addressCtl + '__designation'].value = '';
 		for (var i=0; i<resultForm[addressCtl + '__designationList'].length; i++)
		{
			if (resultForm[addressCtl + '__designationList'].options[i].value == displayArray[7])
			{
				resultForm[addressCtl + '__designationList'].value = displayArray[7];
				resultForm[addressCtl + '__designation'].value = displayArray[8];
			}
		}
	//	resultForm[addressCtl + '__designationList'].value = displayArray[7];
		
		resultForm[addressCtl + '__adcMapPage'].value = displayArray[9];
		resultForm[addressCtl + '__adcMapGrid'].value = displayArray[10];
		
		//Call Validators for this address block
		EnableAddressValidators(addressCtl, true);
	}
}

//Build Address Array
function BuildAddressArray()
{
	//addressArray contains the id's of the address controls
	//Create an array of addresses to display in listbox
	if (addressArray.length > 0){
	    var idx=0;
	    //Create a unique list of addresses based on the address control names
	    var arr = new Array();
	    for (i=0; i<addressArray.length; i++){
	        strAddress = "";
	        ctl = addressArray[i];
	        strAddress = GetAddressValues(ctl);
	        if (IsValidAddress(strAddress)){//The control has a valid address
	            arr[idx] = strAddress;
	            idx++;
	        }
	    }
	    var hiddenAddresses = document.frmMain._hiddenAddresses.value;
	    //now, get the addresses from the hidden form if it's there
	    if (hiddenAddresses.length > 0){
	        var sessionAddress = hiddenAddresses.split("|");
	        //concat the two arays
	        if (sessionAddress != null){
				for (i=0; i<sessionAddress.length; i++){
					if (sessionAddress[i].length > 0){
						arr.push(sessionAddress[i]);
					}
				}
	        }
	    } 
	    pickAddressArray = CreateUniqueAddressList(arr);
	}
}


//Address Picker - display popup at the current x,y mouse position
function PickAddressFromList(requestCtl, title)
{
	InSiteTransfer=true;	
	var addressWindow=null;
	var x = xMousePos-400;
	var y = yMousePos;
	var i;
	var html = '<HTML>\n<HEAD>\n';
	html += "    <TITLE>" + title + "</TITLE>\n";
	html += "    <link rel='stylesheet' href='../styles/pictor.css'>\n";
	html += "    <SCRIPT Language=\"JavaScript\">\n";
	html += "    function AddressPickerOnSelect(ctl, streetNumber, streetName, city, state, zip, county, streetSuffix, designationList, designation, adcMapPage, adcMapGrid)\n";
	html += "    {\n";
    html += "        var resultForm = window.opener.document.forms[0];\n";
    html += "        resultForm[ctl + '__streetNumber'].value = streetNumber;\n";
    html += "        resultForm[ctl + '__streetName'].value = streetName;\n";
    html += "        resultForm[ctl + '__city'].value = city;\n";
    html += "        resultForm[ctl + '__state'].value = state;\n";
    html += "        resultForm[ctl + '__Zip'].value = zip;\n";
    html += "        resultForm[ctl + '__county'].value = county;\n";
    html += "        resultForm[ctl + '__streetSuffix'].value = streetSuffix;\n";   
 //   html += "		 ValidatorValidate(ctl + '__Zip_Valid');\n";
//Swetha Peddi
//10/20/2005 
//POSTIMP1
    html += "        resultForm[ctl + '__designationList'].selectedIndex = 0;\n";
    html += "        resultForm[ctl + '__designation'].value = '';\n";	
    html += "        for (var i=0; i<resultForm[ctl + '__designationList'].length; i++)\n";
    html += "        {\n";
   // html += "			alert(resultForm[ctl + '__designationList'].options[i].value+ ' == ' +designationList);\n";
    html += "			if (resultForm[ctl + '__designationList'].options[i].value == designationList)\n";
    html += "			 {\n";
    html += "               resultForm[ctl + '__designationList'].value = designationList;\n";	
    html += "               resultForm[ctl + '__designation'].value = designation;\n";	
    html += "			 }\n";
    html += "        }\n";
  //  html += "        alert(resultForm[ctl + '__designationList'].length);\n";
  //  html += "        resultForm[ctl + '__designationList'].value = designationList;\n";
 
    html += "        resultForm[ctl + '__adcMapPage'].value = adcMapPage;\n";
    html += "        resultForm[ctl + '__adcMapGrid'].value = adcMapGrid;\n";
    //Call Validators for this address block
    html += "        window.opener.EnableAddressValidators(ctl, true);\n";
    html += "        self.close();\n";
	html += "    }\n";
	html += "    </SCRIPT>\n";
	html += '\n</HE' + 'AD>\n<BODY>' +  '\n';
    html += "<a href='javascript:self.close()' class='PickAddressLink'>Close</a>\n";
	html += "<form name='frmAddressList' method='get' id='frmAddressList'>\n";
	html += "<div id='_divAddresses' class='addressTableContainer'\">\n";
	html += "    <table cellspacing='0' cellpadding='3' bordercolor='Black' border='1'>\n";
	
    var myForm = document.forms[0];
	var addressAddedToList = false;
	var ctl;
	var strAddress;
	var myForm = document.forms[0];
    var streetNumber;
    var streetName;
    var city;
    var state;
    var zip;
    var county;
    var streetSuffix;
    var designationList;
    var designation;
    var adcMapPage;
    var adcMapGrid;
    var disstreetSuffix;
    
	//addressArray contains the id's of the address controls
	//Create an array of addresses to display in listbox
	if (addressArray.length > 0){
	    var idx=0;
	    //Create a unique list of addresses based on the address control names
	    var arr = new Array();
	    for (i=0; i<addressArray.length; i++){
	        strAddress = "";
	        ctl = addressArray[i];
	        strAddress = GetAddressValues(ctl);
	        if (IsValidAddress(strAddress)){//The control has a valid address
	            arr[idx] = strAddress;
	            idx++;
	        }
	    }
	    var hiddenAddresses = document.frmMain._hiddenAddresses.value;
	    //var billingAddresses = document.frmMain._hiddenBillingAddresses.value;
	    //now, get the addresses from the hidden form if it's there
	   // alert("Hidden Project Addresses ->" + hiddenAddresses);
	    if (hiddenAddresses.length > 0){
	        var sessionAddress = hiddenAddresses.split("|");
	        //concat the two arays
	        if (sessionAddress != null){
				for (i=0; i<sessionAddress.length; i++){
					if (sessionAddress[i].length > 0){
						arr.push(sessionAddress[i]);
					}
				}
	        }
	    }
	    
	    var uniqueArray = CreateUniqueAddressList(arr);

	    //Save Unique Address To Hidden Field for use on other pages
	    //create header
		html += "        <TR class='PickAddressHeader'>\n";
		html += "        <TD>&nbsp;&nbsp;</TD>\n";	
		html += "        <TD nowrap>Street #</TD>\n";	  
		html += "        <TD nowrap>Street Name</TD>\n";	
		html += "        <TD nowrap>Suffix</TD>\n";	
		html += "        <TD nowrap>Designation</TD>\n";
		html += "        <TD nowrap>City</TD>\n";	
		html += "        <TD nowrap>State</TD>\n";	
		html += "        <TD nowrap>Zip</TD>\n";	
		html += "        <TD>County</TD>\n";	
		html += "        <TD nowrap>Map Page</TD>\n";	
		html += "        <TD nowrap>Map Grid</TD>\n";	      
		html += "        </TR>\n";
		for (i=0; i<uniqueArray.length; i++)
		{
			strAddress = uniqueArray[i];
			//document.frmMain._hiddenProjectAddresses.value += strAddress + "|";
			if (IsValidAddress(strAddress)){ //if valid address, show in listbox
			    var displayArray = strAddress.split("~");
			    streetNumber = displayArray[0];
				streetName = displayArray[1];
				city = displayArray[2];
				state = displayArray[3];
				zip = displayArray[4];
				county = displayArray[5];
				streetSuffix = displayArray[6];
				designationList = displayArray[7];
				designation = displayArray[8];
				adcMapPage = displayArray[9];
				adcMapGrid = displayArray[10];
				disstreetSuffix = displayArray[11];
				disdesignationList = displayArray[12];
				
				html += "        <TR class='PickAddressContent'>\n";
				html += "        <TD><input name='btnSelect'" + i + " value='Select' type='button' onClick=\"AddressPickerOnSelect('" + requestCtl.id + "','" + streetNumber + "','" + streetName + "','" + city + "','" + state + "','" + zip + "','" + county + "','" + streetSuffix + "','" + designationList + "','" + designation + "','" + adcMapPage + "','" + adcMapGrid + "');\"></TD>\n";
				html += "        <TD>" + streetNumber + "</TD>";
				html += "        <TD>" + streetName + "</TD>";
				html += "        <TD>" + disstreetSuffix + "</TD>";
				html += "        <TD>" + disdesignationList + " " + designation + "</TD>";
				html += "        <TD>" + city + "</TD>";
				html += "        <TD>" + state + "</TD>";
				html += "        <TD>" + zip + "</TD>";
				html += "        <TD>" + county + "</TD>";
				html += "        <TD>" + adcMapPage + "</TD>";
				html += "        <TD>" + adcMapGrid + "</TD>";
				html += "        </TR>\n";
				addressAddedToList = true;
			}
		}
	}
	if (!addressAddedToList)
	{
	    alert("Please enter 1-address first before using this feature.");
	    return;
	}
	html += "    </table></div>\n";
	html += "</form>\n";
	html += '\n</BODY>\n</HTML>';
	settings='width=680,height=188,left=' + x + ',top=' + y + ',location=no,directories=no,menubar=no,toolbar=no,status=no,scrollbars=auto,resizable=no,dependent=no';
	addressWindow=window.open('', 'address_picker_win', settings);
	if (addressWindow != null){
	    addressWindow.document.write(html);
	    addressWindow.document.close(); //stop writing to the document	
	    addressWindow.focus();
	}
}

function CreateUniqueAddressList(arr)
{
    var newArray = new Array();
    arr.sort(); //sort the array
    var arrLen = arr.length;
    var j=1;
    var i=0;
    var temp;
    if (arrLen <= 1){
        return arr;
    }
//window.top.debugWindow =window.open("",
                  //"Debug",
                  //"left=0,top=0,width=300,height=700,scrollbars=yes,"
                  //+"status=yes,resizable=yes");
  //window.top.debugWindow.opener = self;

    ///window.top.debugWindow.document.open();


	for(j = 0; j < arrLen; j++){
	    temp = arr[j];
	    if(temp == arr[j+1]){
	        continue;
	    }
	    newArray[i++] = temp;
	      //window.top.debugWindow.document.write(temp);
	        //window.top.debugWindow.document.write("\n");
	    
	    
	} 
	return newArray;  
}

//Is an address block valid
function IsValidAddress(strAddress){
    if (strAddress.length < 1){
        return false;
    }
    var arr = strAddress.split("~");
    if (arr == null){
        return false;
    }
    if (arr.length < 1){
        return false;
    }
    var streetNumber = arr[0];
    var streetName = arr[1];
    var city = arr[2];
    var state = arr[3];
    var zip = arr[4];    
    var designation = arr[8];
    var RE = new RegExp('^[a-zA-Z0-9, ]+$');
    
    if (!RE.test(streetName) && streetName != '')
    {
      return false;
    }
    
    if (!RE.test(designation) && designation!='')
    {
		return false;
    }
    /*if (!RE.test(streetName) || !RE.test(designation)) 
	{
	  if ((streetName != '') && (designation !=''))
			return false;
	}*/
    if (streetName.length > 0 && city.length > 0 && state.length > 0 && zip.length > 0){
        return true;
    }
    return false;
}

/*function HasSpecialChars(strValue)
{
	var LowerChars = "abcdefghijklmnopqrstuvwxyz";
    var UpperChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    var Numbers = "0123456789";
    var Space = " ";    
    var ok = false;
    var temp;
	for (var i=0;i < strValue.length; i++)
	{
	   temp = "" + strValue.substring(i, i+1);
       if ((LowerChars.indexOf(temp) == "-1") && (UpperChars.indexOf(temp) == "-1") && (Numbers.indexOf(temp) == "-1") && (Space.indexOf(temp) == "-1"))
        {
            ok = true;
        }
        i++;	  
	} 	   
	return ok;	
}*/

//Is an address block valid
function GetAddressValues(ctl)
{
    var el = GetElement(ctl + "__streetNumber");
    if (el){
		var myForm = document.forms[0];
		var streetNumber = myForm[ctl + "_" + "_streetNumber"].value;
		var streetName = myForm[ctl + "_" + "_streetName"].value;
		var city = myForm[ctl + "_" + "_city"].value;
		var state = myForm[ctl + "_" + "_state"].value;
		var zip = myForm[ctl + "_" + "_Zip"].value;
		var county = myForm[ctl + "_" + "_county"].value;
		var streetSuffix = myForm[ctl + "_" + "_streetSuffix"].value;
		
		var disstreetSuffix=document.all[ctl + "_" + "_streetSuffix"].options[document.all[ctl + "_" + "_streetSuffix"].options.selectedIndex].text;
		var disdesignationList=document.all[ctl + "_" + "_designationList"].options[document.all[ctl + "_" + "_designationList"].options.selectedIndex].text;
		
		var designationList = myForm[ctl + "_" + "_designationList"].value;
		var designation = myForm[ctl + "_" + "_designation"].value;
		var adcMapPage = myForm[ctl + "_" + "_adcMapPage"].value;
		var adcMapGrid = myForm[ctl + "_" + "_adcMapGrid"].value;
		return streetNumber + '~' + streetName + '~' + city + '~' + state + '~' + zip + '~' + county + '~' + streetSuffix + '~' + designationList + '~' + designation + '~' + adcMapPage + '~' + adcMapGrid + '~' + disstreetSuffix + '~' + disdesignationList  ;
	}
	else{
	    return "";
	}
}

//Format the address for display purposes
function GetDisplayAddress(strAddress)
{
    var displayAddress = "";
    var displayArray = strAddress.split("~");
    if (displayArray.length > 0)
    {
		streetNumber = displayArray[0];
		streetName = displayArray[1];
		city = displayArray[2];
		state = displayArray[3];
		zip = displayArray[4];
		county = displayArray[5];
		streetSuffix = displayArray[6];
		designationList = displayArray[7];
		designation = displayArray[8];
		adcMapPage = displayArray[9];
		adcMapGrid = displayArray[10];
		disstreetSuffix = displayArray[11];
		disdesignationList =displayArray[12]
		displayAddress += streetNumber;
		displayAddress += streetName.length>0 ? " " + streetName : "";
		displayAddress += streetSuffix.length>0 ? " " + disstreetSuffix : "";
		displayAddress += designationList.length>0 ? " " + disdesignationList : "";
		displayAddress += designation.length>0 ? " " + designation : "";
		displayAddress += city.length>0 ? " " + city : "";
		displayAddress += state.length>0 ? ", " + state : "";
		displayAddress += zip.length>0 ? " " + zip : "";
		displayAddress += county.length>0 ? " " + county : "";
		displayAddress += adcMapPage.length>0 ? " " + adcMapPage : "";
		displayAddress += adcMapGrid.length>0 ? " " + adcMapGrid : "";
	}
	return displayAddress;
}


//Save the scroll coordinates
function saveCoordinates()
{
    var myPageX=0;
    var myPageY=0;
    if (document.all){
        myPageX = document.body.scrollLeft;
        myPageY = document.body.scrollTop;
    }
    else{
        myPageX = window.pageXOffset;
        myPageY = window.pageYOffset;
    }
    document.frmMain.PageX.value = myPageX;
    document.frmMain.PageY.value = myPageY;
}
  
//Scroll to last saved position
function ScrollTo()
{
    //alert(document.frmMain.PageX.value + "-" + document.frmMain.PageY.value);
    window.scrollTo(document.frmMain.PageX.value, document.frmMain.PageY.value);
}

//Scroll to a specific x,y coordinate
function ScrollToLocation(x, y)
{
    window.scrollTo(x, y);
}

   
//Client-side handling of checkbox list items
/*function HandleRdListElectricHeat(radiobuttonListId, count, ValidatorID)
{
   if (IsListItemSelected(checkBoxListId, count, "Yes"))
   {
     document.getElementById(ValidatorID).enabled = true;
   }
   else
   {
     document.getElementById(ValidatorID).enabled = false;
   }
           
}*/
function HandleCheckBoxListClick(checkBoxListId, count, Section)
{  
   InSiteTransfer=true;
   switch(Section)
   {
   
       case "TypeOfConstruction":
           EnableMeterLocValidators(false);
           if (IsListItemSelected(checkBoxListId, count, "Townhouse"))
           {
               ToggleDiv("_divMeterLocReqTownHouses", 1);
           }
           else
           {
               ToggleDiv("_divMeterLocReqTownHouses", 0);
           }   
           break;
       case "Electric Heat":

           if (IsListItemSelected(checkBoxListId, count, "Yes"))
           {
               ToggleDiv("_divNoElectricHeat", 0);
               ToggleDiv("_divTypeOfElectricHeating", 1);
           }
           if (IsListItemSelected(checkBoxListId, count, "No"))
           {
               ToggleDiv("_divNoElectricHeat", 1);
               ToggleDiv("_divTypeOfElectricHeating", 0);
           }   
           break;
       case "Central AC":
           if (IsListItemSelected(checkBoxListId, count, "No"))
           {
               ToggleDiv("_divNumACUnits", 0);
               ToggleDiv("_divACUnits", 0);
           }
           
           if (IsListItemSelected(checkBoxListId, count, "Yes"))
           {
               ToggleDiv("_divNumACUnits", 1);
               ToggleDiv("_divACUnits", 1);
           }   
           break;     
           
       case "Gas Heat":
           if (IsListItemSelected(checkBoxListId, count, "No"))
           {
               ToggleDiv("_divNumGasUnits", 0);
               ToggleDiv("_divGasUnits", 0);
           }
           
           if (IsListItemSelected(checkBoxListId, count, "Yes"))
           {
               ToggleDiv("_divNumGasUnits", 1);
               ToggleDiv("_divGasUnits", 1);
           }   
           break;  
           
       case "Attachments":
		   EnableRefNumberValidator(false);
		   EnableAttachmentValidators(false);
		   var objItem;
		   var FilesArrayCount;
		   FilesArrayCount = FilesAttachedCount.length;
		   if (IsListItemSelected(checkBoxListId, count, "Submit attachment(s) electronically"))
           {
               ToggleDiv("_fileAttachmentDiv", 1);
               AttachmentReqArray[0].innerText = "*";  
               if (FilesArrayCount >= 2)
				{   
				    if (FilesAttachedCount[FilesArrayCount - 1] >= 1)
				    { 
				      AttachmentReqArray[0].innerText = " ";  
				    }				  
				}  
           }
           else
           {   	 	  
				AttachmentReqArray[0].innerText = "  ";  	
				ToggleDiv("_fileAttachmentDiv", 0);			
           }
 
           if (IsListItemSelected(checkBoxListId, count, "Townhouse Only - Site plan previously submitted."))
           {
               ToggleDiv("_divAttachmentReferenceNumber", 1);
           }
           else{
                ToggleDiv("_divAttachmentReferenceNumber", 0);
           }         
           break;   
                                        

	//For the flicker control
       case "TimesPer":
           if (IsListItemSelected(checkBoxListId, count, "Yes"))
           {
               EnableTimesPer(true);
           }
           else
           {
               EnableTimesPer(false);
           }
           break;
	//For the Generate control for load addresses
       case "MoreThanOne":
           if (IsListItemSelected(checkBoxListId, count, "Yes"))
           {
               EnableMoreThanOne(true);
           }
           else
           {
               EnableMoreThanOne(false);
           }
 
           break;          
       default:
           break;
 
    }
    InSiteTransfer=false;
}

//Handles Enabling and disabling of textboxes associated with checkboxes in RS, RD Gas and Electric load pages.
function HandleCheckBoxClick(chkBoxId, txtBoxId, txtBox2Id, valID, valID2)
{
    InSiteTransfer=true;
   	var TextBoxId;
	var CheckBoxId;
	var TextBoxId2;
	var ValCheckBox;
	var ValCheckBox2;
   
    CheckBoxId = document.getElementById(chkBoxId);
	TextBoxId = document.getElementById(txtBoxId);
	TextBoxId2 = document.getElementById(txtBox2Id);
	ValCheckBox = document.getElementById(valID);
	ValCheckBox2 = document.getElementById(valID2);
	
	if (CheckBoxId == null){
	    return;
	}
	    
    if (CheckBoxId.checked)
	 {
		TextBoxId.disabled = false; 
		if (ValCheckBox != null)
			ValCheckBox.enabled = true;					
		if (TextBoxId2 != null)
		{
		  TextBoxId2.disabled = false;
		}
		if (ValCheckBox2 != null)
		{
			ValCheckBox2.enabled = true;		
		}
     }
	else
	 {
		TextBoxId.disabled = true; 
		if (ValCheckBox != null)
			ValCheckBox.enabled = false;		
		if (TextBoxId2 != null)
		{
		  TextBoxId2.disabled = true;
		}	
		if (ValCheckBox2 != null)
		{
			ValCheckBox2.enabled = false;		
		}
	 }
	
	InSiteTransfer=false;
}



//promts user with the text sent. returns true if yes, false if no
function PromptYesNo(theText)
{
 return confirm(theText);

}

function PopUpIfPrevButtonClicked()
{
  var HiddenValue;
  HiddenValue = document.frmMain._IfPrevButtonClickedOnce.value;
  if (HiddenValue == 'false')
  {
    document.frmMain._IfPrevButtonClickedOnce.value = 'true';
    if(!PromptYesNo('You may lose any unsaved data in this page. If you still want to continue click OK'))
    { 
      return false;
    }
    else
      return true;
  }
  else
     return true;  
}

function HandleSGEnabledCheckBoxListClick(SitePlancheckBoxListId,SwitchGearcheckBoxListId, SitePlancount, Section)
{  
   var FilesArrayCount;
   FilesArrayCount = FilesAttachedCount.length;
   switch(Section)
   {
       case "Attachments":
		   EnableRefNumberValidator(false);
		   EnableAttachmentValidators(false);
		   var objItem;		 
		   if (IsListItemSelected(SitePlancheckBoxListId, SitePlancount, "Submit attachment(s) electronically"))
           {   
               ToggleDiv("_fileAttachmentDiv", 1);
               AttachmentReqArray[0].innerText = "*"; 
            //   alert('Entered Attachments main IF');
            //   alert(FilesArrayCount);
               if (FilesArrayCount >= 2)
                {
             //               alert('Entered Attachments 2nd  IF');
			//	    alert(FilesAttachedCount[FilesArrayCount - 1]);
				    if (FilesAttachedCount[FilesArrayCount - 1] >= 1)
				    { 
				       AttachmentReqArray[0].innerText = " ";  
				    }				  
				}  
               if (IsListItemSelected(SwitchGearcheckBoxListId, 2, "Submit drawings electronically."))
               {
        //           alert('SwitchGearcheckBoxListId, 2, Submit drawings electronically.');
                    AttachmentReqArray[1].innerText = "*";
        //             alert(FilesArrayCount);  
                    if (FilesArrayCount >= 2)
					{
		//			alert(FilesAttachedCount[FilesArrayCount - 1]);
					   if (FilesAttachedCount[FilesArrayCount - 1] == 1)
					    {
					      AttachmentReqArray[0].innerText = "*";  
					      AttachmentReqArray[1].innerText = " ";  
					    }
		//			     alert(FilesArrayCount);
		//			    alert(FilesAttachedCount[1]);
					   if (FilesAttachedCount[FilesArrayCount - 1] >= 2)
					    { 
					      AttachmentReqArray[1].innerText = " ";  
					    }				  
					} 
               }
               else
               {
        //            alert(' Entered else for SwitchGearcheckBoxListId, 2, Submit drawings electronically.');
					AttachmentReqArray[1].innerText = "  ";                                 	
			   }
				
           }
           else
           {   	 	  
                if (IsListItemSelected(SwitchGearcheckBoxListId, 2, "Submit drawings electronically."))
                {
       //            alert('Attachments Entered Main else.');
					ToggleDiv("_fileAttachmentDiv", 1);	
					AttachmentReqArray[0].innerText = "*"; 	
					AttachmentReqArray[1].innerText = "  "; 	
	//				 alert(FilesArrayCount);
					if (FilesArrayCount >= 2)
					{
		//			alert(FilesAttachedCount[FilesArrayCount - 1]);
					   if (FilesAttachedCount[FilesArrayCount - 1] >= 1)
					    {
					       AttachmentReqArray[0].innerText = " ";  
					    }				  
					} 
						
				}
				else
				{
	//			    alert('Attachments Entered else in Main Else.');
					AttachmentReqArray[0].innerText = "  "; 	
					AttachmentReqArray[1].innerText = "  "; 	
				    ToggleDiv("_fileAttachmentDiv", 0);	
				}
           }
 
           if (IsListItemSelected(SitePlancheckBoxListId, SitePlancount, "Townhouse Only - Site plan previously submitted."))
           {
               ToggleDiv("_divAttachmentReferenceNumber", 1);
           }
           else{
                ToggleDiv("_divAttachmentReferenceNumber", 0);
           }         
           break;   
           
           
        case "SwitchGear":
		   EnableRefNumberValidator(false);
		   EnableSwitchGearValidators(false);
		  
           if (IsListItemSelected(SwitchGearcheckBoxListId, 2, "Submit drawings electronically."))
           {   
               ToggleDiv("_fileAttachmentDiv", 1);
               AttachmentReqArray[0].innerText = "*";
    //           alert('Entered Swithcgear.');
    //           alert(FilesArrayCount);
                if (FilesArrayCount >= 2)
				{
	///			alert(FilesAttachedCount[FilesArrayCount - 1]);
					   if (FilesAttachedCount[FilesArrayCount - 1] >= 1)
					    { 
					       AttachmentReqArray[0].innerText = " ";  
					    }				  
				}
               if (IsListItemSelected(SitePlancheckBoxListId, SitePlancount, "Submit attachment(s) electronically"))
               {
				 AttachmentReqArray[1].innerText = "*";
	//			  alert(FilesArrayCount);
				 if (FilesArrayCount >= 2)
					{
	//				alert(FilesAttachedCount[FilesArrayCount - 1]);
					   if (FilesAttachedCount[FilesArrayCount - 1] == 1)
					    {
					       AttachmentReqArray[0].innerText = "*";  
					       AttachmentReqArray[1].innerText = " ";  
					       
					    }		
	//				    alert(FilesAttachedCount[FilesArrayCount - 1]);
					   if (FilesAttachedCount[FilesArrayCount - 1] >= 2)
					    {
					      AttachmentReqArray[0].innerText = " ";  
					      AttachmentReqArray[1].innerText = " ";  
					    }				  
					}
			   }
			   else
				 AttachmentReqArray[1].innerText = "  ";	
			   	 
           }
           else
           {    
	//			 alert('Entered main Else in SG');
                 if (IsListItemSelected(SitePlancheckBoxListId, SitePlancount, "Submit attachment(s) electronically"))
				 {
                      ToggleDiv("_fileAttachmentDiv", 1);
                      AttachmentReqArray[0].innerText = "*"; 	
					  AttachmentReqArray[1].innerText = "  "; 	
					  if (FilesArrayCount >= 2)
					{
	//				  alert(FilesAttachedCount[FilesArrayCount - 1]);
					   if (FilesAttachedCount[FilesArrayCount - 1] >= 1)
					    {
					      AttachmentReqArray[0].innerText = " ";  
					    }				  
					}
                 }
                 else
                 {
					  AttachmentReqArray[0].innerText = "  "; 	
					  AttachmentReqArray[1].innerText = "  "; 	
					  ToggleDiv("_fileAttachmentDiv", 0);
				 }
           }
           break;
   }
}      
        
// checkboxlistID = id of the checkboxlist
function IsListItemSelected(checkBoxListId, count, itemValue)
{
	var i = 0;
	var objItem;
	// iterate through listitems that need to be enabled or disabled
	for(i = 0; i<count; i++)
	{
		objItem = document.getElementById(checkBoxListId + '_' + i);
		if(objItem == null)
		{   
		  	continue;
		}
		if (objItem.checked)
		{
		   	//Get the label of checked item
			if (GetCheckBoxItemLabel(checkBoxListId, i) == itemValue){
			    return true;
			}
		}
	}
	return false;
}

//Get the label of the given checkbox item
function GetCheckBoxItemLabel(parent, index)
{
	var parentObj = document.getElementById(parent);
	if (parentObj == null)
	    return "";
	//get all the labels within the parent 
	var labels = parentObj.getElementsByTagName("label");
	if (labels.length >= 0)
	{
	   return labels[index].innerText;
	}
	return "";
}

// Handle ListBox selection 
function HandleListSelection(listControl, valueToCheck, divCtrl)
{
	var ctl = document.getElementById(listControl);
	if (ctl == null){
	    return;
	}
	var selectedText = ctl.options[ctl.selectedIndex].text;
	if (valueToCheck == selectedText){
        ToggleDiv(divCtrl, 1);
    }
    else{
        ToggleDiv(divCtrl, 0);
    } 
}

//C&I Type of Service selection.
function HandleListSelectionCI(listControl, valueToCheck, CheckBoxId, TxtDateID, ValPwrFact, ValStrtLights, ValOwnSwtchGr)
{
  var ctl = document.getElementById(listControl);
  var ctlValPwrFact = document.getElementById(ValPwrFact);
  var ctlValStrtLights = document.getElementById(ValStrtLights);
  var ctlValOwnSwtchGr = document.getElementById(ValOwnSwtchGr);
	if (ctl == null){
	    return;
	}
	var selectedText = ctl.options[ctl.selectedIndex].text;
	if (valueToCheck == selectedText)
	{ 
	   ToggleDiv("_divOtherConsiderations", 0);	
	   var chkBoxctl = document.getElementById(CheckBoxId);
	   var txtDatectl = document.getElementById(TxtDateID);
	   chkBoxctl.checked = false;	  
	   chkBoxctl.disabled = true;
	   txtDatectl.disabled = true;
	   if (ctlValPwrFact != null)
	      ctlValPwrFact.disabled = true;
	   if (ctlValStrtLights != null)
	      ctlValStrtLights.disabled = true;
	   if (ctlValOwnSwtchGr != null)
	      ctlValOwnSwtchGr.disabled = true;
	   return true;	   
    }
    else
    {
       ToggleDiv("_divOtherConsiderations", 1);
	   var chkBoxctl = document.getElementById(CheckBoxId);
	   var txtDatectl = document.getElementById(TxtDateID);
	   chkBoxctl.disabled = false;
	   txtDatectl.disabled = false;  
	   if (ctlValPwrFact != null)
	      ctlValPwrFact.enabled = true;
	   if (ctlValStrtLights != null)
	      ctlValStrtLights.enabled = true;
	   if (ctlValOwnSwtchGr != null)
	      ctlValOwnSwtchGr.enabled = true;
	   return false;    
    } 
}

function Func(listControl, checkBoxctl)
{
 var ctl = document.getElementById(listControl);
 var checkBxctl = document.getElementById(checkBoxctl);
 if (checkBxctl.checked)
 {
  ctl.options[3] = null;
 }
 else
 {
   var optionObject = new Option('Gas','3');
   ctl.options[3] = optionObject;
 } 
}


function HandleStartStopListSelection(listControl, NameOfList)
{
  var ctl = document.getElementById(listControl);  
  var e1;
  var e2;
	if (ctl == null){
	    return;
	}
	var selectedText = ctl.options[ctl.selectedIndex].text;
	if (selectedText == '24x7')
	{
	  for (var i=0; i<StartStopTimeDdlArray.length; i++)
	  {
	    e1 = StartStopTimeDdlArray[i];
	    e1.selectedIndex = 1;	    	   	 
	  }	
	  for (var i=0; i<StartStopTimeVldtrsArray.length; i++)
	  {
		e2 = StartStopTimeVldtrsArray[i];
		ValidatorValidate(e2);
	  }
	}
	else if(selectedText == '24-Hours') 
	{
	 for (var i=0; i<StartStopTimeDdlArray.length; i++)
	  {
	    e1 = StartStopTimeDdlArray[i];	    
	    if (e1.selectedIndex == 1)
	    {
	      e1.selectedIndex = 0;	     
	    }	 
	  }	
	 var ctlToChange = document.getElementById(NameOfList);	
	 ctlToChange.selectedIndex = 2;		
	}	
	else if(selectedText == 'Not Operating') 
	{
	 for (var i=0; i<StartStopTimeDdlArray.length; i++)
	  {
	    e1 = StartStopTimeDdlArray[i];
	    if (e1.selectedIndex == 1)
	    {
	      e1.selectedIndex = 0;
	    }	 
	  }	
	 var ctlToChange = document.getElementById(NameOfList);
	 ctlToChange.selectedIndex = 3;		
	}
	else if (ctl.selectedIndex > 3)
	{
	  for (var i=0; i<StartStopTimeDdlArray.length; i++)
	  {
	    e1 = StartStopTimeDdlArray[i];
	    if (e1.selectedIndex == 1)
	    {
	      e1.selectedIndex = 0;
	    }	 
	  }	
	  var ctlToChange = document.getElementById(NameOfList);
	  if ((ctlToChange.selectedIndex == 2) || (ctlToChange.selectedIndex == 3))	
	  {
	     ctlToChange.selectedIndex = 0;
	  }	  
	}	
}

//dynamically add an item to a listbox
function AddItemToList(listCtl, newText, newValue)
{
    if (listCtl == null){
        return;   
    }
    var len = listCtl.length ++;
    listCtl.options[len].value = newValue;
    listCtl.options[len].text = newText;
}

//Set the input focus to the given control
function SetFocus(ctl)
{
    var el = GetElement(ctl);
    if (el)
    {
        el.focus();
    }
}

//onSubmit function executed
function NewValidatorOnSubmit()
{
    if (typeof(Page_ValidationActive) == "undefined") //perform this check for pages that do not have validations
    {	
		ChangeToWaitCursor();
        return true;    
    }
    //stop submit from running and validation,if they hit the enter key and
    //they are not on a button
    if (!gAllowSubmit)
    {
      //restore focus..or some reason it goes away
      if (lastFocus != null)
          lastFocus.focus();
 	  return false;
	 }

    if (Page_ValidationActive) {
        ValidatorCommonOnSubmit();
    }
    if (!Page_IsValid) //show message at top of page if error
    {
        ValidatorBackColor();//Set Background Color
        ToggleDiv('_divValidatorErrors', 1);
        //goto the top of page
        window.scrollTo(0, 0);
        //need to return true here so that when Previous clicked and errors exist on the screen, can still
        //execute that submit
 //       return false;
			return true; 
    }
    else
    {
		ToggleDiv('_divValidatorErrors', 0);
		ChangeToWaitCursor();
		return true;
    }
}

function ChangeToWaitCursor()
{
   for (var i = 0; i < document.all.length; i++)
   {
     if (document.all[i].style != "undefined")
		document.all[i].style.cursor = "wait";
   }
}




//Set the background of failed controls to yellowish
function ValidatorBackColor(){
    
    var i;
    var el;
    var prevInvalidEl;
    for (i = 0; i < Page_Validators.length; i++){
        if (Page_Validators[i].controltovalidate != null && Page_Validators[i].controltovalidate.length > 0){
            el = document.all[Page_Validators[i].controltovalidate]; //Get the control being validated
            if (el){
                if (Page_Validators[i].isvalid){ //if control is valid, check the previous invalid element
                    el.className = "DataEntryField";
                    if (prevInvalidEl != null){
                        if (prevInvalidEl.id == el.id){ //the previous validator for the same element failed, keep failed
                            el.className = "DataEntryErrorField"; //mark as invalid
                        }
                    }
                }
                else{
                    el.className = "DataEntryErrorField"; //mark as invalid
                    prevInvalidEl = el; //Save the last invalid element
                }
            }
        }
    }
}


//Set Input focus to first invalid field
function ValidatorFocus()
{
    var i;
    for (i = 0; i < Page_Validators.length; i++){
        if (!Page_Validators[i].isvalid){
            document.getElementById(Page_Validators[i].controltovalidate).focus();
            break;
        }
    }
}
//Get a validator from the array by ID
function GetValidatorFromArray(valID)
{
   for (i=0; i < Page_Validators.length; i++)
   {
     if (Page_Validators[i].id == valID)
     {
         return Page_Validators[i];
     }
   }

  
}
function LimitTextOld(fieldObj,maxChars)
{
  var result = true;
  if (fieldObj.value.length >= maxChars)
    result = false;
  
  if (window.event)
    window.event.returnValue = result;
  return result;
}

function LimitText(limitField, limitNum) {
	if (limitField.value.length > limitNum) {
		limitField.value = limitField.value.substring(0, limitNum);
	} 
}

//Makes a control have the required asterisk in front of it,
//or removes the asterisk..depending on flag
function AddDelRequiredAsterisk(controlID, flag)
{
	var ctl = document.getElementById(controlID);
	var reqdString = "<span class=RequiredField id=" + controlID + "_ast>*</span>"; 
	var flTextIsThere = false;
	//does it currently have the asterisk?
	if (ctl.innerText.substr(0, 1) == "*")
		flTextIsThere = true;	
    //turn on or off
    if ((flag == true) && (!flTextIsThere))
       ctl.insertAdjacentHTML("afterBegin", reqdString);
    if ((flag == false) && (flTextIsThere))
		{
		var removeCtl = document.getElementById(controlID + "_ast");
        removeCtl.removeNode(true);
        }
      
}
/*
this will fire on Checking the appliances check box. If allgas checkbox is checked then make rest of appliances
disabled. If atleast one of the other appliances is checked then make tha allgas disabled.
If none if checkboxes are disabled then make all appliances enabled.
*/
function AllGasAppliancesCheck(controlID,control)
{
	if (control == "AllGas") {
		var allgaschkbox = GetElement(controlID.id); 
		if (allgaschkbox.checked){
			ApplianceCheckBoxArrayElectricLoad[0].disabled=true;//stdresload
			ApplianceCheckBoxArrayElectricLoad[1].disabled=true;//range
			ApplianceCheckBoxArrayElectricLoad[2].disabled=true;//clothesdryer
			ApplianceCheckBoxArrayElectricLoad[3].disabled=true;//waterheater
			ApplianceCheckBoxArrayElectricLoad[4].disabled=true;//poolheater
			ApplianceCheckBoxArrayElectricLoad[5].disabled=true;//other
		}else{
			ApplianceCheckBoxArrayElectricLoad[0].disabled=false;
			ApplianceCheckBoxArrayElectricLoad[1].disabled=false;
			ApplianceCheckBoxArrayElectricLoad[2].disabled=false;
			ApplianceCheckBoxArrayElectricLoad[3].disabled=false;
			ApplianceCheckBoxArrayElectricLoad[4].disabled=false;
			ApplianceCheckBoxArrayElectricLoad[5].disabled=false;
		}
	}else{
		if (ApplianceCheckBoxArrayElectricLoad[0].checked || ApplianceCheckBoxArrayElectricLoad[1].checked || ApplianceCheckBoxArrayElectricLoad[2].checked || ApplianceCheckBoxArrayElectricLoad[3].checked || ApplianceCheckBoxArrayElectricLoad[4].checked || ApplianceCheckBoxArrayElectricLoad[5].checked) {
			ApplianceCheckBoxArrayElectricLoad[6].disabled=true;//allgas
		}else{
			ApplianceCheckBoxArrayElectricLoad[6].disabled=false;//allgas
		}
	}
}
/*
this will fire on loading of page. If allgas checkbox is checked then make rest of appliances
disabled. If atleast one of the other appliances is checked then make tha allgas disabled.
If none if checkboxes are disabled then make all appliances enabled.
*/
function AllGasAppliancesCheckOnLoad()
{
	if (ApplianceCheckBoxArrayElectricLoad[6].checked) {
		ApplianceCheckBoxArrayElectricLoad[0].disabled=true;//stdresload
		ApplianceCheckBoxArrayElectricLoad[1].disabled=true;//range
		ApplianceCheckBoxArrayElectricLoad[2].disabled=true;//clothesdryer
		ApplianceCheckBoxArrayElectricLoad[3].disabled=true;//waterheater
		ApplianceCheckBoxArrayElectricLoad[4].disabled=true;//poolheater
		ApplianceCheckBoxArrayElectricLoad[5].disabled=true;//other
	}else{
		if (ApplianceCheckBoxArrayElectricLoad[0].checked || ApplianceCheckBoxArrayElectricLoad[1].checked || ApplianceCheckBoxArrayElectricLoad[2].checked || ApplianceCheckBoxArrayElectricLoad[3].checked || ApplianceCheckBoxArrayElectricLoad[4].checked || ApplianceCheckBoxArrayElectricLoad[5].checked) {
			ApplianceCheckBoxArrayElectricLoad[6].disabled=true;//allgas
		}else{
			ApplianceCheckBoxArrayElectricLoad[6].disabled=false;//allgas
		}	
	}
}
function AllElectricAppliancesCheckOnLoad()
{
	if (ApplianceCheckBoxArray[6].checked) {
		ApplianceCheckBoxArray[0].disabled=true;//range
		ApplianceCheckBoxArray[1].disabled=true;//fireplace
		ApplianceCheckBoxArray[2].disabled=true;//poolheater
		ApplianceCheckBoxArray[3].disabled=true;//other
		ApplianceCheckBoxArray[4].disabled=true;//clothesdryer
		ApplianceCheckBoxArray[5].disabled=true;//waterheater
	}else{
		if (ApplianceCheckBoxArray[0].checked || ApplianceCheckBoxArray[1].checked || ApplianceCheckBoxArray[2].checked || ApplianceCheckBoxArray[3].checked || ApplianceCheckBoxArray[4].checked || ApplianceCheckBoxArray[5].checked) {
			ApplianceCheckBoxArray[6].disabled=true;//allelectric
		}else{
			ApplianceCheckBoxArray[6].disabled=false;//allelectric
		}	
	}
}
function AllElectricAppliancesCheck(controlID,control)
{
	if (control == "AllElectric") {
		var allelecchkbox = GetElement(controlID.id); 
		if (allelecchkbox.checked){
			ApplianceCheckBoxArray[0].disabled=true;//range
			ApplianceCheckBoxArray[1].disabled=true;//fireplace
			ApplianceCheckBoxArray[2].disabled=true;//poolheater
			ApplianceCheckBoxArray[3].disabled=true;//other
			ApplianceCheckBoxArray[4].disabled=true;//clothesdryer
			ApplianceCheckBoxArray[5].disabled=true;//waterheater
		}else{
			ApplianceCheckBoxArray[0].disabled=false;
			ApplianceCheckBoxArray[1].disabled=false;
			ApplianceCheckBoxArray[2].disabled=false;
			ApplianceCheckBoxArray[3].disabled=false;
			ApplianceCheckBoxArray[4].disabled=false;
			ApplianceCheckBoxArray[5].disabled=false;
		}
	}else{
		if (ApplianceCheckBoxArray[0].checked || ApplianceCheckBoxArray[1].checked || ApplianceCheckBoxArray[2].checked || ApplianceCheckBoxArray[3].checked || ApplianceCheckBoxArray[4].checked || ApplianceCheckBoxArray[5].checked) {
			ApplianceCheckBoxArray[6].disabled=true;//allelectric
		}else{
			ApplianceCheckBoxArray[6].disabled=false;//allelectric
		}
	}
}
var __oldDoPostBack
if (typeof(__doPostBack) != "undefined")
{
		 __oldDoPostBack= __doPostBack;
		// replace __doPostBack with another function
		__doPostBack = AlwaysFireBeforeFormSubmit; 
}
//}
		

function AlwaysFireBeforeFormSubmit (eventTarget, eventArgument) 
{
	// do whatever pre-form submission
	InSiteTransfer=true;
	
	
	if (window.location.href.indexOf("Main.aspx")<1)
	{
		// finally, let the original __doPostBack do its work
		if (typeof(__doPostBack) != "undefined")
		{
			//Check if the PostBack was there when we loaded
			if (typeof(__oldDoPostBack) == "undefined")
			{
				__oldDoPostBack= __doPostBack;
			}
			//Make sure we have a Target
			if (typeof(eventTarget)!= "undefined")
			{
				return __oldDoPostBack (eventTarget, eventArgument);
			}
		}
	}
}

//NOTES: Onload fires everytime the Header is written
//So set an Unload flag to false
//If we go through an unload set the Unload flag to true
//On a redirect the header is not sent back down so the
//flag will remain true
//Only flaw to this tactic is if we intentially Response.Redirect
//someone off the site they will not get a warning.

var WeUnloaded=false;

function window.onload()
{
	WeUnloaded=false;
}

//NOTE: This code reloads with every post
//so the clock is reset with every post
//this means that the client and the
//server could be out of sync by the
//length of an HTTP reply, if memory
//servies me correct this cannot
//be more than 60 seconds.
// The math is 1000 = 1 second
// so 1000 * 60 * 90 = 90 minutes

window.setTimeout("InSiteTransfer=true;window.location.href='../idle.htm'",5400000)

function stopSubmit(){
	if (window.event.keyCode == 8)
	{ 
		window.event.cancelBubble = true;
		window.event.returnValue = false; 
	}
}

//Commented by swetha and moved this function to ServiceApp.js
//function window.onbeforeunload()
//{
//		if(InSiteTransfer==false && WeUnloaded!=true)
//		{
			//alert('Unload ' + InSiteTransfer + ' ' + WeUnloaded);
//			if (window.location.href.indexOf("Main.aspx")<1 && window.location.href.indexOf("Confirmation.aspx")<1
//				&& window.location.href.indexOf("InfoCheckList")<1)
//			{
//				if (InSiteTransfer==false )
//				{
//					try
//					{
//					event.returnValue = "Your actions indicate you want to exit the Service Application. All the data you have entered will be lost if you exit. If you wish to exit, please click <OK>. If you would like to continue with your application, click <Cancel>";
					//"Are you sure you want to exit? Press OK to continue, or Cancel to stay on the current page.";
//					}
//					catch(e)
//					{}
//				}
//			}
//		}
//	WeUnloaded=true;
//	InSiteTransfer=false;
//}

