/**
Mano form validator
Liran Oz
*/

function FormValidator(_objName, _formId)
{
	var objName = _objName;
	var formId = _formId;
	var items = new Array();
	var dateItems = new Array();
	var colBgGood = null;
	var colBgBad = null;
	var colBorderGood = null;
	var colBorderBad = null;
	var showError = true;
	var tMonth = 1;
	var tYear = 1;

	/*
	Set colors for the form validators
	*/
	this.setFormColors = function(_colBgGood, _colBgBad, _colBorderGood, _colBorderBad)
	{
		colBgGood = _colBgGood;
		colBgBad = _colBgBad;
		colBorderGood = _colBorderGood;
		colBorderBad = _colBorderBad;
	}
	/*
	display error box or not
	*/

	this.setShowError = function(st)
	{
		if (!st)
			showError = false;
		else
			showError = true;
	}

	/*
	set date for date comparison
	*/
	this.setDates = function(_month, _year)
	{
		tMonth = _month;
		tYear = _year;
	}

	/*
		To add item:
		<itemId>, <validationType>, <required>, <displayMessage>, <displayDependency>

		validationType:
		- string
		- number
		- phone
		- id number
		- credit card (mod 10)
		- cvv
		- email
		- checkbox
		- select
	*/
	this.addItem = function(itemId, validationType, required, msg, displayDependency)
	{
		var obj = document.getElementById(itemId);
		var dObj = null;
		if (displayDependency) {
			dObj = document.getElementById(displayDependency);
		}

		if (!obj)
			return false;

		items[items.length] = new Array(itemId, obj, validationType, required, msg, dObj);

		return true;
	}

	/*
	add date vs month validation, for select inputs
	*/
	this.addDateItem = function (mId, yId, errMsg, displayDependency)
	{
		var mObj = document.getElementById(mId);
		var yObj = document.getElementById(yId);

		var dObj = null;
		if (displayDependency)
			dObj = document.getElementById(displayDependency);

		if (!mObj || !yObj)
			return;

		dateItems[dateItems.length]	= new Array(mObj, yObj, errMsg, dObj);
	}

	function validateDateItem(idx)
	{
		if (idx >= dateItems.length || idx < 0)
			return false;
		var dObj = dateItems[idx][3];
		if (dObj) {
			if (dObj.style.display == 'none')
				return true;
		}

		var mObj = dateItems[idx][0];
		var yObj = dateItems[idx][1];
		var sm = parseInt(mObj.options[mObj.selectedIndex].value);
		var sy = parseInt(yObj.options[yObj.selectedIndex].value);

		if (sy <= tYear && sm < tMonth) {
			itemColorize(mObj, false);
			itemColorize(yObj, false);
			return false;
		}

		itemColorize(mObj, true);
		itemColorize(yObj, true);
		return true;
	}

	function validateItem(idx)
	{
		if (idx >= items.length || idx < 0)
			return false;
		//if it's dependent on div and div is closed it's always true
		var dObj = items[idx][5];
		if (dObj && dObj.style.display == "none")
			return true;

		var obj = items[idx][1];

		//if not required and empty then it's ok
		if (items[idx][3] == false) {
			if (items[idx][2] == 'select' || items[idx][2] == 'checkbox')
				return true;

			if (obj.value.length == 0)
				return true;
		}

		var text = null;
		if (items[idx][2] != 'checkbox' && items[idx][2] != 'select')
			text = obj.value;

		switch (items[idx][2]) {
			case 'string':
				if (text.match(/.+/))
					return true;
				return false;

			case 'phone':
			case 'number':
				if (text.match(/[^0-9]+/) || text.length == 0)
					return false;
				return true;

			case 'idNumber':
				var creditDiv = document.getElementById("crdPaySwitch");
				if(creditDiv.style.display == "none")
				{
					return true;
				}
				else
				{
				    return checkidnum(text);
				}

			case 'credit':
				if (text.match(/[^\d]+/g) )
					return false;
			var cardtype=document.getElementById("crd_type_crd");
				
			if(cardtype.value!="Isracard")	
			{
				//use mod10 function for visa not isracard
				var res = Mod10(text);
				if (res == false)
					return false;
			}
			
			if(cardtype.value=="Isracard")	
			{
				if (text.length >= 8)
					return true;
			}
			else
			{
				if (text.length == 16 || text.length == 15)
					return true;
			}
				return false;

			case 'cvv':
				if (text.match(/[^\d]+/g) ) {
					return false;
				}

				if (text.length == 3 || text.length == 4) {
					return true;
				}
				return false;

			case 'email':
				if (!text.match(/^[a-zA-Z0-9_\.-]+@[a-zA-Z0-9_-]+\.[a-zA-Z0-9_]+((\.[a-zA-Z0-9_]+)*)$/)) {
					return false;
				}
				return true;

			case 'checkbox':
				//if checkbox is validated it's must be set to true
				return obj.checked;

			case 'select':
				//-1 is the value for the text description
				if (obj.options[obj.selectedIndex].value == -1)
					return false;
				return true;
				
			case 'security':
			if (text.match(/.+/))
			{
				var url = "ajax_functions.php?action=get_session&session_name=security_code";
				var inputsecurity=document.getElementById("security_code");
				var xml = LoadXML(url);
				if(xml != null)
				{
					if (xml.getElementsByTagName('session_var')[0] && xml.getElementsByTagName('session_var')[0].firstChild && xml.getElementsByTagName('session_var')[0].firstChild.data)
					{
						security_code = xml.getElementsByTagName('session_var')[0].firstChild.data;
					}
					else
					{
						security_code = "";
					}
				}
				if (trim(inputsecurity.value) != security_code)
				{
					alert(_tb_security_mismatch);
					inputsecurity.focus();
					return false;
				}
				
			}
			else
			{
				return false;
			}
			return true;
		case 'password':
			if (text.match(/.+/))
			{
				var verpas=document.getElementById("passwordverify");
				var mainpas=document.getElementById("mainpassword");
				var illegalchars =/[\W_]/; // allow only letters and numbers
				if (illegalchars.test(mainpas.value))
				{
					alert( _alert_illegalchars);
					return false;
				}				
				if(verpas.value!=mainpas.value)
				{
					alert(_notsamepasword);
					return false;
				}
				else
				return true;
				
			}
			else
			{
				return false;
			}
			
			
			default:
				return false;
		}
	}

	function itemColorize(obj, ok)
	{
		if (!obj.style)
			return;

		if (ok) {
			if (colBgGood)
				obj.style.bgColor = colBgGood;
			if (colBorderGood)
				obj.style.borderColor = colBorderGood;
		}
		else {
			if (colBgBad)
				obj.style.bgColor = colBgBad;
			if (colBorderBad)
				obj.style.borderColor = colBorderBad;
		}
	}
	/*
	Validates the form, colorize the invalid item if colors are set, and set focus if possible
	*/
	this.validateForm = function()
	{
		var errorMsg = null;
		var ok = true;

		for (var i=0; i<items.length; i++) {
			var obj = items[i][1];

			if (!validateItem(i)) {
				if (ok) {
					ok = false;
					if (obj.focus)
						obj.focus();
				}

				if (errorMsg == null)
					errorMsg = items[i][4];

				//colorize
				itemColorize(obj, false);
			}
			else
				itemColorize(obj, true);
		}

		//date items validation
		for (var i=0; i<dateItems.length; i++) {
			var obj = dateItems[i][0];

			if (!validateDateItem(i)) {
				if (ok) {
					ok = false;
					if (obj.focus)
						obj.focus();
				}

				if (errorMsg == null)
					errorMsg = dateItems[i][2];
			}
		}


		if (!ok && showError) {
			alert(errorMsg);
		}

		return ok;
	}

	function checkidnum(idnum)
	{
	 // FUNCTION FOR VALIDATING ID NUMBER
	 //Addition - can only accept numbers! - Liran Oz
	 	//trim - if exists
	 	idnum = idnum.replace('-', '');

	 	if (idnum.match(/[^0-9]/))
	 		return false;



	    while (idnum.length<9)
	    {
	        idnum="0"+idnum;
	    }

	    idnum1=idnum.substr(0,1)*1;
	    idnum2=idnum.substr(1,1)*2;
	    idnum3=idnum.substr(2,1)*1;
	    idnum4=idnum.substr(3,1)*2;
	    idnum5=idnum.substr(4,1)*1;
	    idnum6=idnum.substr(5,1)*2;
	    idnum7=idnum.substr(6,1)*1;
	    idnum8=idnum.substr(7,1)*2;
	    idnum9=idnum.substr(8,1)*1;

	    if (idnum1>9) idnum1=(idnum1%10)+1
	    if (idnum2>9) idnum2=(idnum2%10)+1
	    if (idnum3>9) idnum3=(idnum3%10)+1
	    if (idnum4>9) idnum4=(idnum4%10)+1
	    if (idnum5>9) idnum5=(idnum5%10)+1
	    if (idnum6>9) idnum6=(idnum6%10)+1
	    if (idnum7>9) idnum7=(idnum7%10)+1
	    if (idnum8>9) idnum8=(idnum8%10)+1
	    if (idnum9>9) idnum9=(idnum9%10)+1

	    var sumval=idnum1+idnum2+idnum3+idnum4+idnum5+idnum6+idnum7+idnum8+idnum9;
	    if(sumval == 0)
	     return false;
	    sumval=sumval%10
	    if (sumval>0)
	    {
	        return false;
	    }
	  return true;
	}


/* This script and many more are available free online at
The JavaScript Source!! http://javascript.internet.com
Created by: David Leppek :: https://www.azcode.com/Mod10

Basically, the alorithum takes each digit, from right to left and muliplies each second
digit by two. If the multiple is two-digits long (i.e.: 6 * 2 = 12) the two digits of
the multiple are then added together for a new number (1 + 2 = 3). You then add up the
string of numbers, both unaltered and new values and get a total sum. This sum is then
divided by 10 and the remainder should be zero if it is a valid credit card. Hense the
name Mod 10 or Modulus 10. */

	function Mod10(ccNumb)
	{  // v2.0
		var valid = "0123456789";
		var len = ccNumb.length;
		var iCCN = parseInt(ccNumb, 10);
		var sCCN = ccNumb.toString();
		sCCN = sCCN.replace (/^\s+|\s+$/g,'');
		var iTotal = 0;
		var bNum = true;
		var bResult = false;
		var temp;
		var calc;

		// Determine if the ccNumb is in fact all numbers
		for (var j=0; j<len; j++) {
			temp = "" + sCCN.substring(j, j+1);
			if (valid.indexOf(temp) == "-1"){bNum = false;}
		}

		// if it is NOT a number, you can either alert to the fact, or just pass a failure
		if(!bNum)
			bResult = false;


		// Determine if it is the proper length
		if((len == 0)&&(bResult)) {
			bResult = false;
		}
		else {  // ccNumb is a number and the proper length - let's see if it is a valid card number
			if(len >= 15) {
				for(var i=len;i>0;i--) {
					calc = parseInt(iCCN, 10) % 10;
					calc = parseInt(calc, 10);
					iTotal += calc;
					i--;
					iCCN = iCCN / 10;
					calc = parseInt(iCCN, 10) % 10 ;
					calc = calc *2;

					switch(calc) {
						case 10: calc = 1; break;       //5*2=10 & 1+0 = 1
						case 12: calc = 3; break;       //6*2=12 & 1+2 = 3
						case 14: calc = 5; break;       //7*2=14 & 1+4 = 5
						case 16: calc = 7; break;       //8*2=16 & 1+6 = 7
						case 18: calc = 9; break;       //9*2=18 & 1+8 = 9
						default: calc = calc;           //4*2= 8 &   8 = 8  -same for all lower numbers
					}
					iCCN = iCCN / 10;
					iTotal += calc;
				}
				if ((iTotal%10)==0) {
					bResult = true;
				}
				else {
					bResult = false;
				}
			}
		}

		return bResult;
	}

}
