
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: "VI", // VISA 
               length: "13,16", 
               prefixes: "4",
               checkdigit: true};
  cards [1] = {name: "MC",  //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: "AM",  // American Express
               length: "15", 
               prefixes: "34,37",
               checkdigit: true};
  cards [5] = {name: "Discover", 
               length: "16", 
               prefixes: "6011,650",
               checkdigit: true};
  cards [6] = {name: "JB", //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,18", 
               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; 
  }
    
  // Now remove any spaces from the credit card number
  cardnumber = cardnumber.replace (/\s/g, "");
  
  // Check that the number is numeric
  var cardNo = cardnumber
  var cardexp = /^[0-9]{13,19}$/;
  if (!cardexp.exec(cardNo))  {
     ccErrorNo = 2;
     return false; 
  }
       
  // 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 noSelection(elem, helperMsg){
	if(elem.value == ""){
		alert(helperMsg);
		elem.focus();
		return true;
	}else{
		return false;
	}
}

function isEmpty(elem, helperMsg){
	if (elem)
	{
		if(elem.value.length == 0){
			alert(helperMsg);
			elem.focus(); // set the focus to this input
			return true;
		}
	} else alert ("NULL for " + helperMsg);
	return false;
}

function validate_initiate_plan()
{
	var cctype = document.getElementById('cc_type');
	var cc_num = document.getElementById('cc_num');
	var cc_yy =  document.getElementById('cc_yy');
	var cc_mm  =  document.getElementById('cc_mm');
	var cc_cvv2 = document.getElementById('cvv2');

	if (isEmpty(document.getElementById('first_name'),"Please enter your firstname...")) return false;
	if (isEmpty(document.getElementById('last_name'),"Please enter your lastname...")) return false;
	if (isEmpty(document.getElementById('address'),"Please enter your address...")) return false;
	if (isEmpty(document.getElementById('city'),"Please enter your city..."))	 return false;
	
	if (noSelection(document.getElementById('province_code'),"Please enter the province for this address..."))	return false;	
	if (noSelection(document.getElementById('country_code'),"Please enter the country for this address..."))	return false;	
	if (isEmpty(document.getElementById('email_address'),"Please enter your e-mail address...")) return false;
    if (!emailValidator(document.getElementById('email_address'),"Please enter the correct e-mail address..."))	
	if (isEmpty(document.getElementById('pstn_phone'),"Please enter your phone number..."))		return false;	
	// cc
     
if (noSelection (cctype, 'Please select your card type')) return false;
if (!isNumeric(cc_num,'Please enter a valid credit card number')) return false;
if (!checkCreditCard (cc_num.value, cctype.value)) 
	{
		alert (ccErrors[ccErrorNo]);
		return false;
	}
if (!isNumeric(cc_mm,'Please enter a valid month')) return false;
if (!isNumeric(cc_yy,'Please enter a valid year')) return false;
if (!isNumeric(cc_cvv2,'Please enter a valid 3-digit CVV2 number at the back of your card')) return false;

	
	return true;
}

function emailValidator(elem, helperMsg){
	var emailExp = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,6}$/;
	if(elem.value.match(emailExp)){
		return true;
	}else{
		alert(helperMsg);
		elem.focus();
		return false;
	}
}
function validate(fieldV){
	
	var emailfilter = /^\w[\w\.\+]*\@\w+(\.\w+)*(\.[a-zA-Z]{2,4}){1,2}$/;
	
	var err_messages = "";
	var testpassed = true;
	switch(fieldV.attr("type")){
		case 'text':
		case 'password':
			switch(fieldV.attr("name")){
				case 'email':
				case 'email_address':
					if(!emailfilter.test(fieldV.val())){
						err_messages += "Not valid email.";
						testpassed= false;
					}
					break;
				case 'confirm_password':
				case 'confirm_pass':
					var pass = $('input.required[@name^=pass]');
				
					if((pass.length > 0) && (pass.val() != fieldV.val())){
						err_messages += "Password and Confirmation don't match.";
						testpassed= false;
					}
					break;
				case 'password':
				case 'pass':
				
					if(fieldV.val().length < 6){
						err_messages += "Password must be at least 6 characters long.";
						testpassed= false;
					}
					break;
			}
				// For all text or passwords
				if((fieldV.val().length == 0) ||(fieldV.val() == null )){
					err_messages += "Cannot be empty.";
					testpassed= false;
				}
			break;
			
		case 'checkbox':
			switch(fieldV.attr("name")){
				case 'e911_terms':
				case 'terms_and_conditions':
					if((!fieldV.attr('checked'))){
						err_messages += "You Must Agree To Continue.";
						testpassed= false;
					}
					break;
				default:
					if((!fieldV.attr('checked'))){
						err_messages += "You Must Check To Continue.";
						testpassed= false;
					}
					break;
			}
			break;
		case 'radio':
			one_sel = false;
			$("input.required[@name=" + fieldV.attr("name")+ "]").each( function(){
				one_sel = (one_sel || this.checked);
			});
			if(!one_sel){
				err_messages += "You Must Choose One.";
				testpassed= false;
			}
			break;
	}
	
	
	// Write the error message after the failed field
	writeMessage(fieldV, err_messages);
	
	return testpassed;
}

function writeMessage(fieldV, err_messages){
	if($("#_" + fieldV.attr("name") + '_ems').length > 0){
		$("#_" + fieldV.attr("name") + '_ems').text(err_messages);
	} else {
		if(err_messages.length > 0){
			fieldV.after(
					"<span id='_" + fieldV.attr("name") + "_ems' "
						+"class='message' >"
						+ err_messages
						+ "</span>"
			);
		};
	};
	
};

function validate_required(){
	$("input.required").bind( "blur", function(){
		validate($(this));
	});

	$("input.dependent").each( function(){
		var dep = $(this);
		var depe = $(this).siblings("input[@type='checkbox'].dependee");
	//	depe.add("input[@type='radio'].dependee");
		
		depe.each( function(){
			$(this).click( 
				function(){
					dep.attr("disabled", !(dep.attr("disabled")));
					dep.toggleClass('required');
					writeMessage(dep, "")
				});
		});
	});

	$("form").bind("submit", function(){
		all_valid = true;
		$("input.required", $(this)).each( function(){
			field_validated = validate($(this));
			all_valid = (field_validated && all_valid);
		});
		return all_valid;
	});
	
}

$.fn.check = function(mode) {
	var mode = mode || 'toggle'; // if mode is undefined, use 'toggle' as default
	return this.each(function() {
		switch(mode) {
		case 'on':
			this.checked = true;
			break;
		case 'off':
			this.checked = false;
			break;
		case 'toggle':
			this.checked = !this.checked;
			break;
		}
	});
};


function createPopups(){
	$("a.popup").each( function(){
		var linkto = $(this).attr('href');
		$(this).click( function(){
			window.open(linkto);
			return false;
		});
	});
}

function ActivateHandlers(){
	$("a.handler").each( function(){
		var linkto = $(this).attr('href');
		$(this).click( function(){
			$(linkto).removeClass('closed');
			$(linkto).addClass('open');
			return false;
		});
	});
}

