/*-------------------------------------------------------------------------------------------
 2010-01-03 DoRiders() - Increase brochure no. from 4 to 6 chars - in riders-form.asp only.
 2010-01-08 DoRiders() - If DealerID specified, Set AFFILIATE field to ------.
 2010-01-17 doPartnerForm - ChequeName  & ContactName
 2010-01-18 xx and zz testing for forms
 2010-03-12 Contact form - make Tel required.
 2010-03-25 Set E to EMBEDDED for Order Type
 2010-03-25 [TEST] in subject line for xx or zz
 2010-03-27 Remove formmail,php for riders form - dealers.
 2010-04-28 Ride for Sight - If Brochure field contains Membership no, bypass credit Card Screen
 2010-05-02 Payment CC revamp - Calls new riders-payment-form.asp instead of riders-form-cc.asp/
 2010-05-14 Tweak doDealer()  rad.value to rad. This rtn is called on form pageload.
 2010-06-14 Ride for Sight - Bypass payment form if BrichureNo format is E10-tr-900-10237 - new riders-rfs-confirm.asp page
 2010-06-24 Price Changes
 2010-07-01 HST
 2010-10-06 Renewals/remove dealer ID.
***-------------------------------------------------------------------------------------------*/
	
//* This handles running script locally, on TEST, and in production without changes.
  	var thesite		= "http://motorescue.ca";
  	var thesiteSSL	= "https://motorescue.ca";
	var test = "";
	var dirx = location.href.substring(0,location.href.lastIndexOf('/')+1);	
	if (dirx.indexOf("/test/") > -1) {
		sMode = "TEST"	
//		thesite = "";
		test = "/test";			
	}
	if (dirx.indexOf("localhost") > -1) {
		sMode = "LOCAL"
		thesite = "";
		test = "/mo";	
	}
//	alert(thesite + test + "/en/riders-confirm-dealer.asp") 
 
	var imagedir = "../images";
	
//* Init these to prevent javascript error on submit when testing with xx	
	var nPrice = 0;
	var nTax = 0;
	var nTotal = 0;
	
	var keycount = 0;
	var sDealerType = "";  // E = Embedded  W = Wholesale, ie over the counter.
 
//*---------------------------------------	
//* Login Button
//*---------------------------------------
	if(document.images){
	  	loginon 	= new Image(); loginon.src= imagedir + "/b-loginon.gif";
	 	loginoff	= new Image(); loginoff.src= imagedir + "/b-loginoff.gif";  	
	  	logouton 	= new Image(); logouton.src= imagedir + "/b-logouton.gif";
	 	logoutoff	= new Image(); logoutoff.src= imagedir + "/b-logoutoff.gif"; 
	} 		  	

function calcPrice ( arg, form) {
//******************************************************************************* 
// Calculate Price based on radio buttons selected
//*******************************************************************************  
// 	alert(arg);
	nPrice1 = 59.95;  //69.95;
	nPrice2 = 79.95;
	nPrice3 = 99.95;
 
	if (arg == 1) {		
		nPrice = nPrice1;
	}
	if (arg == 2) {
		nPrice = nPrice2;
	}
	if (arg == 3) {
		nPrice = nPrice3;
	}
	
		nPrice	= formatDollar(nPrice);
 		nTax	=  parseFloat(nPrice * .13) //* HST
		nTax	= formatDollar(nTax);
		nTotal	= parseFloat(nTax) + parseFloat(nPrice);					
		nTotal	= formatDollar(nTotal);
 	
		document.form0.Price.value = nPrice;
		document.form0.Tax.value = nTax;
		document.form0.Total_Cost.value = nTotal;
 
}

function pad(number, length) {
//******************************************************************************* 
//  PAD String with leading zeroz
//*******************************************************************************  
    var str = '' + number;
    while (str.length < length) {
        str = '0' + str;
    }
    return str;
}

function doDealer ( form, rad ) {
//******************************************************************************* 
//  Call when Dealer? radio buttons are pressed. Show/hide dealerid and brochureno.
//*******************************************************************************  	
//alert(form);
	var sDealer = rad.value;
	
	//* This is required if run from onLoad event in the form page.
	if (form == "xyzzy") {
		sDealer = rad; 
	}	
 	
	if (sDealer == "Y") {
		 // show_dealer (ordertypex,dealeridx)
		 document.getElementById("dealeridx").style.display='block';
		 document.getElementById("brochurex").style.display='none';
		 document.form0.BrochureNo.value = "";
	}

	if (sDealer == "N") {
		 document.getElementById("dealeridx").style.display='none';
		 document.getElementById("ordertypex").style.display='none';
		 document.getElementById("brochurex").style.display='block';
		 document.form0.DealerID.value = "";
		 document.form0.Order_Type[0].checked = false;
		 document.form0.Order_Type[1].checked = false;
	}
//	alert(rad);	
//	alert(sDealer);	
} 

function doChange(form) {
//******************************************************************************* 
//   DEALER ID FIELD - If user pastes in the id, this will handle displaying ordertype radios.
//*******************************************************************************  
   	var sDealerID = spaceTrim(document.form0.DealerID.value);	
	var nDealerID_len = sDealerID.length;
	
	if (nDealerID_len >= 8) {
		sDealerID = spaceTrim(document.form0.DealerID.value);
		sDealerID = sDealerID.toUpperCase();
		document.form0.DealerID.value = sDealerID; //Put uppercase back into form.
		var sDealerIDBeg 	= sDealerID.substring(0,3);
		var sDealerIDMid 	= sDealerID.substring(3,6);
		var sDealerIDEnd 	= sDealerID.substring(7,8);	
	}
	if (sDealerIDEnd == "E") {
		document.getElementById("ordertypex").style.display='block';
	}
	else {
		document.getElementById("ordertypex").style.display='none';
	}
// 	alert(nDealerID_len + " END= " + sDealerIDEnd);
}

function doKey(e) {
//*******************************************************************************
// DEALER ID FIELD 
//  onkeydown="return doKey(event)" 
// e/E = 69    w/W = 87  
// http://www.quirksmode.org/js/keys.html
//*******************************************************************************       
    var k;
    document.all ? k = e.keyCode : k = e.which;

/*
	if ((k > 47 && k < 58) || 
		k == 8 || 
		k == 9 || 
		(k > 95 && k < 106) ||
		(k >= 65 && k <= 90)) {
	}
 */
 
	var sDealerID = spaceTrim(document.form0.DealerID.value);	
	var nDealerID_len = sDealerID.length + 1;

	//* If Char position 8 and it's a E, it's Embedded.  86 = v for paste
	if (nDealerID_len >= 8 ) {
		if (k == 69 || k == 86) {
		  sDealerType = "E";
		  //* Display embedded/wholesale radio button
		  document.getElementById("ordertypex").style.display='block';
		}
		if (k == 87) {
		  sDealerType = "W";
		  //* Hide embedded/wholesale radio button
		  document.getElementById("ordertypex").style.display='none';
		}		
	}						
	else {
		sDealerType = "";
		document.getElementById("ordertypex").style.display='none';
	}	
	
   document.all ? k = e.keyCode : k = e.which;
 	return ((k > 47 && k < 58) || k == 8 || k == 9 || (k > 95 && k < 106) || (k >= 65 && k <= 90));
}

function numeric(e) {
//*******************************************************************************
// 	Don't allow keypress if not numeric
//  onkeydown="return numeric(event)"   
//*******************************************************************************       
     var k;
     document.all ? k = e.keyCode : k = e.which;
     return ((k > 47 && k < 58) || k == 8 || k == 9 || (k > 95 && k < 106));
}
 
//*----------------------------------------------
//* Show and Hide  
//*---------------------------------------------- 
function show_dealer (sh1,hi1) {
//	alert(sh1);
 	document.getElementById(hi1).style.display='none';
	document.getElementById(sh1).style.display='block'; 
}
 
function doPartnerForm ( form ) {	
//*******************************************************************************
// AFFILIATE SIGNUP FORM   XXX123 
//******************************************************************************* 
//		theString = "ABCDEFGHIJKLMNPQRSTUVWXYZ"; //** O removed
//		sLetter1 = randomChar(theString);
//		sLetter2 = randomChar(theString);
		//* Append 2 random letters to end
 
//		sRandNum = randomInt(100, 999); 
//		sAffCode = "X" + sRandNum + sLetter1 + sLetter2;
       //alert(sAffCode);

	var firstmessage="Please provide the following valid information:\n\n ";
	var errormessage="";
    var testFlag = 0;  // set to 1 if Comments = "xx", 2 if "zz" - bypass validation.

//       alert(sAffCode)
	if (spaceTrim(document.form0.ChequeName.value) == "") errormessage=errormessage + "Cheque Recipient Name\n"; 
	if (spaceTrim(document.form0.Website.value) == "") errormessage=errormessage + "Website\n";       	
 	if (spaceTrim(document.form0.ContactName.value) == "") errormessage=errormessage + "Contact Name\n";
  	if (spaceTrim(document.form0.Address.value) == "") errormessage=errormessage + "Address\n";
  	if (spaceTrim(document.form0.City.value) == "") errormessage=errormessage + "City\n";

//*------------------------------------
//* Province SELECT LIST
//*------------------------------------
  	itemx = document.form0.Prov.selectedIndex;
 	itemval = document.form0.Prov.options[itemx].value
 	if (itemval == "") errormessage = errormessage + "Province\n";
 	
  	if (spaceTrim(document.form0.Postal_Code.value) == "") errormessage=errormessage + "Postal Code\n";
 	if (spaceTrim(document.form0.Telephone.value) == "") errormessage=errormessage + "Telephone\n";
 
	if (document.form0.Email.value.length ==0 || document.form0.Email.value.indexOf('@', 0) == -1 || document.form0.Email.value.indexOf('.', 0) == -1) {errormessage=errormessage+"Email address\n"} 

//* If City start with xx, set testFlag on - for developer testing 
	var sCity = spaceTrim(document.form0.City.value);
	if (sCity.substring(0,2) == "xx") {errormessage=""; testFlag = 1;}
	if (sCity.substring(0,2) == "zz") {errormessage=""; testFlag = 2;} 		
       
	if (errormessage !="") { alert (firstmessage + errormessage) ;}
	else { 	
 		var sEmailto = "service@motorescue.ca";			// Default receipient 
// 		sEmailto = "pc@twistedpixel.com";				// TESTING
 	  	document.form0.recipients.value = sEmailto;
		
		if (testFlag == 1) {
			document.form0.recipients.value = "pc@twistedpixel.com";
			document.form0.Email.value 		= "pc@twistedpixel.com"; 
		}
		if (testFlag == 2) {
			document.form0.recipients.value = "nscn@sympatico.ca";		 
			document.form0.Email.value 		= "nscn@sympatico.ca"; 			
		}		

		if(testFlag != 0) {
			document.form0.ChequeName.value		= "Acme Widget Corp.";
 			document.form0.Website.value		= "www.acmewidget.com";
			document.form0.ContactName.value	= "John Smith"; 
			document.form0.Address.value		= "123 Main Street"; 
			document.form0.City.value			= "Toronto"; 
			document.form0.Prov.selectedIndex	= "9"; 
			document.form0.Postal_Code.value	= "L9M 1E1"; 
			document.form0.Telephone.value		= "416-555-5555"; 
		}

//*------------------------------------------
//* CALCULATE PARTNER CODE (AFFCODE)  XXX999
//*------------------------------------------
       sWebsite = spaceTrim(document.form0.Website.value);
     
 //      sWebsite =	fnGetDomain(sWebsite);
		
		//http://www.developertutorials.com/questions/question/q-242.php
   		domainArray = sWebsite.split('.'); 
   		domainArrayLen = domainArray.length;
   		// eg. http://twistedpixel.com
        if (domainArrayLen == 2) {
        	sWebsite = domainArray[0];
        }
        // eg. http://www.twistedpixel.com
   		if (domainArrayLen == 3) {
        	sWebsite = domainArray[1];
        }

		sAffPrefix = sWebsite.substr(0,3)
		
        //* Get rid of http:// prefix if it's there.
       if (sWebsite.indexOf("http://") == 0) {
			sAffPrefix = sWebsite.substr(7,3)  ; 	       		
		}
		sAffPrefix = sAffPrefix.toUpperCase();        
//        alert(domainArrayLen);
//        alert(sWebsite);
 
/*------------------  
       if (sWebsite.indexOf('www.') == 0) {
			sAffPrefix = sWebsite.substr(4,3)  ; 	       		
		}
		else {
			sAffPrefix = sWebsite.substr(0,3) ;
		}
---------------------*/		


		sRandNum = randomInt(100, 999); 
		sAffCode = sAffPrefix + sRandNum;
//		alert(sAffCode);

		document.form0.AffCode.value = sAffCode;  //* Write it to a hidden field in the form
		
//		document.form0.cc.value = "service@motorescue.ca";			 	 	
 		document.form0.bcc.value = "pc@twistedpixel.com";			 	 	
 
//		document.form0.email.value = document.form0.Email.value;  //* Not really need because not using formmail.
		//* Email field is blank so set from email (formmail "from" var) to default recipient
//		if (spaceTrim(document.form0.Email.value) == "") {
//			document.form0.email.value = sEmailto;
//		} 
		
		sGoodUrl = thesite + test + "/en/partners-confirm.asp";
		sSubject = "MOTORESCUE - PARTNER SIGN-UP " + sAffCode;
	  	document.form0.subject.value = sSubject; 	
		document.form0.good_url.value = sGoodUrl;
		
// 		document.form0.action = thesite + test + "/en/partners-send.asp"; 
 		document.form0.action = "partners-send.asp";  	
  		document.form0.method = "POST";
     	document.form0.submit()
 		return(0);		

	}       
}  //* END DOPARTNERS()

function doMembershipType ( form ) {	
//*******************************************************************************
// Process MembershipType radio buttons
//******************************************************************************* 
//	sBrochureNoSave = document.form0.BrochureNo.value;
	var sDashes = "-------------------------------------------";
//* New membership - disable (readonly) brochure (membership) field.
	if (document.form0.MembershipType[0].checked) {		 
		document.form0.BrochureNo.style.backgroundColor = "#DDDDDD";
//		document.form0.BrochureNo.disabled="true";
		document.form0.BrochureNo.readOnly = true;
		document.form0.BrochureNo.value = sDashes;
		document.getElementById("promoinstructions").style.display='none';
	}
	
//* Renewal or Dealer. Dealers must enter a dealer id.	
 	if (document.form0.MembershipType[1].checked || document.form0.MembershipType[2].checked) {		 
		document.form0.BrochureNo.style.backgroundColor = "#FFFFFF";
//		document.form0.BrochureNo.disabled="false";
		document.form0.BrochureNo.readOnly=false;
		if (document.form0.BrochureNo.value == sDashes) document.form0.BrochureNo.value = "";		
		document.getElementById("promoinstructions").style.display='block';
	} 
}
 	
function doRiders ( form ) {	
//*******************************************************************************
// RIDERS SIGNUP FORM - FORMMAIL.PHP 
//******************************************************************************* 
	var firstmessage="Please provide the following valid information:\n\n ";
	var errormessage="";
	var errorcode=0; 
	var len;
	var testFlag = 0;  // set to 1 if Comments = "xx", 2 if "test" - bypass validation.
	var isDealer = 0;  //* Set to 1 if it's a dealer entering info. NEW and Membership # in brochure field

 
//*-------------------------------------------------------
//* FOR TESING
//* If City start with xx or zz, set testFlag on - for developer testing 
//*-------------------------------------------------------
	var sCity = spaceTrim(document.form0.City.value);
	
	if (sCity.substring(0,2) == "xx") { testFlag = 1;}
	if (sCity.substring(0,2) == "zz") { testFlag = 2;} 	
	

		if (testFlag == 1) {
			document.form0.recipients.value = "pc@twistedpixel.com";
			document.form0.Email.value 		= "pc@twistedpixel.com"; 
		}
		if (testFlag == 2) {
			document.form0.recipients.value = "nscn@sympatico.ca";		 
			document.form0.Email.value 		= "nscn@sympatico.ca"; 			
		}		

		if(testFlag != 0) {
			document.form0.Name.value			= "Bif Roderick"; 			
			document.form0.Address.value		= "123 Main Street"; 
			if (sCity.length == 2) { 
				document.form0.City.value = document.form0.City.value + " Toronto"; 
			} 
			
			document.form0.Prov.selectedIndex	= "9"; 
			document.form0.Postal_Code.value	= "L9M 1E1"; 
			document.form0.Telephone.value		= "416-555-5555"; 
			document.form0.Vehicle_Type[1].checked = true;    //* Motorcycle Radio
			document.form0.Make.value = "Yamaha";
			document.form0.Model.value = "BFM-3000";
			document.form0.PlateNo.value = "78432";
			document.form0.Colour.value = "Black";
			document.form0.Vehicle_Year.selectedIndex	= "11";   //* Drop
			document.form0.Price.value = "79.95";       
			document.form0.Tax.value = "7.79";         
			document.form0.Total_Cost.value = "83.94 ";  
		}	
 
//*------------------------------------
//  DEALER RADIO 
//*------------------------------------
//	if (document.form0.Dealer[0].checked ||
//		document.form0.Dealer[1].checked  ) {	}
//	 		else {errormessage=errormessage + "Dealer?\n"} 
	 		

//*-----------------------------------------------------------------------------------
//* If brochure no. starts with 3 letters, it's a dealer id. Bypass Credit Card form.
//*-----------------------------------------------------------------------------------
/*-------------------------
	var isDealer = 0;  //* Set to 1 if it's a dealer entering info.
	var bDealerIDvalid = 0;
	var sOrderType = "";  // E or W. For E Dealers only
 
	//* If dealer
	if (document.form0.Dealer[1].checked) {
		isDealer = 1;
		sDealerID = spaceTrim(document.form0.DealerID.value);
		sDealerID = sDealerID.toUpperCase();
		document.form0.DealerID.value = sDealerID; //Put uppercase back into form.
		var sDealerIDBeg 	= sDealerID.substring(0,3);
		var sDealerIDMid 	= sDealerID.substring(3,6);
		var sDealerIDEnd 	= sDealerID.substring(7,8);	
		//sDealerIDEnd 		= sDealerIDEnd.toUpperCase();
//		alert(sDealerID);

		if (sDealerID.length = 8) {
			if (isAlphabeticString(sDealerIDBeg) == true &&	
				isInteger(sDealerIDMid) == true &&
				(sDealerIDEnd == "E" || sDealerIDEnd == "W")) {
//					alert("good");
					bDealerIDvalid = 1;
					sDealerType = sDealerIDEnd;
				}
			else {
				 errormessage=errormessage + "Dealer ID\n";
				}
		}
		
		else {
			//* Dealerid length < 8 is invalid 		
			errormessage=errormessage + "Dealer ID\n";
		}
	}
 	
	if (sDealerIDEnd == "E") {
		//*------------------------------------
		//  ORDER TYPE RADIO   E or W
		//*------------------------------------
		if (document.form0.Order_Type[0].checked ||
			document.form0.Order_Type[1].checked  ) {
				if (document.form0.Order_Type[0].checked ) 
					sOrderType = document.form0.Order_Type[0].value;
			    if (document.form0.Order_Type[1].checked ) 
					sOrderType = document.form0.Order_Type[1].value;
			}
		 	else {errormessage=errormessage + "Order Type\n"} 				
	}
	if (sDealerIDEnd == "W") {
		 sOrderType = "W";   //* Always W if Dealer type is W
	}
----------------------------------*/

 
// 	alert("Beg=" + sDealerIDBeg + "\nMid=" + sDealerIDMid + "\nEnd=" + sDealerIDEnd);	 		  
 
	//*------------------------------------
	//  If DealerID is specied, Afflilate code must be blank.
	//*------------------------------------ 
// 	if (document.form0.DealerID.length > 0 || document.form0.DealerID.value != "") {
// 		document.form0.AFFILIATE.value = "------"; 
// 	}

//*------------------------------------
// MEMBERSHIP TYPE RADIO - NEW or RENEW 
//*------------------------------------
	var sMembershipType = ""; // NEW or RENEW
	if (document.form0.MembershipType[0].checked ||
		document.form0.MembershipType[1].checked ||
		document.form0.MembershipType[2].checked ) {	
			if (document.form0.MembershipType[0].checked) sMembershipType = "NEW";
			if (document.form0.MembershipType[1].checked) sMembershipType = "RENEW";	
			if (document.form0.MembershipType[2].checked) {
				var isDealer = 1;  //* Set to 1 if it's a dealer entering info.  BYPASS CREDIT CARD SCREEN
				sMembershipType = "DEALER";		
			}
		}
	 		else {errormessage=errormessage + "New Membership or Renewal?\n"}   
 
 //*--------------------------------------------------------------------
//* VALIDATE MEMBERSHIP NO. (In Promo field which is labeled BrochureNo)
//*--------------------------------------------------------------------
	sBrochureNo = spaceTrim(document.form0.BrochureNo.value);
	sBrochureNo = sBrochureNo.toUpperCase();
	document.form0.BrochureNo.value = sBrochureNo;  //* put upper case version back into form
		
//* E10-TR-210-10070 
	var sBroch1 = "";
	var sBroch2 = "";
	var sBroch3 = "";
	var sBroch4 = "";
	var nBrochValid = 0;  //* Set to 4 later if valide membership number
	var nBroch1Valid = 0;
	var nBroch2Valid = 0;
	var nBroch3Valid = 0;
	var nBroch4Valid = 0;

//alert("sBrochureNo=" + sBrochureNo + "\nLength=" + sBrochureNo.length +  "\nCount=" + sBrochureNo.count('-'))

	if (sBrochureNo.length == 16 && sBrochureNo.count('-') == 3 ) {
	
		var sSplit = sBrochureNo.split("-");
		if (sSplit != null && sBrochureNo != "") {
			
		    sBroch1 = sSplit[0];	// E10
		    sBroch2 = "" + sSplit[1];	// TR
		    sBroch3 = sSplit[2];	// 210
		    sBroch4 = sSplit[3];	// 10070
		} 
//		alert("sBroch2=" + sBroch2)
		sBroch1_1 = sBroch1.substring(0,1);  //* E
		sBroch1_2 = sBroch1.substring(1);    //* 10
	//	if (sBroch2 != "undefined" && sBroch3 != "undefined" && sBroch4 != "undefined") {
			if (isAlphabeticChar(sBroch1_1) == true && isInteger(sBroch1_2) == true  && sBroch1.length == 3) {		
				nBroch1Valid = 1;  //* Valid		
			}
			if (isAlphabeticString(sBroch2) == true && sBroch2.length == 2) {		
				nBroch2Valid = 1;  //* Valid		
			}
			if (isInteger(sBroch3) == true && sBroch3.length == 3) {		
				nBroch3Valid = 1;  //* Valid		
			}	
			if (isInteger(sBroch4) == true && sBroch4.length == 5) {		
				nBroch4Valid = 1;  //* Valid		
			}
	//	}	
		//* if sBrochValid == 4, then membership # is valid.
		nBrochValid = nBroch1Valid + nBroch2Valid + nBroch3Valid + nBroch4Valid;		
	}
			
 //	alert("nBrochValid=" + nBrochValid);
 	
	if ((sMembershipType == "RENEW" || sMembershipType == "DEALER") && nBrochValid != 4) {
		errormessage=errormessage + "Membership No.\n"  //* If renewal, membership number must be correct format
	} 
 
 	if (spaceTrim(document.form0.Name.value) == "") errormessage=errormessage + "Name\n";
  	if (spaceTrim(document.form0.Address.value) == "") errormessage=errormessage + "Address\n";
  	if (spaceTrim(document.form0.City.value) == "") errormessage=errormessage + "City\n";

//*------------------------------------
//* Province SELECT LIST
//*------------------------------------
  	itemx = document.form0.Prov.selectedIndex;
 	itemval = document.form0.Prov.options[itemx].value;
 	var sProv = itemval;  //* Need to put this in cookie
 	if (itemval == "") errormessage = errormessage + "Province\n";
 	
  	if (spaceTrim(document.form0.Postal_Code.value) == "") errormessage=errormessage + "Postal Code\n";
 	if (spaceTrim(document.form0.Telephone.value) == "") errormessage=errormessage + "Telephone\n";
 
	if (document.form0.Email.value.length ==0 || document.form0.Email.value.indexOf('@', 0) == -1 || document.form0.Email.value.indexOf('.', 0) == -1) {errormessage=errormessage+"Email address\n"} 

//*------------------------------------
// VEHICLE TYPE RADIO  (Scooter / Motorcycle
//*------------------------------------
	if (document.form0.Vehicle_Type[0].checked ||
		document.form0.Vehicle_Type[1].checked ) {	}
	 		else {errormessage=errormessage + "Vehicle Type\n"}   

//*------------------------------------
//* Vehicle_Year SELECT LIST
//*------------------------------------
  	itemx = document.form0.Vehicle_Year.selectedIndex;
 	itemval = document.form0.Vehicle_Year.options[itemx].value
 	if (itemval == "") errormessage = errormessage + "Vehicle Year\n";

	if (spaceTrim(document.form0.Make.value) == "") errormessage=errormessage + "Vehicle Make\n";
	if (spaceTrim(document.form0.Model.value) == "") errormessage=errormessage + "Vehicle Model\n";
	if (spaceTrim(document.form0.PlateNo.value) == "") errormessage=errormessage + "License Plate No.\n";
	if (spaceTrim(document.form0.Colour.value) == "") errormessage=errormessage + "Colour\n";
 
//  	errormessage ="";  // Uncomment to deactivate validation for Testing

//*-------------------------------------------
//* Check if it's a dealer entering the info
//*-------------------------------------------
//	if (sMembershipType == "NEW" && nBrochValid == 4) {
//		var isDealer = 1;  //* Set to 1 if it's a dealer entering info.  BYPASS CREDIT CARD SCREEN
//	}

	if (errormessage !="") { alert (firstmessage + errormessage) ;}
	else { 	
 		var sEmailto = "service@motorescue.ca";			// Default receipient 
// 		sEmailto = "pc@twistedpixel.com";				// TESTING
 	  	document.form0.recipients.value = sEmailto;
 
 		document.form0.bcc.value = "pc@twistedpixel.com";			 	 	

		if (testFlag == 1) {
			document.form0.recipients.value = "pc@twistedpixel.com"; 
		}

	if (sMembershipType == "NEW") {
		sBrochureNo = "";  //* Remove dashes from field so it won't print in subject
	}

		document.form0.email.value = document.form0.Email.value;
		
		//* Email field is blank so set from email (formmail "from" var) to default recipient
		if (spaceTrim(document.form0.Email.value) == "") {
			document.form0.email.value = sEmailto;  //s5to  ??
		} 

//***  STORE COST in COOKIE. TO BE RETRIEVED FROM CREDIT CARD FORM

//*--------------------------------------
//* TRANSACTION NO. YYYYMMDD-hhmmss-XX where XX = 2 random letters
//*--------------------------------------
		var now = new Date();
 		sTransNo = dateFormat(now, "yyyymmdd-HHMMss"); 
		theString = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
		sLetter1 = randomChar(theString);
		sLetter2 = randomChar(theString);
		//* Append 2 random letters to end
		sTransNo = sTransNo + "-"   + sLetter1 + sLetter2;
		
		sAuthCode = "61-" + randomInt(1111, 9999); 
//		alert(sAuthCode);
//		alert(sTransNo);
 

//*------------------------------------
//* SET COOKIES. TO be retrived in riders-form-cc.asp
//*------------------------------------
//		thePrice = document.form0.Price.value = nPrice;
//		theTax   = document.form0.Tax.value = nTax;
//		theTotal = document.form0.Total_Cost.value = nTotal;
		
		thePrice = document.form0.Price.value;
		theTax   = document.form0.Tax.value;
		theTotal = document.form0.Total_Cost.value;
				
		theTrans = sTransNo;
		theEmail = document.form0.Email.value;

//* NOT REQUIRED - Now using riders-payment-form.asp which doesn't use cookies
//		setCookie("thePrice", thePrice); 
//		setCookie("theTax", theTax); 
//		setCookie("theTotal", theTotal); 
//		setCookie("theTrans", sTransNo); 
//		setCookie("theEmail", theEmail);

//*------------------------------------ 
//* To put in cookie to pass to dealer confirm form
//*------------------------------------ 
 	var sName = spaceTrim(document.form0.Name.value);
 	var sAddress = spaceTrim(document.form0.Address.value);
 	var sCity = spaceTrim(document.form0.City.value);
// 	var sProv = itemval;  //* Done above.
 	var sPostal = spaceTrim(document.form0.Postal_Code.value);
	sPostal = sPostal.toUpperCase();
	document.form0.Postal_Code.value = sPostal; //Put uppercase back into form.		
//* NOT REQUIRED - Now using riders-payment-form.asp which doesn't use cookies
//		setCookie("theName", sName); 
//		setCookie("theAddress", sAddress);
//		setCookie("theCity", sCity);
//		setCookie("theProv", sProv);
//		setCookie("thePostal", sPostal);
// 		setCookie("theAuthCode", sAuthCode);
		 
		//* Put these Vars in the form to pass to riders-confirm-dealer.asp
		document.form0.TransNo.value = theTrans; 
		document.form0.AuthCode.value = sAuthCode;
//		document.form0.DealerType.value = sDealerType;  //* E or W
// 		document.form0.OrderType.value = sOrderType;  //* E or W
		
		var sFormmail = thesite + "/formmail.php"; //* Default formmail script for  non dealer submissions
		
		//* Default is Rider with Credit Card		
//		sBrochureNo = spaceTrim(document.form0.BrochureNo.value);
 
 	  	sSubject = "MR RIDER A " + sMembershipType + " " + sTransNo + " " + sBrochureNo;
// 	  	sSubject = "MR RIDER A " + sTransNo + " " + sBrochureNo;
	    sGoodUrl =  thesiteSSL + test + "/en/riders-form-cc.asp";   // 2010-05-02 new routine used. 
		//sGoodUrl =  thesiteSSL + test + "/en/riders-form-payment.asp";  // 2010-05-02 new routine
 		sFormmail = thesiteSSL + test + "/en/riders-payment-form.asp";  // 2010-05-02 new routine
		//*-------------------------------------------------------------------------------------
		//* If it's a dealer entering the info, then bypass credit card form
		//* If Brochure contains membership no E10-TR-210-10070, then bypass credit card form
		//* Still uses the STATIC confirmation form.
		//*-------------------------------------------------------------------------------------
		//* If it's a dealer entering the info, then bypass credit card form
		
		if (isDealer == 1) {
			sGoodUrl = thesite + test + "/en/riders-confirm-rider.asp";
 			sSubject = "MR DEALER - " + sTransNo + " " + sBrochureNo;
 			sFormmail = thesite + "/formmail.php";
 //			sFormmail = thesiteSSL + test + "/en/riders-payment-confirm.asp";  // 2010-05-02   ***** CONFIRM ****  Cant pass date to this
 			sFormmail = thesite + test + "/en/riders-confirm-dealer.asp";
 			//sFormmail = thesiteSSL + test + "/en/riders-rfs-confirm.asp";  // 2010-06-14 Static form for Ride for Sight (RFS)
		}

 	
		//* If dealer then bypass credit card form
//		if (isDealer == 1) {
// 			sGoodUrl = thesite + test + "/en/riders-confirm-dealer.asp";
// 			sSubject = "MR RIDERS D " + sTransNo + " " + sBrochureNo;
//		}
//		alert(sOrderType);

	
		
//*---------------------------------
//* IF DEALER		
//*---------------------------------
//		if (isDealer == 1) {
//			sSubject = "MR DEALER " + sDealerType + " " + sTransNo + " - " + sOrderType;
//			sGoodUrl = "";  //* N/A because we're not using formmail here	 		
//	 		sFormmail = thesite + test + "/en/riders-confirm-dealer.asp";
//		} //* END IF DEALER

		if (testFlag == 1 || testFlag == 2 ) {
			sSubject = sSubject + " [TEST]"; 
		}
				
//		alert(sSubject + "\n" + sFormmail);
// 	  	alert(sFormmail)
		document.form0.subject.value = sSubject; 	
		document.form0.good_url.value = sGoodUrl;
 		document.form0.action = sFormmail;  	
		document.form0.method = "POST";
  	  	document.form0.submit()
 		return(0); 	
   }  
}


function doPaymentCC ( form ) {	
//******************************************************************************* 
//  CREDIT CARD INFO - FORMMAIL.PHP 
//******************************************************************************* 
	var firstmessage="Please provide the following valid information:\n\n ";
	var errormessage = "";
	var errorcode=0; 
	var len;
	var testFlag = 0;  // set to 1 if Comments = "xx", 2 if "test" - bypass validation.
 
//*------------------------------------
//* GET COOKIES
//*------------------------------------
  
//	thePrice = getCookie("thePrice"); 
//	theTax   = getCookie("theTax");
//	theTotal = getCookie("theTotal");
//	theTrans = getCookie("theTrans");
//	theEmail = getCookie("theEmail");
 
//	document.form0.Price.value = thePrice;
//	document.form0.Tax.value = theTax;
//	document.form0.Total_Cost.value = theTotal;
//	document.form0.TransNo.value = theTrans;
//	document.form0.email.value = theEmail;
 
// theData = thePrice + " " + theTax + " " + theTotal + " " + theTrans + " " + theEmail;
// alert(theData)
 
//*------------------------------------
//* CREDIT CARD VALIDATION
//*------------------------------------
	m_cardname = "Cardholder name";
	m_cardtype = "Card Type";
	m_cardno = "Card number";
	m_cardmm = "Card Expiry Month";
	m_cardyy = "Card Expiry Year";
	m_carddate = "Card Expiry Date";
	m_ccid = "CCID (Security code)";

//*------------------------------------
// CARD TYPE
//*------------------------------------
	if (document.form0.Card_Type[0].checked ||
		document.form0.Card_Type[1].checked ||
		document.form0.Card_Type[2].checked ) {	}
	 		else {errormessage=errormessage + m_cardtype + "\n"} 

if (spaceTrim(document.form0.Cardholder_Name.value) == "") errormessage=errormessage + m_cardname + "\n";  		
      	
//*** CARD NUMBER 
	minlength = 8; fieldblank=true;
    document.form0.Cardno.value = spaceTrim(document.form0.Cardno.value);	
    for (j=0; j < document.form0.Cardno.value.length; j++) 
    {
      if (document.form0.Cardno.value.substring(j,j+1) !=" ") {fieldblank=false}
    }
    if (document.form0.Cardno.value.length < minlength || fieldblank || isCreditCardString(document.form0.Cardno.value) == false)
      	{errormessage=errormessage + m_cardno + "\n";}        
      	
//*** MM       	
	itemmm = document.form0.Card_Exp_mm.selectedIndex;
	itemval = document.form0.Card_Exp_mm.options[itemmm].value;
 	cardmm = itemval;
	if (itemmm == "") {errormessage=errormessage + m_cardmm + "\n";}		      		

//*** YY 
	itemyy = document.form0.Card_Exp_yy.selectedIndex;
	itemval = document.form0.Card_Exp_yy.options[itemyy].value;
 	cardyy = itemval;
	if (itemyy == "") {errormessage=errormessage + m_cardyy + "\n";} 
	
//* mm and yy have been selected, check if card date is older than current date
	if (itemmm != "" & itemyy != "") {
		var today = new Date();
	    var thisyy = today.getYear();					// NS4x: Year is 3 digits (eg. 102), IE4x, Year is 4 digits (eg. 2002)
	    var thismm = today.getMonth() + 1;				// add 1 to compensate since Jan = 00, Dec = 11.
	    
	    var yystring = "" + thisyy;  					// convert to string
		var yylen = yystring.length;
	    thisyy = yystring.substring(yylen-2,yylen);		// Use last 2 digits of year
	    
	    var mmstring = "" + thismm;						// convert to string
	    var mmlen = mmstring.length;
	    if (mmlen == 1) thismm = "0" + thismm;			// Pad 0 on left
	    
 	    thisyyyymm = "20" + thisyy + thismm;
 	    cardyyyymm = "20" + cardyy + cardmm;    
	    
	    //* If card date older than current date
	    if (cardyyyymm < thisyyyymm) {errormessage=errormessage + m_carddate + "\n";}  
    }
    
    if (document.form0.CCID.value.length < 3) {errormessage=errormessage + m_ccid + "\n";} 
//*------------------------------------   
//** End Credit card validation 	
//*------------------------------------
 
//  	errormessage ="";  // Uncomment to deactivate validation for Testing

//* If comments start with xx, set testFlag on - for developer testing 
	var sCardholder_Name = spaceTrim(document.form0.Cardholder_Name.value);
	if (sCardholder_Name.substring(0,2) == "xx") {errormessage=""; testFlag = 1;}
	if (sCardholder_Name.substring(0,4) == "zz") {errormessage=""; testFlag = 2;} 	

	if (errormessage !="") { alert (firstmessage + errormessage) ;}
	else { 	
 		var sEmailto = "service@motorescue.ca";			// Default receipient 
// 		sEmailto = "pc@twistedpixel.com";
 			
 	  	document.form0.recipients.value = sEmailto;
		
		if (testFlag == 1) {
			document.form0.recipients.value = "pc@twistedpixel.com";
			document.form0.email.value 		= "pc@twistedpixel.com"; 
		}
		if (testFlag == 2) {
			document.form0.recipients.value = "nscn@sympatico.ca";		 
			document.form0.Email.value 		= "nscn@sympatico.ca"; 			
		}	
		
 		document.form0.bcc.value = "pc@twistedpixel.com";			 	 	
 		sTrans = spaceTrim(document.form0.TransNo.value);  //* It's a hidden field on the cc payment form
 	  	sSubject = "MR RIDER B " + sTrans;
 
 //* These will be encrypted - dupes of clear text fields.
//	 	document.form0.theTransNo.value = theTrans;
//	 	document.form0.thePrice.value 	= thePrice;
//	  	document.form0.theTax.value 	= theTax;
//		document.form0.theTotal_Cost.value = theTotal; 
//		document.form0.theEmail.value 	= theEmail;	 
  	
	  	document.form0.subject.value = sSubject; 	
//		document.form0.good_url.value = thesite + test + "/en/riders-confirm.asp";
//		document.form0.good_url.value = thesite + test + "/en/riders-confirm-rider.asp";
		document.form0.good_url.value = thesite + test + "/en/riders-payment-confirm.asp"; // 2010-05-02 new routine
//		document.form0.bad_url.value = thesite + test + "/mailer/fmbadhandler.php ";
// 		document.form0.action = thesiteSSL + "/mailer/formmail.php"; 
 		document.form0.action = thesiteSSL + "/formmail.php";  	
//	  	document.form0.enctype = "multipart/form-data";      //* For attachments
  		document.form0.method = "POST";
	  	document.form0.submit()
 		return(0); 	
   }  
}

function doContact ( form ) {	
//******************************************************************************* 
//  CONTACT US FORM - FORMMAIL.PHP 
//******************************************************************************* 
	var firstmessage="Please provide the following valid information:\n\n ";
	var errormessage="";
	var errorcode=0; 
	var len;
	var testFlag = 0;  // set to 1 if Comments = "xx", 2 if "test" - bypass validation.
 
 	if (spaceTrim(document.form0.Name.value) == "") errormessage=errormessage + "Name\n";
 	if (spaceTrim(document.form0.Telephone.value) == "") errormessage=errormessage + "Telephone\n";
	if (document.form0.Email.value.length ==0 || document.form0.Email.value.indexOf('@', 0) == -1 || document.form0.Email.value.indexOf('.', 0) == -1) {errormessage=errormessage+"Email address\n"} 
 
if (spaceTrim(document.form0.Comments.value) == "") errormessage=errormessage + "Comment or question\n";
 
//  	errormessage ="";  // Uncomment to deactivate validation for Testing

//* If comments start with xx, set testFlag on - for developer testing 
	var sComments = spaceTrim(document.form0.Comments.value);
	if (sComments.substring(0,2) == "xx") {errormessage=""; testFlag = 1;}
	if (sComments.substring(0,4) == "zz") {errormessage=""; testFlag = 2;} 	

	if (errormessage !="") { alert (firstmessage + errormessage) ;}
	else { 	
 	
 		var sEmailto = "service@motorescue.ca";			// Default receipient 		
 	  	document.form0.recipients.value = sEmailto;
		
		if (testFlag == 1) {
			document.form0.recipients.value = "pc@twistedpixel.com";
			document.form0.Email.value 		= "pc@twistedpixel.com"; 
		}
		if (testFlag == 2) {
			document.form0.recipients.value = document.form0.Email.value;
		}		
		
 		document.form0.bcc.value = "pc@twistedpixel.com";			 	 	

		document.form0.email.value = document.form0.Email.value;
		//* Email field is blank so set from email (formmail "from" var) to default recipient
		if (spaceTrim(document.form0.Email.value) == "") {
			document.form0.email.value = sEmailto;
		} 
 	  		  	
 	  	sSubject = "MOTORESCUE - CONTACT US";
 	  	
	  	document.form0.subject.value = sSubject;
 	
		document.form0.good_url.value = thesite + test + "/en/contact-confirm.asp";
//		document.form0.bad_url.value = thesite + test + "/mailer/fmbadhandler.php ";
 		document.form0.action = thesite + "/mailer/formmail.php";  	
//	  	document.form0.enctype = "multipart/form-data";      //* For attachments
  		document.form0.method = "POST";
	  	document.form0.submit()
 		return(0); 	
   }  
}

 
function checkString (strng) {
//******************************************************************************* 
//  Check string for invalid chars.      Do not use these chararacters: ~`\"|$%^\\
//******************************************************************************* 
// 	var illegalChars = /\W/;    // allow only letters, numbers, and underscores
//	var illegalChars = /[^~`"|]/g;    // allow only letters, numbers, and underscores
//  var illegalChars = /[^0-9a-zA-Z]/
//	var illegalChars = /[|!@#$%&*]/
	
	var error = false;
//	var illegalChars = /[|!@#$%^*\\]/; // Don't allow any of these
	var illegalChars = /[~`""|$%^\\]/;
	error = (illegalChars.test(strng));
	return error;
}

function dealerLogin (form){

//******************************************************************************* 
//  Validate Dealer Login form      Do not use these chararacters: ~`\"|$%^\\
//******************************************************************************* 
	var firstmessage="Please provide the following valid information:\n_____________________________________________\n\n ";
	var errormessage="";
	var msg2 = "";
	var fieldisblank=true;						

	var sDealerID = spaceTrim(document.form0.DealerID.value);
 	if (checkString(sDealerID) == true || sDealerID == "" || sDealerID.length != 8 ) errormessage=errormessage + "Dealer ID\n";
 
	
//*** PASSWORD 
    fieldisblank=true
    for (j=0; j < document.form0.Password.value.length; j++) 
    {
      if (document.form0.Password.value.substring(j,j+1) !=" ") {fieldisblank=false}
    }
    if (document.form0.Password.value.length < 4 || fieldisblank)
      	{errormessage=errormessage+" Password\n"}	

//	errormessage = "";   // Uncomment to deactivate the validation for testing
 

   if (errormessage !="") { alert (firstmessage + errormessage); }
   else {   
  	document.form0.action = "dealers-login-data.asp"; 
    document.form0.method = "POST";
  	document.form0.submit();
 	return(0);  
   }
	
}

//////////////////////////////////////////////////////////////////////////////////////////
//  GENERAL FUNCTIONS  
//////////////////////////////////////////////////////////////////////////////////////////

//******************************************************************************* 
// COUNT CHARS IN A STRING
// Use it like this
// test = 'one,two,three,four'
// commas = test.count(',') // returns 3
//******************************************************************************* 
String.prototype.count=function(s1) { 
    return (this.length - this.replace(new RegExp(s1,"g"), '').length) / s1.length;
}

function countInstances(string, word) {
//*----------------------------------------------
//* Count words or chars in a string. eg. nDotCount =  countInstances(sWebsite, ".")
//*---------------------------------------------- 
  var substrings = string.split(word);
  return substrings.length - 1;
}

//*----------------------------------------------
//* Show and Hide 
//*---------------------------------------------- 
function show_hide(sh1,hi1,hi2,com) 
{
 	document.getElementById(hi1).style.display='none';
	document.getElementById(hi2).style.display='none';
	
	obj=document.getElementById(sh1)
	obj.style.display == "block" ? obj.style.display = "none" : obj.style.display = "block"; 
	
//	alert(obj.style.display);

//* Display common stuff (name, comments, etc. plus submit button
	x=document.getElementById(com)
	if (obj.style.display=="block"){	
		x.style.display = "block";
	}	
	else {
		x.style.display = "none";
	}	 
}

function flipImg(imgNam,imgTyp,onoff){
//*******************************************************************************
//	Do the mouse over image flipping.
//******************************************************************************* 		
  	if(document.images){ 	
 		document.images[imgNam].src=eval(imgTyp+onoff+'.src');
  	}
}
 
 function spaceTrim(InString) {
//*******************************************************************************
// Trim leading and trailing spaces of form input fields
//*******************************************************************************
	var LoopCtrl=true;
	while (LoopCtrl) {
		if (InString.indexOf("  ") != -1) {
			Temp = InString.substring(0, InString.indexOf("  "))
			InString = Temp + InString.substring(InString.indexOf("  ")+1, 
				InString.length)
		} else
			LoopCtrl = false;
	}
	if (InString.substring(0, 1) == " ")
		InString = InString.substring(1, InString.length)
	if (InString.substring (InString.length-1) == " ")
		InString = InString.substring(0, InString.length-1)
	return (InString)
}

function setCookie(name, value, expires, path, domain, secure) {
//*******************************************************************************
// Generic rtn to set a cookie.
//*******************************************************************************
       var curCookie = name + "=" + escape(value) +
           ((expires) ? "; expires=" + expires.toGMTString() : "") +
           ((path) ? "; path=" + path : "") +
           ((domain) ? "; domain=" + domain : "") +
           ((secure) ? "; secure" : "");
       document.cookie = curCookie;
}
 
function getCookie(name) {
//*******************************************************************************
// Get a cookie.
//*******************************************************************************	
       var dc = document.cookie;
       var prefix = name + "=";
       var begin = dc.indexOf("; " + prefix);
       if (begin == -1) {
         begin = dc.indexOf(prefix);
         if (begin != 0) return null;
       } else
         begin += 2;
       var end = document.cookie.indexOf(";", begin);
       if (end == -1)
         end = dc.length;
       return unescape(dc.substring(begin + prefix.length, end));
     } 
     
function doClear ( form ) {	
//*******************************************************************************
// Clear Form  -  
//*******************************************************************************	
//alert(pagelang);
    var msg_e = "Are you sure that you want to clear all the data you have entered on this form?";
    var msg_f = "Voulez-vous vraiment effacer toutes les données?";
    var clearmsg = msg_e;
 // if (pagelang == "f") clearmsg = msg_f;
    
	var confirmOK = confirm(clearmsg);
  	if (confirmOK) document.form0.reset();    
}
  
function makeArray(){
    this.length = makeArray.arguments.length 
        for (var i = 0; i < this.length; i++)
        this[i + 1] = makeArray.arguments[i]
}

function randNum (num) {
    var now = new Date();                                  
    var rand = Math.round(num * Math.cos(now.getTime()));  
    if (rand < 0) rand = - rand; if (rand == 0) rand++;        
    return rand;                                           
}

function showAddr(part1, part2){
//*******************************************************************************
//	Display mailto link, hide from spam miners.
//*******************************************************************************
  if (part2 == undefined) part2 = "motorescue.ca";	
  var addr = part1 + "@" + part2;
  var result = ("<a href='" + "mail" + "to:" + addr + "'>" + addr + "</a>")
  return result;
} 

function NewWindow(mypage, myname, w, h, scroll)
{
var winl = (screen.width - w) / 2;
var wint = (screen.height - h) / 2;
winprops = 'height='+h+',width='+w+',top='+wint+',left='+winl+',scrollbars='+scroll+',resizable'
win = window.open(mypage, myname, winprops)
if (parseInt(navigator.appVersion) >= 4) { win.window.focus(); }
}   

function isCreditCardString (InString)  {
//*******************************************************************************
// Check if string is a number or spaces
//*******************************************************************************
	if(InString.length==0) 
		return (false);
	RefString="1234567890. ";
	for (Count=0; Count < InString.length; Count++)  {
		TempChar= InString.substring (Count, Count+1);
		if (RefString.indexOf (TempChar, 0)==-1)  
			return (false);
	}
	return (true);
}
 
function isInteger(s)
{   var i;
    for (i = 0; i < s.length; i++)
    {   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}
function isAlphabeticChar (InString)  {
	if(InString.length!=1) 
		return (false);
	InString=InString.toLowerCase ()
	RefString="abcdefghijklmnopqrstuvwxyz";
	if (RefString.indexOf (InString, 0)==-1) 
		return (false);
	return (true);
}

function isAlphabeticString (InString)  {
	if(InString.length==0)
		return (false);
	InString=InString.toLowerCase ()
	RefString="abcdefghijklmnopqrstuvwxyz";
	for (Count=0; Count < InString.length; Count++)  {
		TempChar= InString.substring(Count, Count+1);
		if (RefString.indexOf(TempChar, 0)==-1) 
			return (false);
	}
	return (true);
}

function formatDollar (Val, DollarSign)  {
//*******************************************************************************
// FORMAT DOLLAR
//*******************************************************************************	
	Val=""+Val;
	if (Val.indexOf (".", 0)!=-1) {
		Dollars = Val.substring(0, Val.indexOf (".", 0));
		Cents = Val.substring(Val.indexOf (".", 0)+1, Val.indexOf (".", 0)+3);
		if (Cents.length==0) 
			Cents="00";
		if (Cents.length==1)
			Cents=Cents+"0";
	} else {
		Dollars = Val;
		Cents = "00";
	}
	OutString="";
	len=Dollars.length;
	if (len>=3) {
		while (len>0) {
			TempString=Dollars.substring(len-3, len)
			if (TempString.length==3) {
				OutString=","+TempString+OutString
				len=len-3;
			} else {
				OutString=TempString+OutString
				len=0
			}
		}
		if (OutString.substring(0, 1)==",") 
			Dollars=OutString.substring (1, OutString.length)
		else
			Dollars=OutString
	} 
	if (DollarSign)
		return ("$"+Dollars+"."+Cents);
	else
		return (Dollars+"."+Cents);
}

//****************************************************************
//* Return a random upper case letter.
//****************************************************************
function createRandomUpperCaseLetter()
{
   return String.fromCharCode(65 + Math.round(Math.random() * 25));
}
//****************************************************************
//* Return a random lower case letter.
//****************************************************************
function createRandomLowerCaseLetter()
{
   return String.fromCharCode(97 + Math.round(Math.random() * 25));
}

function randomLetter() 
// Returns: a random character from the string 
{  
	str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    return str.charAt(randomInt(0, str.length-1)); 
}

//////////////////////////////////////////////////////////////////////
// File:   random.js 
// Author: Dave Reed 
// Date:   1/10/02
// http://www.dave-reed.com/Nifty/randSeq.html 
// This file contains several routines for generating random values 
////////////////////////////////////////////////////////////////////////  

function randomNum(low, high) 
// Given   : low <= high 
// Returns : a random number in the range [low, high) 
{ 
    return Math.random()*(high-low) + low; 
}  

function randomInt(low, high) 
// Given   : low <= high 
// Returns : a random integer in the range [low, high] 
{ 
    return Math.floor(Math.random()*(high-low+1)) + low; 
}  

function randomChar(str) 
// Given  : str is a nonempty string 
// Returns: a random character from the string 
{  
    return str.charAt(randomInt(0, str.length-1)); 
}  

function randomOneOf(list) 
// Given  : list is a nonempty list (array) 
// Returns: a random item from the list 
{    
    return list[randomInt(0, list.length-1)]; 
} 

function generateRandSeq(len, letters)
  // Assumes: len >= 0
  // Returns: random sequence of letters, length len
  {
      var i, seq = "";
      for (i = 1; i <= len; i = i + 1) {
          seq += randomChar(letters);
      }
      return seq;
  }

//*******************************************************************************************
/*
	Date Format 1.1
	(c) 2007 Steven Levithan <stevenlevithan.com>
	MIT license
	With code by Scott Trenda (Z and o flags, and enhanced brevity)
	http://blog.stevenlevithan.com/archives/date-time-format
*/

/*** dateFormat
	Accepts a date, a mask, or a date and a mask.
	Returns a formatted version of the given date.
	The date defaults to the current date/time.
	The mask defaults ``"ddd mmm d yyyy HH:MM:ss"``.
*/
var dateFormat = function () {
	var	token        = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloZ]|"[^"]*"|'[^']*'/g,
		timezone     = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
		timezoneClip = /[^-+\dA-Z]/g,
		pad = function (value, length) {
			value = String(value);
			length = parseInt(length) || 2;
			while (value.length < length)
				value = "0" + value;
			return value;
		};

	// Regexes and supporting functions are cached through closure
	return function (date, mask) {
		// Treat the first argument as a mask if it doesn't contain any numbers
		if (
			arguments.length == 1 &&
			(typeof date == "string" || date instanceof String) &&
			!/\d/.test(date)
		) {
			mask = date;
			date = undefined;
		}

		date = date ? new Date(date) : new Date();
		if (isNaN(date))
			throw "invalid date";

		var dF = dateFormat;
		mask   = String(dF.masks[mask] || mask || dF.masks["default"]);

		var	d = date.getDate(),
			D = date.getDay(),
			m = date.getMonth(),
			y = date.getFullYear(),
			H = date.getHours(),
			M = date.getMinutes(),
			s = date.getSeconds(),
			L = date.getMilliseconds(),
			o = date.getTimezoneOffset(),
			flags = {
				d:    d,
				dd:   pad(d),
				ddd:  dF.i18n.dayNames[D],
				dddd: dF.i18n.dayNames[D + 7],
				m:    m + 1,
				mm:   pad(m + 1),
				mmm:  dF.i18n.monthNames[m],
				mmmm: dF.i18n.monthNames[m + 12],
				yy:   String(y).slice(2),
				yyyy: y,
				h:    H % 12 || 12,
				hh:   pad(H % 12 || 12),
				H:    H,
				HH:   pad(H),
				M:    M,
				MM:   pad(M),
				s:    s,
				ss:   pad(s),
				l:    pad(L, 3),
				L:    pad(L > 99 ? Math.round(L / 10) : L),
				t:    H < 12 ? "a"  : "p",
				tt:   H < 12 ? "am" : "pm",
				T:    H < 12 ? "A"  : "P",
				TT:   H < 12 ? "AM" : "PM",
				Z:    (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
				o:    (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4)
			};

		return mask.replace(token, function ($0) {
			return ($0 in flags) ? flags[$0] : $0.slice(1, $0.length - 1);
		});
	};
}();

// Some common format strings
dateFormat.masks = {
	"default":       "ddd mmm d yyyy HH:MM:ss",
	shortDate:       "m/d/yy",
	mediumDate:      "mmm d, yyyy",
	longDate:        "mmmm d, yyyy",
	fullDate:        "dddd, mmmm d, yyyy",
	shortTime:       "h:MM TT",
	mediumTime:      "h:MM:ss TT",
	longTime:        "h:MM:ss TT Z",
	isoDate:         "yyyy-mm-dd",
	isoTime:         "HH:MM:ss",
	isoDateTime:     "yyyy-mm-dd'T'HH:MM:ss",
	isoFullDateTime: "yyyy-mm-dd'T'HH:MM:ss.lo"
};

// Internationalization strings
dateFormat.i18n = {
	dayNames: [
		"Sun", "Mon", "Tue", "Wed", "Thr", "Fri", "Sat",
		"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
	],
	monthNames: [
		"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
		"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
	]
};

// For convenience...
Date.prototype.format = function (mask) {
	return dateFormat(this, mask);
}


