/*************
Validation for Signup Forms
*************/

// getting contact values in billing info

// Checking Market and MLS ID //
/*
function chkfields()
{
if (document.frm.market_id.value == '')
	{
		alert('Please Select The Market')
		document.frm.market_id.focus()
		}
	else if
		(document.frm.mls_id.value == '')
	{
		alert('Please Select The MLS/Public ID')
		document.frm.mls_id.focus()
		}		
	else	
		document.frm.submit()
}
*/


//////////////Startstep 1 signup//////////////

function checkSignupOne(frm){

	var mlsidchk, mkidchk

	mlsidchk = chkMLS(frm.mls_id.value)
	mkidchk = check_MktID(frm.market_id)
	

	if ( (mlsidchk == true) && (mkidchk == true) ){
		//alert('submitting')
		frm.submit()
	}
}


function chkMLS(alphane)
{
	if ( alphane.length == 0 ){
		alert('Please Enter Your MLS/Public ID')
		return false
	}
	var numaric = alphane;
	for(var j=0; j<numaric.length; j++)
		{
		  var alphaa = numaric.charAt(j);
		  var hh = alphaa.charCodeAt(0);
		  if((hh > 47 && hh<59) || (hh > 64 && hh<91) || (hh > 96 && hh<123))
		  {
		  }
		else	{
			alert('MLS / Public ID has invalid characters')
			 return false;
		  }
		}
 return true;
}


function check_MktID(e){

	if ( e.selectedIndex > 0){
	return true	
	}
	else{
		alert('Please Select Your Market/MLS')
		return false
	}
}

//////////////END step 1 //////////////



//////////////Startstep 2 signup//////////////

function checkSignupTwo(frm){
	var ccName
		if (frm.CardType.value == 'VS')
		 ccName = "Visa"
		if (frm.CardType.value == 'MC')
		 ccName = "MasterCard"
		if (frm.CardType.value == 'AE')
		 ccName = "AmEx"


	var tchk, i
	i=0
	//alert(frm.fillBillInfo.checked)
	
	if (frm.in_agree.checked == true){

		tchk = isNotNull(frm.NameOnCard_FirstName, "First Name")
		if ( tchk == true )i++;

		tchk = isNotNull(frm.NameOnCard_LastName, "Last Name")
		if ( tchk == true )i++;
		
		tchk = checkEmail(frm.Email)
		if ( tchk == true )i++;

		tchk = isNotNull(frm.BillingAddress1, "Billing Address")
		if ( tchk == true )i++;
		
		tchk = isNotNull(frm.BillingAddress2, "Billing Address")
		if ( tchk == true )i++;
		
		tchk = isNotNull(frm.BillingCity, "Billing City")
		if ( tchk == true )i++;
		
		if ( frm.BillingState.value != null )i++;

		if ( frm.BillingCountry.value != null)i++;

		
		tchk = isNotNull(frm.BillingZip_Code, "Billing Zip Code")
		if ( tchk == true )i++;

		tchk = isNotNull(frm.BillingPhone, "Billing Phone")
		if ( tchk == true )i++;
		
		tchk = isNotNull(frm.CardNumber, "Credit Card Number")
		if ( tchk == true )i++;

		tchk = isNotNull(frm.SiteSubDomain, "Sub Domain")
		if ( tchk == true )i++;	
		

		tchk = checkCreditCard(frm.CardNumber.value, ccName)
		if ( tchk == true )i++;	

		tchk = validateZIP(frm.BillingZip_Code.value)
		if ( tchk == true )i++;	
				
		
		if (i == 14 ){
			return true
		}
			else
				alert('Please Fill in the Required fields')

	}//end if in_agree
	else{
		alert('You must agree with our terms')
		frm.in_agree.className= "inputreq"
	}


}//end function checkSignupTwo



function isNotNull(e, capText){
	if (e.value.length  >  1){
		return true
	}
	else{
		//alert('Please Fill in the ' + capText)
		e.className= "inputreq"
		return false
	}
}



function validateZIP(field) {
var valid = "0123456789-";
var hyphencount = 0;

if (field.length!=5 && field.length!=10) {
alert("Please enter your 5 digit or 5 digit+4 zip code.");
return false;
}
for (var i=0; i < field.length; i++) {
temp = "" + field.substring(i, i+1);
if (temp == "-") hyphencount++;
if (valid.indexOf(temp) == "-1") {
alert("Invalid characters in your zip code.  Please try again.");
return false;
}
if ((hyphencount > 1) || ((field.length==10) && ""+field.charAt(5)!="-")) {
alert("The hyphen character should be used with a properly formatted 5 digit+four zip code, like '12345-6789'.   Please try again.");
return false;
   }
}
return true;
}



function checkEmail(e) {
	var emailStr = e.value
	var emailPat=/^(.+)@(.+)$/
	var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]"
	var validChars="\[^\\s" + specialChars + "\]"
	var quotedUser="(\"[^\"]*\")"
	var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/
	var atom=validChars + '+'
	var word="(" + atom + "|" + quotedUser + ")"
	var userPat=new RegExp("^" + word + "(\\." + word + ")*$")
	var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$")
	var matchArray=emailStr.match(emailPat)
	
	if (matchArray==null) {
		e.className= "inputreq"
		alert("Email address seems incorrect (check @ and .'s)")
		return false

	}

	var user=matchArray[1]
	var domain=matchArray[2]
	
	if (user.match(userPat)==null) {
	    alert("The username doesn't seem to be valid.")
		e.className= "inputreq"
	    return false
	}
	
	
	var IPArray=domain.match(ipDomainPat)
	
	if (IPArray!=null) {
		  for (var i=1;i<=4;i++) {
		    if (IPArray[i]>255) {
		        alert("Destination IP address is invalid!")
		e.className= "inputreq"
			return false
		    }
	    }
	    return true
	}
	
	
	var domainArray=domain.match(domainPat)
	
	if (domainArray==null) {
		alert("The domain name doesn't seem to be valid.")
		e.className= "inputreq"
	    return false
	}
	
	var atomPat=new RegExp(atom,"g")
	var domArr=domain.match(atomPat)
	var len=domArr.length
	
	if (domArr[domArr.length-1].length<2 || 
	    domArr[domArr.length-1].length>3) {

	   alert("The address must end in a three-letter domain, or two letter country.")
		e.className= "inputreq"
	   return false
	}

	if (len<2) {
	   var errStr="This address is missing a hostname!"
	   alert(errStr)
		e.className= "inputreq"
	   return false
	}

		return true;
}//end checkemail




//>>Start CC info

/*============================================================================*/

/*

This routine checks the credit card number. The following checks are made:

1. A number has been provided
2. The number is a right length for the card
3. The number has an appropriate prefix for the card
4. The number has a valid modulus 10 number check digit if required

If the validation fails an error is reported.

The structure of credit card formats was gleaned from a variety of sources on 
the web, although the best is probably on Wikepedia ("Credit card number"):

  http://en.wikipedia.org/wiki/Credit_card_number

Parameters:
            cardnumber           number on the card
            cardname             name of card as defined in the card list below

Author:     John Gardner
Date:       1st November 2003
Updated:    26th Feb. 2005      Additional cards added by request
Updated:    27th Nov. 2006      Additional cards added from Wikipedia

*/

/*
   If a credit card number is invalid, an error reason is loaded into the 
   global ccErrorNo variable. This can be be used to index into the global error  
   string array to report the reason to the user if required:
   
   e.g. if (!checkCreditCard (number, name) alert (ccErrors(ccErrorNo);
*/

var ccErrorNo = 0;
var ccErrors = new Array ()

ccErrors [0] = "Unknown card type";
ccErrors [1] = "No card number provided";
ccErrors [2] = "Credit card number is in invalid format";
ccErrors [3] = "Credit card number is invalid";
ccErrors [4] = "Credit card number has an inappropriate number of digits";

function checkCreditCard (cardnumber, cardname) {

     
  // Array to hold the permitted card characteristics
  var cards = new Array();

  // Define the cards we support. You may add addtional card types.
  
  //  Name:      As in the selection box of the form - must be same as user's
  //  Length:    List of possible valid lengths of the card number for the card
  //  prefixes:  List of possible prefixes for the card
  //  checkdigit Boolean to say whether there is a check digit
  
  cards [0] = {name: "Visa", 
               length: "13,16", 
               prefixes: "4",
               checkdigit: true};
  cards [1] = {name: "MasterCard", 
               length: "16", 
               prefixes: "51,52,53,54,55",
               checkdigit: true};
  cards [2] = {name: "DinersClub", 
               length: "14,16", 
               prefixes: "300,301,302,303,304,305,36,38,55",
               checkdigit: true};
  cards [3] = {name: "CarteBlanche", 
               length: "14", 
               prefixes: "300,301,302,303,304,305,36,38",
               checkdigit: true};
  cards [4] = {name: "AmEx", 
               length: "15", 
               prefixes: "34,37",
               checkdigit: true};
  cards [5] = {name: "Discover", 
               length: "16", 
               prefixes: "6011,650",
               checkdigit: true};
  cards [6] = {name: "JCB", 
               length: "15,16", 
               prefixes: "3,1800,2131",
               checkdigit: true};
  cards [7] = {name: "enRoute", 
               length: "15", 
               prefixes: "2014,2149",
               checkdigit: true};
  cards [8] = {name: "Solo", 
               length: "16,18,19", 
               prefixes: "6334, 6767",
               checkdigit: true};
  cards [9] = {name: "Switch", 
               length: "16,18,19", 
               prefixes: "4903,4905,4911,4936,564182,633110,6333,6759",
               checkdigit: true};
  cards [10] = {name: "Maestro", 
               length: "16", 
               prefixes: "5020,6",
               checkdigit: true};
  cards [11] = {name: "VisaElectron", 
               length: "16", 
               prefixes: "417500,4917,4913",
               checkdigit: true};
               
  // Establish card type
  var cardType = -1;
  for (var i=0; i<cards.length; i++) {

    // See if it is this card (ignoring the case of the string)
    if (cardname.toLowerCase () == cards[i].name.toLowerCase()) {
      cardType = i;
      break;
    }
  }
  
  // If card type not found, report an error
  if (cardType == -1) {
     ccErrorNo = 0;
     return false; 
  }
   
  // Ensure that the user has provided a credit card number
  if (cardnumber.length == 0)  {
     ccErrorNo = 1;
     return false; 
  }
  
  // Check that the number is numeric, although we do permit a space to occur  
  // every four digits. 
  var cardNo = cardnumber
  var cardexp = /^([0-9]{4})\s?([0-9]{4})\s?([0-9]{4})\s?([0-9]{1,4})$/;
  if (!cardexp.exec(cardNo))  {
     ccErrorNo = 2;
     return false; 
  }
    
  // Now remove any spaces from the credit card number
  cardexp.exec(cardNo);
  cardNo = RegExp.$1 + RegExp.$2 + RegExp.$3 + RegExp.$4;
       
  // Now check the modulus 10 check digit - if required
  if (cards[cardType].checkdigit) {
    var checksum = 0;                                  // running checksum total
    var mychar = "";                                   // next char to process
    var j = 1;                                         // takes value of 1 or 2
  
    // Process each digit one by one starting at the right
    var calc;
    for (i = cardNo.length - 1; i >= 0; i--) {
    
      // Extract the next digit and multiply by 1 or 2 on alternative digits.
      calc = Number(cardNo.charAt(i)) * j;
    
      // If the result is in two digits add 1 to the checksum total
      if (calc > 9) {
        checksum = checksum + 1;
        calc = calc - 10;
      }
    
      // Add the units element to the checksum total
      checksum = checksum + calc;
    
      // Switch the value of j
      if (j ==1) {j = 2} else {j = 1};
    } 
  
    // All done - if checksum is divisible by 10, it is a valid modulus 10.
    // If not, report an error.
    if (checksum % 10 != 0)  {
     ccErrorNo = 3;
     return false; 
    }
  }  

  // The following are the card-specific checks we undertake.
  var LengthValid = false;
  var PrefixValid = false; 
  var undefined; 

  // We use these for holding the valid lengths and prefixes of a card type
  var prefix = new Array ();
  var lengths = new Array ();
    
  // Load an array with the valid prefixes for this card
  prefix = cards[cardType].prefixes.split(",");
      
  // Now see if any of them match what we have in the card number
  for (i=0; i<prefix.length; i++) {
    var exp = new RegExp ("^" + prefix[i]);
    if (exp.test (cardNo)) PrefixValid = true;
  }
      
  // If it isn't a valid prefix there's no point at looking at the length
  if (!PrefixValid) {
     ccErrorNo = 3;
     return false; 
  }
    
  // See if the length is valid for this card
  lengths = cards[cardType].length.split(",");
  for (j=0; j<lengths.length; j++) {
    if (cardNo.length == lengths[j]) LengthValid = true;
  }
  
  // See if all is OK by seeing if the length was valid. We only check the 
  // length if all else was hunky dory.
  if (!LengthValid) {
     ccErrorNo = 4;
     return false; 
  };   
  
  // The credit card is in the required format.
  return true;
}


function chkPhone(v)
{
var ph=v.value.replace(/[^0-9]+/g,'');
v.value=ph.substring(0,3)+'-'+ph.substring(3,6)+'-'+ph.substring(6,15);
}

/*============================================================================*/

//end cc infor


//////////////END step 2 //////////////