/*
	This code is to allow Javascript to communcted to the Server in order to update it
*/

//
// Define a list of Microsoft XML HTTP ProgIDs.
//
var XMLHTTPREQUEST_MS_PROGIDS = new Array(
  "Msxml2.XMLHTTP.7.0",
  "Msxml2.XMLHTTP.6.0",
  "Msxml2.XMLHTTP.5.0",
  "Msxml2.XMLHTTP.4.0",
  "MSXML2.XMLHTTP.3.0",
  "MSXML2.XMLHTTP",
  "Microsoft.XMLHTTP"
);

//
// Define ready state constants.
//
var XMLHTTPREQUEST_READY_STATE_UNINITIALIZED = 0;
var XMLHTTPREQUEST_READY_STATE_LOADING       = 1;
var XMLHTTPREQUEST_READY_STATE_LOADED        = 2;
var XMLHTTPREQUEST_READY_STATE_INTERACTIVE   = 3;
var XMLHTTPREQUEST_READY_STATE_COMPLETED     = 4;

//
// Returns XMLHttpRequest object. 
//
function getXMLHttpRequest()
{
  var httpRequest = null;

  // Create the appropriate HttpRequest object for the browser.
  if (window.XMLHttpRequest != null)
    httpRequest = new window.XMLHttpRequest();
  else if (window.ActiveXObject != null)
  {
    // Must be IE, find the right ActiveXObject.
    var success = false;
    for (var i = 0;i < XMLHTTPREQUEST_MS_PROGIDS.length && !success;i++)
    {
      try
      {
        httpRequest = new ActiveXObject(XMLHTTPREQUEST_MS_PROGIDS[i]);
        success = true;
      }
      catch (ex)
      {}
    }
  }

  // Display an error if we couldn't create one.
  if (httpRequest == null)
    alert("Error in HttpRequest():\n\n"
      + "Cannot create an XMLHttpRequest object.");

  // Return it.
  return httpRequest;
}

//adds in a comma in the current postion for display affect
function addCommas(nStr)
{
	if (nStr != undefined)
	{
		nStr += '';
		x = nStr.split('.');
		x1 = x[0];
		x2 = x.length > 1 ? '.' + x[1] : '';
		var rgx = /(\d+)(\d{3})/;
		while (rgx.test(x1)) {
			x1 = x1.replace(rgx, '$1' + ',' + '$2');
		}
		return x1 + x2;
	}//end of if
	
	return "";
}//end of addCommas()

//Adds text to any part of the body of a HTML
function addNode(tagParent,strText,boolAddToBack, boolRemoveNode)
{
  var strNode = document.createTextNode(strText);//holds the test which will be added
     
  //gets the properties of the node
  tagParent = getDocID(tagParent);
  
  //checks if the user whats to replace the node in order to start with a clean slate
  //it also checks if there is a chode node to replace
  if (boolRemoveNode == true && tagParent.childNodes.length > 0)
	//replaces the current node with what the user wants
	tagParent.replaceChild(strNode,tagParent.childNodes[0]);
  else
  {
  	//checks if the user whats to added to the back of the id or the front
  	if(boolAddToBack == true)
		tagParent.appendChild(strNode);
  	else
		//This is a built-in function of Javascript will add text to the beginning of the child
  		insertBefore(strNode,tagParent.firstChild);
  }//end of if else
  
  //returns the divParent in order for the user to use it for more uses
  return tagParent;
}//end of addNode()

/*

	Start of Auto Insurance Estimator funcitons ONLY FOR LEVINE SITE

*/

//for the Death Caluations
function addingDeath()
{	
	var floTotal = parseFloat(removeCommas(getDocID('txtMortgage').value)) + parseFloat(removeCommas(getDocID('txtDebt').value)) + parseFloat(removeCommas(getDocID('txtEmerg').value)) + parseFloat(removeCommas(getDocID('txtFinal').value));//holds the total for the function

	//does the Caluations for the First Section, Death
	getDocID('txtDeath').value = addCommas(floTotal.toFixed(0));
	
	//checks if an error in the total and if so then put it to zero
	if (getDocID('txtDeath').value == "NaN")
		getDocID('txtDeath').value = "0";
		
	//does the total calutions of this section for Liabilities
	liabilitiesCalutions();
}//end of addingDeath()

//for the Child Caluations
function childCalutions()
{
	var floTotal = parseFloat(removeCommas(getDocID('txtNumChild').value)) * parseFloat(removeCommas(getDocID('txtCostChild').value)) * parseFloat(removeCommas(getDocID('txtYearsChild').value));//holds the total for the function
	
	//does the Caluations for the 2nd Section, Child
	getDocID('txtChildEdu').value = addCommas(floTotal.toFixed(0));
		
	//checks if an error in the total and if so then put it to zero
	if (getDocID('txtChildEdu').value == "NaN")
		getDocID('txtChildEdu').value = "0";
		
	//does the total calutions of this section for Liabilities
	liabilitiesCalutions();
}//end of childCalutions()

//for the Lost Income Caluations
function incomeCalutions()
{	
	/*//var floPercent = parseFloat(getDocID('txtIncomePercent').value) * 0.01;//holds the Percent
	var floAnnAmmount = parseFloat(getDocID('txtIncome').value) * 0.03 * 12;//holds the Annountal Ammount
	var folInterest = parseFloat(getDocID('txtIncomeInterest').value) - parseFloat(getDocID('txtIncomeIndex').value);//holds the Inerest
		
	//does the Caluations for the 3nd Section, Lost Income
	getDocID('txtIncomeReplace').value = floAnnAmmount + 1 + folInterest + parseFloat(getDocID('txtIncomeNumYears').value) + 12;
	
	var floPerInfer = parseFloat(getDocID('txtIncomeIndex').value) * 0.01;//holds the Percent
	
	//does the Caluations for the 3nd Section, Lost Income
	getDocID('txtIncomeReplace').value = parseFloat(getDocID('txtIncome').value) * 1 * parseFloat(getDocID('txtIncomeNumYears').value) * floPerInfer + 0;*/
	
	realRateCalculations();

  	var intFreq = 1;//the number of times they will pay for that year for the life insurance
	var floIncomeRateReturn = parseFloat(removeCommas(getDocID('txtIncomeRateReturn').value));//holds the Income Rate Return
	var floIncomeIndex = parseFloat(removeCommas(getDocID('txtIncomeIndex').value));//holds the Income Index
	
	//makes sure that there is some sort of value from 1 - 100 in the index
	if (floIncomeIndex != 0.00)
    	fract_index = factorForPeriod(1 + (floIncomeIndex / 100), intFreq);
  	else
    	fract_index = 1;
  
  	var r_sum = 0;//holds the sum of the income
  	var r_income = parseFloat(removeCommas(getDocID('txtIncome').value));//holds what percent the user what to use for there life insurance
  	var fract_discount = factorForPeriod(1 + (floIncomeRateReturn / 100), intFreq);//holds the discount that they might have

	//goes around for each year they have the life insurance and how many times the they will pay for that year for the life insurance
  	for (intIndex = 1; intIndex <= parseInt(removeCommas(getDocID('txtIncomeNumYears').value)) * intFreq; intIndex++)
	{
    	r_sum = r_sum + r_income;
    	r_income = r_income * fract_index / fract_discount;
  	}//end of for loop
  	
	//updates the total income
	getDocID('txtIncomeReplace').value = addCommas(r_sum.toFixed(0));
	
	//checks if an error in the total and if so then put it to zero
	if (getDocID('txtIncomeReplace').value == "NaN")
		getDocID('txtIncomeReplace').value = "0";
	
	//does the total calutions of this section for Liabilities
	liabilitiesCalutions();
}//end of incomeCalutions()

//for the Real Rate Calculations
function realRateCalculations()
{	
	//does the Caluations that added up the last three section Death, Child and Lost Income
	getDocID('txtRealRate').value = parseFloat(removeCommas(getDocID('txtIncomeRateReturn').value)) - parseFloat(removeCommas(getDocID('txtIncomeIndex').value));
		
	//checks if an error in the total and if so then put it to zero
	if (getDocID('txtRealRate').value == "NaN")
		getDocID('txtRealRate').value = "0";
		
	//rounds the real rate to be only one diecimlly
	getDocID('txtRealRate').value = parseFloat(getDocID('txtRealRate').value);
		
	//does the grand total of both sections Liabilities and Assets
	insuranceCalutions();
}//end of realRateCalculations()

//for the Total of Liabilities
function liabilitiesCalutions()
{
	var floTotal = parseFloat(removeCommas(getDocID('txtDeath').value)) + parseFloat(removeCommas(getDocID('txtChildEdu').value)) + parseFloat(removeCommas(getDocID('txtIncomeReplace').value));//holds the total for the function
	
	//does the Caluations that added up the last three section Death, Child and Lost Income
	getDocID('txtLiabilities').value = addCommas(floTotal.toFixed(0));
			
	//checks if an error in the total and if so then put it to zero
	if (getDocID('txtLiabilities').value == "NaN")
		getDocID('txtLiabilities').value = "0";
	
	//does the grand total of both sections Liabilities and Assets
	insuranceCalutions();
}//end of liabilitiesCalutions()

//for the Assets
function assetsCalutions()
{
	var floTotal = parseFloat(removeCommas(getDocID('txtLiquid').value)) + parseFloat(removeCommas(getDocID('txtLifeIns').value));//holds the total for the function
	
	//does the Caluations for Assests
	getDocID('txtTotalLiquid').value = addCommas(floTotal.toFixed(0));	
	
	//checks if an error in the total and if so then put it to zero
	if (getDocID('txtTotalLiquid').value == "NaN")
		getDocID('txtTotalLiquid').value = "0";
	
	//does the grand total of both sections Liabilities and Assets
	insuranceCalutions();
}//end of assetsCalutions()

//for Insurance
function insuranceCalutions()
{
	var floTotal = parseFloat(removeCommas(getDocID('txtLiabilities').value)) - parseFloat(removeCommas(getDocID('txtTotalLiquid').value));//holds the total for the function
	
	//does the Caluations for both the grand total for both the assests and Liabilities
	getDocID('txtTotalLiabAssets').value = addCommas(floTotal.toFixed(0));
		
	//checks if an error in the total and if so then put it to zero
	if (getDocID('txtTotalLiabAssets').value == "NaN")
		getDocID('txtTotalLiabAssets').value = "0";
}//end of insuranceCalutions()

/*

	End of Auto Insurance Estimator funcitons

*/

//checks if the number is current
function checkNumber(tagNum,strSectionName,tagMessage)
{
	//checks if tagNum is an actully number
	if(IsNumeric(tagNum.value) == false)
 		{displayMessage(tagMessage,"In the " + strSectionName + " Section, the Field must be a Number",true,true);
			return false;}

	//resets the display Message
	displayMessage(tagMessage,'',true,true);
	
	//makes sure that there is some in the tagNum in order not to have a non-number error in the total of the section
	if (tagNum.value == "")
		return false;
	else
		return true;
}//end of checkNumber()

//sets up the basic Links since they are so many of them for Links ONLY
function createLink(tagTD,strLink,strOnClick,strNameTag,strClassName)
{
	//sets the Attributes for the tagA then adds it to the table
	tagA = document.createElement('a');//holds the Linking tag
	tagA.setAttribute('href',strLink);
	if (strClassName != '') tagA.setAttribute('class', strClassName);
	if (strOnClick != '') tagA.setAttribute('onclick',strOnClick);
	tagA.appendChild(document.createTextNode(strNameTag));
	tagTD.appendChild(tagA);
	
	return true;
}//end of createLink()

//decodes str to be a normal string in order to read it
function decodeURL(strDecode)
{
     return unescape(strDecode.replace(/\+/g, " "));
}//end of decodeURL()

//does the display the a message in a on the page weather then an alert
function displayMessage(tagMessage,strMessText,boolAddToBack, boolRemoveNode)
{
	//gets the message properties and sets the text furthermore it does the display
	tagMessage = addNode(tagMessage,strMessText,boolAddToBack, boolRemoveNode);
	tagMessage.style.display = "block";	
	
	return tagMessage;
}//end of displayMessage()

//encodes str to a URL so it can be sent over the URL address
function encodeURL(strEncode) {
	var strResult = "";
	
	for (intIndex = 0; intIndex < strEncode.length; intIndex++) {
		if (strEncode.charAt(intIndex) == " ") strResult += "+";
		else strResult += strEncode.charAt(intIndex);
	}
	
	return escape(strResult);
}//end of encodeURL()

//gives the user the message has been sent or not and changes the pop area
function endMessage(strEndMessage,strID,tagMessage)
{
	tagPopUpArea = getDocID("div" + strID + "Email");//holds the pop up area
	
	//adds some text to the div tag and then displays it to the user
	displayMessage(tagMessage,strEndMessage,true,true);
	
	//adds in the new line
	tagPopUpArea.appendChild(document.createElement('br'));
	
	//checks if there is the finction was called by the Contact form which does not have a CSS Pop-Up Window
	if (strID != "")
	{
		var tagDIV = document.createElement('div');//holds the DIV tag
		
		//holds the real time div and give its name and align and the link that will close the pop up
		tagDIV.setAttribute('id', "divClose" + strID);
		tagDIV.setAttribute('align', "center");
		tagPopUpArea.appendChild(tagDIV);
		
		//Because IE is not Startand the browser things the code is string until they fix it it will have to be like this 
		//checks if the user is uing IE or another Browser
		if (navigator.userAgent.indexOf('MSIE') !=-1)
		{
			//sets the Attributes for the tagA then adds it to the table
			var tagA = document.createElement('a');//holds the Linking tag
			tagA.setAttribute('href',"javascript:void(0);");
			tagA.setAttribute('className',"aBlackColour");
			tagA.onclick = function(){toggleLayer("div" + strID + "Email");}
			tagA.appendChild(document.createTextNode("[Close]"));
			tagDIV.appendChild(tagA);
		}//end of if
		else
			//resets the tagA and does remove node and creates the A tags Attribute
			createLink(tagDIV,"javascript:void(0);","javascript:toggleLayer('div" +strID + "Email')",'[Close]','aBlackColour');
	}//end of if
}//end of endMessage()

//does the factoring for the period
function factorForPeriod(r_appr, freq)
{
  return Math.exp(Math.log(r_appr)* 1 / freq);
}//end of factorForPeriod()

//gets the document properties in order to use them as there are many types of browers with different versions
function getDocID(tagLayer)
{
	var tagProp = "";//holds the proerties of tagLayer

	//gets the whichLayer Properties depending of the differnt bowers the user is using
	if (document.getElementById)//this is the way the standards work
		tagProp = document.getElementById(tagLayer);
	else if (document.all)//this is the way old msie versions work
		tagProp = document.all[tagLayer];
	else if (document.layers)//this is the way nn4 works
		tagProp = document.layers[tagLayer];
		
	return tagProp;
}//end of getDocID()

//checks if sText is a number or not
function IsNumeric(sText)
{
   var ValidChars = "0123456789.-,";//holds the valid chars
   var IsNumber=true;//holds the indecater that sText is a number
   var Char;//holds each chars of sText
 
   //goes around checking each char in sText
   for (intIndex = 0; intIndex < sText.length && IsNumber == true; intIndex++) 
   { 
   	  //gets each char of sText then does a indexOf to see if it is a validchar
      Char = sText.charAt(intIndex); 
      if (ValidChars.indexOf(Char) == -1) 
         IsNumber = false;
   }//end of for loop
   
   return IsNumber;
}//end of IsNumeric()

//removes all new lines and replaces them with a <br/> html tag
function nl2br(strText)
{
	//checks if there is anything inside strText
	if (strText != "")
	{
 		var re_nlchar = "";//holds the different newlines that the OS uses
		strText = escape(strText);//in codes strText to be more like a URL to find the newlines
			
		//finds the either \r or \n or both since \r is for Linex and Apple and \n is for MS
		if(strText.indexOf('%0D%0A') > -1)
			re_nlchar = /%0D%0A/g ;
		else if(strText.indexOf('%0A') > -1)
			re_nlchar = /%0A/g ;
		else if(strText.indexOf('%0D') > -1)
			re_nlchar = /%0D/g ;
	
		//checks if there is any new lines in strText
		if (re_nlchar != "")
			//changes the strText back to normal with all of the newlines changes to <br/> tag
			return unescape(strText.replace(re_nlchar,'<br />'));
	}//end of if
	
	return strText;
}//end of nl2br()

//set up the form to not be used while sending the message
function preSendEMail(tagMessage,tagEMailBody)
{
	//display to the user their message is beening sent and disables the textbox area
	displayMessage(tagMessage,'Sending Message...',true,true);
	tagEMailBody.style.display = 'none';
}//end of preSendEMail()

//removes the commas on the money values to use them in math foumlas
function removeCommas(strMoney)
{	
	//makes sure that there is some thing inside strMoney to check
	if (strMoney != "" && strMoney != undefined)
		return strMoney.replace(/,/g, '');
	else
		return "";
}//end of removeCommas()

//sends an email to one of the bios people in About2.php
function sendEMail(strPHPFileName,tagName,tagEMail,tagComm,strEmpID,tagMessage,strSubject,tagEMailBody,intID)
{
	tagName = getDocID(tagName);//holds the text box for the Name
	tagEMail = getDocID(tagEMail);//holds the text box for the E-Mail
	tagComm = getDocID(tagComm);//holds the textarea Commentss
	tagEMailBody = getDocID(tagEMailBody);//holds the Body of the message where the user types in there message
	
	var strFilter = /^.+@.+\..{2,3}$/;//holds the filtter for the Email
	var htmlJavaServerObject = getXMLHttpRequest();//holds the object of the server
	
	//checks if there is a Name
	if (tagName.value=="")
  		{displayMessage(tagMessage,'You must have a Name Entered',true,true);
			return false;}
	
	//checks if there is E-Mail
	if (tagEMail.value=="")
  		{displayMessage(tagMessage,'You must have E-Mail Address',true,true);
			return false;}	
			
	//checks if there the E-Mail Format is current
	if (strFilter.test(tagEMail.value) == false)
  		{displayMessage(tagMessage,'Please Input Valid E-Mail Address!',true,true);
			return false;}	
	else if (tagEMail.value.match(/[\(\)\<\>\,\;\:\\\/\"\[\]]/))
  		{displayMessage(tagMessage,'The E-Mail Address Contains Illegal Characters.',true,true);
			return false;}
			
	//checks if there is some Commentss
	if (tagComm.value=="")
  		{displayMessage(tagMessage,'You must have some Comments',true,true);
			return false;}	
		
	//Abort any currently active request.
	htmlJavaServerObject.abort();
	
	//prepers the form for sending a e-mail
	preSendEMail(tagMessage,tagEMailBody);
	
	// Make a request
 	htmlJavaServerObject.open("Post", strPHPFileName, true);
	htmlJavaServerObject.setRequestHeader("Content-Type","application/x-www-form-urlencoded");

	htmlJavaServerObject.onreadystatechange = function(){
    	if(htmlJavaServerObject.readyState == 4 && htmlJavaServerObject.status == 200)
		{
			//closes the pop up and removes the textbox so the user cannot use them again until they refresh the page
			endMessage(htmlJavaServerObject.responseText,intID,tagMessage);
						
			//resets the fields and disables the field area
			tagName.value = "";
			tagEMail.value = "";
			tagComm.value = "";
			tagEMailBody.style.display = "none";
		}//end of if
	}//end of function()
	htmlJavaServerObject.send("txtName=" + encodeURL(tagName.value) + "&txtFromEMail=" + encodeURL(tagEMail.value) + "&txtComm=" + encodeURL(nl2br(tagComm.value)) + "&EmpID=" + encodeURL(strEmpID) + "&Subject=" + encodeURL(strSubject));

	return true;
}//end of sendEMail()

//sends an email from one of the arrow images that is throw out the site.
function sendEMailArrow(strPHPFileName,tagName,tagCompany,tagPhone,tagEMail,tagComm,tagMessage,tagSubject,tagEMailBody,strID)
{	
	tagName = getDocID(tagName);//holds the text box for the Name
	tagEMail = getDocID(tagEMail);//holds the text box for the E-Mail
	tagComm = getDocID(tagComm);//holds the textarea Commentss
	tagPhone = getDocID(tagPhone);//holds the text box for the Phone Number
	tagSubject = getDocID(tagSubject);//holds the text box for the Subject
	tagEMailBody = getDocID(tagEMailBody);//holds the Body of the message where the user types in there message
	
	var strFilter = /^.+@.+\..{2,3}$/;//holds the filtter for the Email
	var strPhoneString = tagPhone.value.replace(/[\(\)\.\-\ ]/g, '');//removes teh basic phone number chars
	var htmlJavaServerObject = getXMLHttpRequest();//holds the object of the server

	//checks if there is a Name
	if (tagName.value=="")
  		{displayMessage(tagMessage,'You must have a Name Entered',true,true);
			return false;}

	//skips over the comapny since it not need for the Doctors
	if(tagCompany != "")
	{
		tagCompany = getDocID(tagCompany);//holds the text box for the Company
		
		//checks if there is a Company
		if (tagCompany.value=="")
			{displayMessage(tagMessage,'You must have a Company Entered',true,true);
				return false;}
	}//end of if
	
	//checks if there is a Phone
	if (tagPhone.value=="")
  		{displayMessage(tagMessage,'You must have a Phone Number Entered',true,true);
			return false;}
			
	//checks if there the Phone Number Format is current
	if (IsNumeric(strPhoneString) == false)
  		{displayMessage(tagMessage,'The Phone Number Contains Illegal Characters.',true,true);
			return false;}
	else if (!(strPhoneString.length == 10))
  		{displayMessage(tagMessage,'The Phone Number is the Wrong Length, Included an Area Code.',true,true);
			return false;}
		
	//checks if there is E-Mail
	if (tagEMail.value=="")
  		{displayMessage(tagMessage,'You must have E-Mail Address',true,true);
			return false;}	
			
	//checks if there the E-Mail Format is current
	if (strFilter.test(tagEMail.value) == false)
  		{displayMessage(tagMessage,'Please Input Valid E-Mail Address!',true,true);
			return false;}
	else if (tagEMail.value.match(/[\(\)\<\>\,\;\:\\\/\"\[\]]/))
  		{displayMessage(tagMessage,'The E-Mail Address Contains Illegal Characters.',true,true);
			return false;}
			
	//checks if there is some Commentss
	if (tagComm.value=="")
  		{displayMessage(tagMessage,'You must have some Comments',true,true);
			return false;}
		
	//Abort any currently active request.
	htmlJavaServerObject.abort();
	
	//prepers the form for sending a e-mail
	preSendEMail(tagMessage,tagEMailBody);
	
	// Makes a request
 	htmlJavaServerObject.open("Post", strPHPFileName, true);
	htmlJavaServerObject.setRequestHeader("Content-Type","application/x-www-form-urlencoded");

	htmlJavaServerObject.onreadystatechange = function(){
    	if(htmlJavaServerObject.readyState == 4 && htmlJavaServerObject.status == 200)
		{
			//closes the pop up and removes the textbox so the user cannot use them again until they refresh the page
			endMessage(htmlJavaServerObject.responseText,strID,tagMessage);
			
			//skips over the comapny since it not need for the Doctors
			if(tagCompany != "")
				tagCompany.value = "";
				
			//resets the fields and disables the field area
			tagPhone.value = "";
			tagName.value = "";
			tagEMail.value = "";
			tagComm.value = "";
			tagEMailBody.style.display = "none";
		}//end of if
	}//end of function()
	
	//skips over the comapny since it not need for the Doctors
	if(tagCompany != "")
		htmlJavaServerObject.send("txtName=" + encodeURL(tagName.value) + "&txtFromEMail=" + encodeURL(tagEMail.value) + "&txtComm=" + encodeURL(nl2br(tagComm.value)) + "&EmpID=0&Subject=" + encodeURL(tagSubject.value) + "&Phone=" + encodeURL(tagPhone.value) + "&Company=" + encodeURL(tagCompany.value));
	else
		htmlJavaServerObject.send("txtName=" + encodeURL(tagName.value) + "&txtFromEMail=" + encodeURL(tagEMail.value) + "&txtComm=" + encodeURL(nl2br(tagComm.value)) + "&EmpID=0&Subject=" + encodeURL(tagSubject.value) + "&Phone=" + encodeURL(tagPhone.value) + "&Company=");
			
	return true;
}//end of sendEMailArrow()