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_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_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];}
}

function MM_showHideLayers() { //v6.0
  var i,p,v,obj,args=MM_showHideLayers.arguments;
  for (i=0; i<(args.length-2); i+=3) if ((obj=MM_findObj(args[i]))!=null) { v=args[i+2];
  if (obj.style) { obj=obj.style; v=(v=='show')?'visible':(v=='hide')?'hidden':v; }
  obj.visibility=v; }
  }

function MM_nbGroup(event, grpName) { //v3.0
  var i,img,nbArr,args=MM_nbGroup.arguments;
  if (event == "init" && args.length > 2) {
    if ((img = MM_findObj(args[2])) != null && !img.MM_init) {
      img.MM_init = true; img.MM_up = args[3]; img.MM_dn = img.src;
      if ((nbArr = document[grpName]) == null) nbArr = document[grpName] = new Array();
      nbArr[nbArr.length] = img;
      for (i=4; i < args.length-1; i+=2) if ((img = MM_findObj(args[i])) != null) {
        if (!img.MM_up) img.MM_up = img.src;
        img.src = img.MM_dn = args[i+1];
        nbArr[nbArr.length] = img;
    } }
  } else if (event == "over") {
    document.MM_nbOver = nbArr = new Array();
    for (i=1; i < args.length-1; i+=3) if ((img = MM_findObj(args[i])) != null) {
      if (!img.MM_up) img.MM_up = img.src;
      img.src = (img.MM_dn && args[i+2]) ? args[i+2] : args[i+1];
      nbArr[nbArr.length] = img;
    }
  } else if (event == "out" ) {
    for (i=0; i < document.MM_nbOver.length; i++) {
      img = document.MM_nbOver[i]; img.src = (img.MM_dn) ? img.MM_dn : img.MM_up; }
  } else if (event == "down") {
    if ((nbArr = document[grpName]) != null)
      for (i=0; i < nbArr.length; i++) { img=nbArr[i]; img.src = img.MM_up; img.MM_dn = 0; }
    document[grpName] = nbArr = new Array();
    for (i=2; i < args.length-1; i+=2) if ((img = MM_findObj(args[i])) != null) {
      if (!img.MM_up) img.MM_up = img.src;
      img.src = img.MM_dn = args[i+1];
      nbArr[nbArr.length] = img;
  } }
}

// Hide the status message
//Visit JavaScript Kit (http://javascriptkit.com) for script
function hidestatus(){
    window.status=""
    return true
}


function OpenNewWindow(WindowLink)
{
window.open(WindowLink,'winc', 'height=504,width=590,toolbar=no,location=no,directories=no, status=no,menubar=no,scrollbars=yes,resizable=yes, copyhistory=no,width=590,height=504') 
}


function PopNewWindow(WindowLink)
{
window.open(WindowLink,'wind', 'height=430,width=840,toolbar=no,location=no,directories=no, status=no,menubar=no,scrollbars=yes,resizable=yes, copyhistory=no,width=840,height=430') 
}

function PopSmWindow(WindowLink)
{
window.open(WindowLink,'wine', 'height=450,width=600,toolbar=no,location=no,directories=no, status=no,menubar=no,scrollbars=yes,resizable=yes, copyhistory=no,width=600,height=450') 
}

function PopInsuredLoginWindow(WindowLink)
{
window.open(WindowLink,'winf', 'height=800,width=600,toolbar=no,location=no,directories=no, status=no,menubar=no,scrollbars=no,resizable=no, copyhistory=no,width=600,height=800') 
}

function CreateAgentInfo(PanelID) {
	// Insert/Update data from the Current Visible Panel to the database and move to the next Panel.

    if (isEmpty(PanelID)) {
        alert("...Missing PanelID...");
        return;
    }
    
    var docID = document.getElementById;
    
    // ***** Contact Information Panel *****
    if (PanelID == 1) {

        // Set the Phone & FAX fields
	    docID("Phone").value = docID("Phone1").value + docID("Phone2").value + docID("Phone3").value;
	    if (docID("PhoneExt").value != "") {
	        docID("Phone").value = docID("Phone").value+"x"+docID("PhoneExt").value;
	    }
	    docID("FAX").value = docID("FAX1").value + docID("FAX2").value + docID("FAX3").value;

		// Verify data has been entered for the following fields in FieldIDList.
        var FieldIDList = new Array("BusinessLine", "BusinessName", "Address1", "Zipcode", 
                                    "City", "State", "Phone1", "Phone2", "Phone3", "Email");
        if (VerifyRequiredFields(FieldIDList) == false) {return;}
		
        // Move to the next Panel
    	docID("Panel1").style.visibility = 'hidden';
        docID("Panel2").style.visibility = 'visible';
        // Set focus to first field on the new visible panel
	    docID("BusinessYears").focus();

		// Formulate the SQL Column Names & Values for the SQL Insert statement
        var FieldIDList = new Array("Program", "BusinessLine", "BusinessName", "PrincipalsName", 
                                    "Address1", "Address2", "Zipcode", "City", "State", 
                                    "Phone", "FAX", "Email", "IsMailingAddress",
                                    "MailAddress1", "MailAddress2", "MailCity", "MailState", "MailZipCode");
        // Formulate the Column Names
		for (i in FieldIDList) {
		    if (i == 0) {
		        var SqlColumnNames = FieldIDList[0];
		    } else {
   				SqlColumnNames = SqlColumnNames+", "+FieldIDList[i];
   		    }
   		}
		// Formulate the Column Values
		for (i in FieldIDList) {
		    if (i == 0) {
		        if (isWhitespace(docID(FieldIDList[0]).value)) {
		            var SqlColumnValues = "NULL";
		        } else {
		            var SqlColumnValues = "'"+docID(FieldIDList[0]).value+"'";
		        }
		    } else {
		        if (isWhitespace(docID(FieldIDList[i]).value)) {
		            SqlColumnValues = SqlColumnValues+", NULL";
		        } else {
   			        SqlColumnValues = SqlColumnValues+", '"+docID(FieldIDList[i]).value+"'";
   			    }
   			}
   		}

		// Check for apostrophes and replace so the INSERT doesn't fail
		// var SqlColumnValues = SqlColumnValues.replace(/'/g,'');  // NOT WORKING...

		stSQL = "Insert into AgentAppointment (" + SqlColumnNames + ") values (" + SqlColumnValues + ");";
   		// Add the Sql Statement to get the PrimaryKey value after the Insert
   		stSQL = stSQL + " Select SCOPE_IDENTITY();";


    // ***** Company Information Panel *****
	} else if (PanelID == 2) {

		// Verify data has been entered for the following fields in FieldIDList.
        var FieldIDList = new Array("BusinessYears", "PassengerVolumeAll", "PassengerVolume", "MonthlyApps", 
                                    "PrincipalMarkets1");
        if (VerifyRequiredFields(FieldIDList) == false) {return;}
	
	    // Move to the next Panel
	    docID("Panel2").style.visibility = 'hidden';
        docID("Panel3").style.visibility = 'visible';
        // Set focus to Close button on the new visible panel
	    docID("CloseButton").focus();
	    
	    // Formulate the SQL Update statement
        var FieldIDList = new Array("BusinessYears", "PassengerVolumeAll", "PassengerVolume", "MonthlyApps", 
                                    "PrincipalMarkets1", "PrincipalMarkets2", "PrincipalMarkets3", "Comments");
		for (i in FieldIDList) {
		    if (i == 0) {
		        if (isWhitespace(docID(FieldIDList[0]).value)) {
		            var SqlColumnNamesValues = FieldIDList[0]+" = NULL";
		        } else {
		            var SqlColumnNamesValues = FieldIDList[0]+" = '"+docID(FieldIDList[0]).value+"'";
		        }		    
		    } else {
		        if (isWhitespace(docID(FieldIDList[i]).value)) {
		            SqlColumnNamesValues = SqlColumnNamesValues+", "+FieldIDList[i]+" = NULL";
		        } else {
		            SqlColumnNamesValues = SqlColumnNamesValues+", "+FieldIDList[i]+" = '"+docID(FieldIDList[i]).value+"'";
		        }
   		    }
   		}
   		
   		stSQL = "Update AgentAppointment Set " + SqlColumnNamesValues
   		        + " Where PrimaryKey = " + docID("PrimaryKey").value + ";";
   		// Add a dummy Sql Statement so that cmd.ExecuteScalar() in CreateAgentAppointment.aspx will without an error
   		// ** To be removed once CreateAgentAppointment.aspx can determine incoming string is Insert or Update
   		stSQL = stSQL + " Select CURRENT_USER;";
   		        
	}
	
	// For Debugging the Sql statement
   	//alert(stSQL);
   	
  	// Properly Encode the SQL statement that will be sent to the server over xmlHTTP POST method
   	stSQL = "stSQL="+encodeURIComponent(stSQL);
   	if (PanelID == 2) {
   		// Add parameters to let CreateAgentAppointment.aspx know the application is completed.
   	    // This can then trigger additional code on the server side to run such as sending email
   	    stSQL = "AppCompleted=1&PrimaryKey="+docID("PrimaryKey").value+"&"+stSQL;
   	}

	// Send SQL statement to server
	// Results are returned once xmlHttp.readyState is completed (see ProcessSQLData() function)
   	SendSQLData(stSQL);

}


var xmlHttp
function SendSQLData(stSQL) {
	// Call a server page to execute a SQL statement and return
	// the results using the XMLHTTP object.
	// This Remote Procedure Call method will avoid reloading the entire page.

    xmlHttp=GetXmlHttpObject()
 
    if (xmlHttp==null)
    {
        alert ("Browser does not support HTTP Request")
        return;
    }
    // Location of the server page that will process the SQL Statment
    // (** in the future this process should be changed to a WebService that calls a stored procedure **)
    var url="CreateAgentAppointment.aspx"
    xmlHttp.onreadystatechange=ProcessSQLData
	
   	xmlHttp.open("POST", url, false);

   	// Format the stSQL value as a Form POST so we can use "Request.Form(stSQL)" on the server.
	xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

	// Submit the HTTP request
	// Results are returned once xmlHttp.readyState is completed (see ProcessSQLData() function)
   	xmlHttp.send(stSQL);

}

function ProcessSQLData() 
{ 
    if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
    {
        // Get the results from the server
        var response=xmlHttp.responseText;
        
        response=response.substring(0,response.indexOf("<!DOCTYPE")-4);
        
        if(response=="Empty")
        {
            alert("No Record Found !!!");
        }
        else if(response=='Error')
        {
            alert("An xmlHttp Error occured in accessing the Database !!!");
        }
        else
        {
            //alert(xmlHttp.responseText);


            // Extract the Primary Key from the xmlHttp response.
            // The hidden PrimaryKey field will be empty when going from Panel1 to Panel2
            if (isEmpty(document.getElementById("PrimaryKey").value)) {
                var ResultsArray = response.split('|');
                var PrimaryKey = ResultsArray[0];
                document.getElementById("PrimaryKey").value = PrimaryKey;
            }
            
                        
            // Move to the next Panel
	//docID = document.getElementById;
	//docID("Panel1").style.visibility = 'visible'
            
            
        }
        
        xmlHttp = null;
   } 
} 

function GetXmlHttpObject()
{ 
    var objXMLHttp=null
    if (window.XMLHttpRequest)
    {
        objXMLHttp=new XMLHttpRequest()
    }
    else if (window.ActiveXObject)
    {
        objXMLHttp=new ActiveXObject("Microsoft.XMLHTTP")
    }
    return objXMLHttp
} 


var ZipCodeFieldID  // set in getZipInfo so ProcessZipInfo can know which Zipcode field needs the info

function getZipInfo(CurrentZipCode, FieldID) {
	// Return the City, State, Areacode for the given Zipcode.

    if (isEmpty(CurrentZipCode)) {return;}
    
	// FieldID is the ID tag for the Input Field so we know which Zipcode field needs info
    ZipCodeFieldID = FieldID;

	// Call a server page to execute a SQL statement and return
	// the results using the XMLHTTP object.
	// This Remote Procedure Call method will avoid reloading the entire page.
    xmlHttp=GetXmlHttpObject()
    if (xmlHttp==null)
    {
        alert ("Browser does not support HTTP Request")
        return;
    }
    
    // Request will be sent to the WebService to query the database
    var url="http://www.aggressiveinsurance.net/GetZipInfo.asmx/GetZip?z=" + CurrentZipCode;
    //var url="http://localhost/Aggressive/GetZipInfo.asmx/GetZip?z=" + CurrentZipCode;
    xmlHttp.onreadystatechange=ProcessZipInfo

	// Submit the HTTP request
	// Results are returned once xmlHttp.readyState is completed (see ProcessZipInfo() function)
   	xmlHttp.open("GET", url, true);
   	xmlHttp.send(null);

}

function ProcessZipInfo() {
    // Process the XML dataset returned from the Web Service that contains the Zip info
    if (xmlHttp.readyState == 4) {
    
        // for debugging
        //alert("responseText=    " + xmlHttp.responseText);
        
        if (xmlHttp.status == 200) {
            var response = xmlHttp.responseXML.documentElement;
            if (response.text == "") {
                alert("Please enter a valid zip code");
                return;
            }
            var responseCity = response.getElementsByTagName('city')[0].firstChild.data;
            var responseState = response.getElementsByTagName('state')[0].firstChild.data;
            //var responseAreacode = response.getElementsByTagName('areacode')[0].firstChild.data;
            
            if (ZipCodeFieldID == "Zipcode") {
                document.getElementById("City").value = responseCity;
                document.getElementById("State").value = responseState;
                //document.getElementById("Phone1").value = responseAreacode;
                //document.getElementById("Phone1").select();
            } else if (ZipCodeFieldID == "MailZipCode") {
                document.getElementById("MailCity").value = responseCity;
                document.getElementById("MailState").value = responseState;
            }
        } else {
            alert("Please enter a valid zip code:\n" +
            xmlHttp.statusText);
        }
    }
}

function VerifyRequiredFields(FieldIDList) {		
	// Get all the <LABEL> tags associated with the current form.
	var LabelTags = document.AppointmentsForm.getElementsByTagName("LABEL");
	for (i in FieldIDList) {
		var CurrentField = document.getElementById(FieldIDList[i]);
		// If no value was entered for the current enabled field...
		if (isWhitespace(CurrentField.value) && CurrentField.disabled == false) {
			// Set the Field Label for the alert message to the field ID
			// just in case a <LABEL> tag was not defined for the current field.
			var FieldLabel = FieldIDList[i];
			// Find the Label Text associated with the current field.
			for ( i=0; i < LabelTags.length; i++ ) {
				if (LabelTags[i].htmlFor == CurrentField.id) {
					FieldLabel = LabelTags[i].innerHTML;
					break;
				}
			}	
			alert("Please enter a value for '"+FieldLabel+"'");
			CurrentField.focus();
			return false;
		}
	}
}

function VerifyInteger() {
	/* Verify field value is an integer. */
	
	// Get the Current field object and its value.
	var oField = window.event.srcElement;
	var FieldValue = oField.value;
	
	// If value is not blank...
	if (!isWhitespace(FieldValue)) {
		if (!isInteger(FieldValue)) {
			alert("Value must be numeric.");
			oField.focus();
			oField.select();
			return false;
		}
	}
}

function VerifyEmail() {
	/* Verify field value is a valid email address. */

	// Get the Current field object and its value.
	var oField = window.event.srcElement;
	var FieldValue = oField.value;
	
	// If value is not blank...
	if (!isWhitespace(FieldValue)) {
		if (!isEmail(FieldValue)) {
			alert("Value must be a valid email address in the form of\n\tx@x.x");
			oField.focus();
			oField.select();
			return false;
		}
	}
}

function NextOnMaxLength() {
	/*
	   When the maxlength has been reached for the current field, move to the
	   next field on the current form using the tabIndex attribute.
	*/
	
	// Get the Current field object and its value.
	var oField = window.event.srcElement;
	var FieldValue = oField.value;
	// If the Current field length equals the <INPUT> fields maxlength attribute...
	if (FieldValue.length == oField.maxLength) {
		var CurrentTabIndex = oField.tabIndex;
		var oForm = oField.form;
		var ele = oForm.elements;
		for ( i=0; i < ele.length; i++ ) {
			// Move to the first enabled field in the form collection with a 
			// tabIndex greater than the current.
			if (ele[i].tabIndex > CurrentTabIndex && ele[i].disabled == false) {
				ele[i].focus();
				break;
			}
		}
	}
}

function EnableMailingFields() {
	/* Enable all the Mailing Address fields if Radio button is 'Yes', else disable if 'No'. */

	if (window.event.type == "click") {
		var FieldValue = window.event.srcElement.value;
	} else { 
		return false;
	}	
	var FieldIDList = new Array("MailAddress1", "MailAddress2", "MailCity", "MailState", "MailZipCode");
	for (i in FieldIDList) {
		var CurrentElement = document.getElementById(FieldIDList[i]);
		if (FieldValue == "Y") { // enable the fields...
			CurrentElement.disabled = false;		
			CurrentElement.style.background = "#ffffff";
			CurrentElement.value = "";
		} else { // disable the fields...
			CurrentElement.disabled = true;		
			CurrentElement.style.background = "#cccccc";
			CurrentElement.value = "";
		}		
	}
	if (FieldValue == "Y") {
	    // IsMailingAddress is the actual Input field that gets sent to the database.
	    // IsMailingAddressYes & IsMailingAddressNo fields are only there to display
	    // a Radio Button so we need to manually set the value for IsMailingAddress Input field
	    // based on which Radio Button was clicked.
	    document.getElementById("IsMailingAddress").value = "Y";
		document.getElementById("MailAddress1").focus();
	} else {
	    document.getElementById("IsMailingAddress").value = "N";
	}
}

function SetBusinessLineLabel2() {
    // When BusinessLine value on Panel 1 changes, set BusinessLineLabel2 on Panel 2 to the same value.
    docID = document.getElementById;
    docID("BusinessLineLabel2").innerText = docID("BusinessLine").value;
}

function BackButtonClick(PanelID) {
    // Move back one Panel from the current Panel
    // No validations are done so if "Next" is clicked after clicking "Back"
    // any code written for that "Next" button will run again.
    docID = document.getElementById;
    if (PanelID == 3) {
	    docID("Panel3").style.visibility = 'hidden';
        docID("Panel2").style.visibility = 'visible';
    } else if (PanelID == 4) {
	    docID("Panel4").style.visibility = 'hidden';
        docID("Panel3").style.visibility = 'visible';
    }
}


function NextButtonBypass(PanelID) {
// ** FOR TEST PURPOSES ONLY **
// ** REMOVE KeyPress FUNCTION on the Next Buttons FOR PRODUCTION ENVIORONMENT **
// When the single-quote character (') key is press on the Next Button, 
// bypass current Panel validations and move to the next Panel without running any other code.
	
	docID = document.getElementById;
	if (window.event.keyCode == 39)  {
	    if (PanelID == 1) {
    	    docID("Panel1").style.visibility = 'hidden';
            docID("Panel2").style.visibility = 'visible';
            docID("NextButton2").focus();
        } else if (PanelID == 2) {
    	    docID("Panel2").style.visibility = 'hidden';
            docID("Panel3").style.visibility = 'visible';
            docID("CloseButton").focus();
        } else if (PanelID == 3) {
    	    docID("Panel3").style.visibility = 'hidden';
            docID("Panel1").style.visibility = 'visible';
            docID("NextButton1").focus();
        }
    }
}

//========================================
// Runs when Appointments page loads
//========================================

function AppointmentsOnLoad() {

	// Make the first Panel form visible
	// (Initially all Panels are hidden using the CSS class "AppointmentPanel")
	docID = document.getElementById;
	docID("Panel1").style.visibility = 'visible'
	
	
	/* Setup the field Event binding - used for various validations
	   We're binding here instead of embedding the javascript functions directly in the HTML tag.
	   ** This will only include binding to functions that don't require parameters   */
	   
	// For fields in FieldIDList set ONKEYUP event to the NextOnMaxLength function.
	var FieldIDList = new Array("Zipcode", "Phone1", "Phone2", "Phone3", "PhoneExt", 
								"FAX1", "FAX2", "FAX3", "MailZipCode");
	for (i in FieldIDList) {
		docID(FieldIDList[i]).onkeyup = NextOnMaxLength;
	}
	// For fields in FieldIDList set ONCHANGE event to the VerifyInteger function.
	var FieldIDList = new Array("Zipcode", "Phone1", "Phone2", "Phone3", "PhoneExt",
								"FAX1", "FAX2", "FAX3", "MailZipCode");
	for (i in FieldIDList) {
		docID(FieldIDList[i]).onchange = VerifyInteger;
	}
	
    // Any other fields...
    docID("Email").onchange = VerifyEmail;
	docID("IsMailingAddressYes").onclick = EnableMailingFields;
	docID("IsMailingAddressNo").onclick = EnableMailingFields;
	
	// Set focus to first field on the form
	docID("BusinessLine").focus();
}
