var CHECKSUM  = 0;
var ALLVALID  = 511;
var HASFNAME  = 1;
var HASSNAME  = 2;
var EMAILOK   = 4;
var PASSOK    = 8;
var PASSMATCH = 16;
var LEGALOK   = 32;
var CCNUMOK   = 64;
var HASEXPDT  = 128;
var HASCVV    = 256;
		

// TURN ON PASSWORD MATCHING (WHILE WE DON'T USE PASSWORDS)
//turnOn(PASSMATCH);


function zap(){
	turnOn(PASSMATCH);
	turnOn(PASSOK);

	var button = obtainElement('submit');
	if ((CHECKSUM & ALLVALID) == ALLVALID){
		button.disabled = false;
		button.src = "/images/greenOrder.png";
		return true;
		}
	else{
		button.disabled = true;
		button.src = "/images/redOrder.png";
		return false;
		}
}

function testall(){
	turnOn(PASSMATCH);
	turnOn(PASSOK);
	basicCCvalidate();
	validateExpDate();
	CVV2validate();
	validateFname();
	validateSname();
	validateEmail();
	passVer();
	getLegal();
	XvalidatePassword();
}

function turnOff(probe){
	if ((CHECKSUM & probe) == probe)
		CHECKSUM = CHECKSUM ^ probe;
}

function turnOn(probe){
	CHECKSUM = CHECKSUM | probe;
}


function obtainElement(eid){

    if (document.all) { //IS IE 4 or 5 (or 6 beta)
        var element = eval( "document.all." + eid);
    }
    if (document.layers) { //IS NETSCAPE 4 or below
        var element = document.layers[eid];
    }
    if (document.getElementById &&!document.all) {
        var element = document.getElementById(eid);
    }
    return element;
}

function CVV2validate(){
	var cvvfiled = obtainElement("CVV");
	var cvvnum   = cvvfiled.value;

	if (cvvnum.length < 3){
		turnOff(HASCVV);
        	obtainElement("cvv2Alert").innerHTML = '<img src="/images/redX16.gif" alt=":-("/>';	
		zap();
		}
	else {
		turnOn(HASCVV);
    		obtainElement("cvv2Alert").innerHTML = '<img src="/images/greenOK16.gif" alt=":-)"/>';
		zap();
		}
}

function basicCCvalidate(){
	var ccfield  = obtainElement("ccno");
	var ccnumber = ccfield.value;

	var result = validateCreditCard(ccnumber);
	if (result == false){
		turnOff(CCNUMOK);
		obtainElement("ccnumberAlert").innerHTML = '<img src="/images/redX16.gif" alt=":-("/>';
		obtainElement("cctypeInform").innerHTML ='&nbsp;';
		zap();
		}
	else{
		switch(result){
			case 'AX':
			case 'DI':
			case 'CB':		
			case 'ER':
			case 'JC':
				alert("We are so sorry for the inconvenience. We can only accept Visa, Mastercard or Diners Club Credit cards.");
				turnOff(CCNUMOK);
				obtainElement("ccnumberAlert").innerHTML = '<img src="/images/redX16.gif" alt=":-("/>';
				obtainElement("cctypeInform").innerHTML ='&nbsp;';
				zap();
				return;
				break;
			case 'VI':
				obtainElement("cctypeInform").innerHTML = '<img src="/images/VisaOK.png" alt="Visa"/>';
				break;
			case 'MC':
				obtainElement("cctypeInform").innerHTML = '<img src="/images/MC_OK.png" alt="Mastercard"/>';
				break;
			case 'DC':
				obtainElement("cctypeInform").innerHTML = '<img src="/images/Diners_OK.png" alt="Diners Club"/>';
				break;
			}
		turnOn(CCNUMOK);
		obtainElement("ccnumberAlert").innerHTML = '<img src="/images/greenOK16.gif" alt=":-)"/>';
		zap();
	}
}

function validateExpDate(){
	var expMonth = obtainElement("expmonth").value;
	var expYear = obtainElement("expyear").value;
	if ((expMonth != '00') && (expYear != '00')){
		turnOn(HASEXPDT);
		obtainElement("expdateAlert").innerHTML = '<img src="/images/greenOK16.gif" alt=":-)"/>';
		zap();
	}
	else{
		turnOff(HASEXPDT);
		obtainElement("expdateAlert").innerHTML = '<img src="/images/redX16.gif" alt=":-("/>';
		zap();
	}

}


function validateFname(){
	var fname = obtainElement("firstname").value;
	//console.info("fname %s",fname);
	if (fname.length < 3){
		turnOff(HASFNAME);
        	obtainElement("firstnameAlert").innerHTML = '<img src="/images/redX16.gif" alt=":-("/>';	
		zap();
		}
	else {
		turnOn(HASFNAME);
    		obtainElement("firstnameAlert").innerHTML = '<img src="/images/greenOK16.gif" alt=":-)"/>';
		zap();
		}
}

function validateSname(){
	var sname = obtainElement("surname").value;
	if (sname.length < 3){
		turnOff(HASSNAME);
        	obtainElement("surnameAlert").innerHTML = '<img src="/images/redX16.gif" alt=":-("/>';		
		zap();
		}
	else {
		turnOn(HASSNAME);
    		obtainElement("surnameAlert").innerHTML = '<img src="/images/greenOK16.gif" alt=":-)"/>';
		zap();
		}
}

function validateEmail(){
    // Regular expression for checking email addresses.
    var emailfilter = /^\w+[\+\.\w-]*@([\w-]+\.)*\w+[\w-]*\.([a-z]{2,4}|\d+)$/i;
    var mailElement = obtainElement("email");
    var email       = mailElement.value;

    if (emailfilter.test(email)==false){
        obtainElement("emailAlert").innerHTML = '<img src="/images/redX16.gif" alt=":-("/>';
	//mailElement.select();
	turnOff(EMAILOK);
	zap();
    	}
    else {
    	obtainElement("emailAlert").innerHTML = '<img src="/images/greenOK16.gif" alt=":-)"/>';
	turnOn(EMAILOK);
	zap();
    	}
}


function passVer(){
	var pass  = obtainElement("passwd").value;
	var passV = obtainElement("passwordV").value;
	if ((pass != passV)|(pass == '')|(passV=='')){
		obtainElement("passMatch").innerHTML = '<img src="/images/redX16.gif" alt=":-("/>';
		turnOff(PASSMATCH);
		zap();
		}
	else{
		obtainElement("passMatch").innerHTML = '<img src="/images/greenOK16.gif" alt=":-("/>';
		turnOn(PASSMATCH);
		zap();
		}
}


function getLegal(){
    var lcheck = obtainElement('legalConsent');
    var cdiv  = obtainElement('legalBG');
    if (lcheck.checked){
	cdiv.style.background = 'green';
	cdiv.style.border = '2px solid green';
	turnOn(LEGALOK);
	zap();
        }
    else{
     	cdiv.style.background = 'red';
	cdiv.style.border = '2px solid red';
	turnOff(LEGALOK);
	zap();
        }
}


function XvalidatePassword() {
	var strength    = obtainElement('strength');
	var pwd         = obtainElement('passwd');
	var strongRegex = new RegExp("^(?=.{8,})(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*\\W).*$", "g");
	var mediumRegex = new RegExp("^(?=.{7,})(((?=.*[A-Z])(?=.*[a-z]))|((?=.*[A-Z])(?=.*[0-9]))|((?=.*[a-z])(?=.*[0-9]))).*$", "g");
	var enoughRegex = new RegExp("(?=.{6,}).*", "g");

	if (pwd.value.length==0) {
		strength.style.backgroundPosition = '0 0px';
		turnOff(PASSOK);
		} 
	else if (false == enoughRegex.test(pwd.value)) {
		strength.style.backgroundPosition = '0 -0px';
		turnOff(PASSOK);
		} 
	else if (strongRegex.test(pwd.value)) {
		strength.style.backgroundPosition = '0 -75px';
		turnOn(PASSOK);
		} 
	else if (mediumRegex.test(pwd.value)) {
		strength.style.backgroundPosition = '0 -50px';
		turnOn(PASSOK);
		} 
	else {
		strength.style.backgroundPosition = '0 -25px';
		turnOn(PASSOK);
		}
	passVer();
	zap();
}


// Gratitude to perkiset from http://www.perkiset.org for
// posting this piece of code. Very helpful indeed. THANKS!!!
function validateCreditCard(workStr)
{
	workStr = workStr.replace(/\.|\-| /g, '');
	if (!workStr.match(/^[0-9]{13,16}$/)) { return false; }
	var chars = new Array();
	var len = workStr.length;
	for (var i=len-1; i>=0; i--) { chars[(len - 1) - i] = workStr.charAt(i); }
	
	var checkVal = 0;
	for (var i=0; i<len; i++)
	{
		if ((i + 1) % 2) { checkVal += (chars[i] - 0); } 
		else {
			var thisVal = chars[i] * 2;
			if (thisVal <= 9) { checkVal += (thisVal - 0); }
			if (thisVal >= 10) { checkVal += (thisVal - 9); }
		}
	}
	if (checkVal % 10) { return false; }
	
	var chars1 = workStr.charAt(0);
	var chars2 = workStr.substr(0, 2);
	var chars3 = workStr.substr(0, 3);
	var chars4 = workStr.substr(0, 4);
	
	if ( (chars1 == '4') && ((len == 16) || (len == 13)) ) { return 'VI'; } // Visa
	if ( (len == 16) && (chars2 >= '51') && (chars2 <= '55')) { return 'MC'; } // MasterCard
	if ( (len == 15) && ((chars2 == '34') || (chars2 == '37')) ) { return 'AX'; } // AmEx
	if ( (chars4 == '6011') && (len == 16) ) { return 'DI'; } // Discover
	if ( (((chars3 >= '300') && (chars3 <= 305)) || (chars2 == '36')) && (len == 14) ) { return 'DC'; } // Diners Club
	if ( (chars2 == '38') && (len == 14) ) { return 'CB'; } // Carte Blanche
	if ( ((chars4 == '2014') || (chars4 == '2149')) && (len == 15) ) { return 'ER'; } // En Route
	if ( ((chars4 == '2131') || (chars4 == '1800')) && (len == 15) ) { return 'JC'; } // JCB
	if ( (chars1 == '3') && (len == 16) ) { return 'JC'; } // JCB Also
	return false;
}

// Accept only digits in a digit oriented field (mainly credit card numbers)

function onlyDigits(field){
	var str = /[^\d]/g;
	field.value = field.value.replace(str,'');
}


