/**
 * @Author:	Albert Harounian
 * @desc: 	Global form elements validation
 * @since: 	August 16 2007
 * @usage: 	validate(
 *					frmName 		[required],
 *					errorClass 		[optional],
 *					breakByAlert 	[optional]
 *				   );
 *			frmName 		= form NAME(NOT ID!) to be validate
 *			errorClass 		= class name to be ADDED to element when the value is not valid
 *			breakByAlert 	= if sets to true function WILL return error string for current element, then makes alert and exits
 * ***************************************************************************************************************************
 * SYNTAX:
 *		 required="REQUIRED TPYE:FIELD NAME:ERROR MSG;EXTRA PARAMS"
 *
 *		 REQUIRED TPYE 	= any|email|numeric|hebrew|english|price|password|file|terms for the same input name 
 *		 FIELD NAME		= field name that present to user on error;
 *		 ERROR MSG 	= your msg when the field doesnt match the required type [optional]
 *		 EXTRA PARAMS 	= ALLOWED extensions file for file inputs ( divider line seperated ) or 
 *						  MINIMUM CHARS and/or COMPARISON to another input(by NAME) for PASSWORD inputs ( COMMA seperated )
 * ***************************************************************************************************************************
 * ***************************************************************************************************************************
 * NOTES: this validation function use 'REQUIRED' attribute for checking the field.
 *	 	 (!) REQUIRED TPYE CAN be ANYTHING if the input type is NOT TEXT type but it CAN NOT be NULL
 *	 	 (!) REQUIRED TPYE CAN be NULL if it defined before (usually for radio buttons and checkboxes)
 *
 *		 (!) FIELD NAME can be NULL or ANYTHING - its up to you
 *		 (!) If FIELD NAME is empty the REAL(from 'name' attribute) will present to user
 *
 *	 	 (!) if ERROR MSG is NOT defined, the function will return messages form variables BELOW instead
 *
 *		 (!) when EXTRA PARAMS used for PASSWORD inputs, values(minimum length and/or comparison input name) 
 *			 should be seperates by COMMA
 * ***************************************************************************************************************************
 * e.g <input type="text" value="email" required="email:Login E-Mail:Invalid E-Mail">
 * e.g <input type="text" value="firstName" required="any:">
 * e.g <input type="text" value="firstName" name="password" required="password::The passwords doesnt match!;password2">
 * e.g <input type="text" value="firstName" name="password2">
 * e.g <input type="checkbox" value="terms" required="terms:Site Terms:You must agree">
 * e.g <input type="radio" name="userGender" value="male" required="sex:Gender:">
 * e.g <input type="radio" name="userGender" value="female"> (!) No need to define REQUIRED attribute
 * e.g <input type="file" value="userPic" required="picture:Your pat picture:Extention not allowed;gif|jpg|png">
 */

var isNull 				= "נא להזין מידע בשדה {FIELD}.";
var isTooShort			= "נא להזין לפחות {NUM} תווים בשדה {FIELD}.";
var isNotNumber			= "נא להזין נתונים מספריים בלבד בשדה {FIELD}.";
var isNotEmail			= "אי מייל אינו תקין.";
var isNotEqualPassword	= "אימות סיסמא נכשלה.";
var isNotPhone			= "מספר טלפון בשדה {FIELD} אינו תקין.";
var isNotPrice			= "מחיר אינו תקין.";
var isNotHeb			= "נא להזין תווים בעברית בלבד בשדה {FIELD}.";
var isNotEng			= "נא להזין תווים באנגלית בלבד בשדה {FIELD}.";
var isNotChecked		= "חובה לסמן שדה {FIELD}.";
var isNotFile			= "חובה לבחור קובץ לשדה {FIELD}.";
var isNotAllowedExt		= "סיומת קובץ לא מורשת לשדה {FIELD}.";
var isNotAgreeTerms		= "יש להסכים לתנאי השימוש באתר לפני ההרשמה";


// DO NOT edit variables below!
var forms_ENGLISH 		= "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ -";
var forms_HEBREW 		= "אבגדהוזחטיכלמנסעפצקרשתךףןםץ -";
var forms_DIGITS 		= "0123456789 -";

function validate(frmName, errorClass, breakByAlert){
	if(!frmName || !eval('document.'+frmName)){
		alert("ERROR: no form name!");
		return '';
	}
	var theElem;
	var theFrm 		= eval('document.'+frmName);
	var inputs 		= theFrm.length;
	var inpDefValue = "";
	var inpValue 	= "";
	var inpName		= "";
	var required	= "";
	var reqType 	= "";
	var reqName 	= "";
	var reqValue 	= "";
	var err 		= "";
	var i 			= 0;
	var j 			= 0;
	var isChecked 	= false;
	var fileExt 	= "";
	var extParams 	= "";
	var fieldArr 	= new Array();
	if(breakByAlert==null){
		breakByAlert = false;
	}
	for(i=0;i<inputs;i++){
		theElem = theFrm.elements[i];
		inpName = theElem.name;
		required = theElem.getAttribute('required');
		if(required!='' && required!=null){
			if(!is_inArray(inpName, fieldArr)){
				fieldArr[fieldArr.length] = inpName;
				required	= required.split(';');
				reqType 	= required[0].split(':')[0];
				reqName 	= required[0].split(':')[1];
				reqValue 	= required[0].split(':')[2];
				extParams	= required[1];
				inpValue 	= theElem.value;
				inpDefValue = theElem.defaultValue;
				if(inpValue!=inpDefValue || extParams.toUpperCase().indexOf('ALLOW_DEFAULT')==-1){
					switch(theElem.type){
						case "checkbox":
						case "radio":
							isChecked = false;
							for(j=0;j<inputs && !isChecked;j++){
								if(theFrm.elements[j].type==theElem.type && theFrm.elements[j].name==inpName){
									if(theFrm.elements[j].checked){
										isChecked = true;
									}
								}
							}
							if(!isChecked){
								err += reqValue ? reqValue : (reqType=='terms' ? isNotAgreeTerms : isNotChecked).replace('{FIELD}',reqName);
								err += "\n";
								if(theElem.className.indexOf(errorClass) == -1){
									theElem.setAttribute('orgClass',theElem.className);
									theElem.className +=  " " + errorClass;
								}
								if(breakByAlert){
									alert(err);
									return err;
								}
							}else{
								theElem.className = theElem.className.replace(errorClass,'');
							}
							break;
						case "select-one":
						case "select-multiple":
							if(theElem.options[theElem.selectedIndex].value==''){
								err += reqValue ? reqValue : isNotChecked.replace('{FIELD}',reqName);
								err += "\n";
								if(theElem.className.indexOf(errorClass) == -1){
									theElem.setAttribute('orgClass',theElem.className);
									theElem.className +=  " " + errorClass;
								}
								if(breakByAlert){
									alert(err);
									return err;
								}
							}else{
								theElem.className = theElem.className.replace(errorClass,'');
							}
							break;
						case "file":
							fileExt 	= inpValue.split('.');
							fileExt 	= fileExt[fileExt.length-1];
							extParams 	= extParams.split("|");
							if(inpValue==''){
								err += reqValue ? reqValue : isNotFile.replace('{FIELD}',reqName);
								if(breakByAlert){
									alert(err);
									return err;
								}
								err += "\n";
							}else{
								if(!is_inArray(fileExt,extParams)){
									err += reqValue ? reqValue : isNotAllowedExt.replace('{FIELD}',reqName);
									err += "\n";
									if(theElem.className.indexOf(errorClass) == -1){
										theElem.setAttribute('orgClass',theElem.className);
										theElem.className +=  " " + errorClass;
									}
									if(breakByAlert){
										alert(err);
										return err;
									}
								}else{
									theElem.className = theElem.className.replace(errorClass,'');
								}
							}
							break;
						case "text":
						case "hidden":
						case "password":
						case "textarea":
							extParams = extParams ? extParams.split(',') : inpValue.length;
							if(inpValue==inpDefValue || inpValue==''){
								err +=  isNull.replace('{FIELD}',reqName);
								err += "\n";
								if(theElem.className.indexOf(errorClass) == -1){
									theElem.setAttribute('orgClass',theElem.className);
									theElem.className +=  " " + errorClass;
								}
								if(breakByAlert){
									alert(err);
									theElem.focus();
									return err;
								}
							}else if(inpValue.length < extParams[0]){
								err +=  (isTooShort.replace("{NUM}",extParams[0])).replace('{FIELD}',reqName);
								err += "\n";
								if(theElem.className.indexOf(errorClass) == -1){
									theElem.setAttribute('orgClass',theElem.className);
									theElem.className +=  " " + errorClass;
								}
								if(breakByAlert){
									alert(err);
									theElem.focus();
									return err;
								}
							}else{
								switch(reqType){
									case "any":
										theElem.className = theElem.className.replace(errorClass,'');
										break;
									case "numeric":
										if(!IsNumeric(inpValue)){
											err += reqValue ? reqValue : isNotNumber.replace('{FIELD}',reqName);
											err += "\n";
											if(theElem.className.indexOf(errorClass) == -1){
												theElem.setAttribute('orgClass',theElem.className);
												theElem.className +=  " " + errorClass;
											}
											if(breakByAlert){
												alert(err);
												theElem.focus();
												return err;
											}
										}else{
											theElem.className = theElem.className.replace(errorClass,'');
										}
										break;
									case "email":
										if(!IsEmail(inpValue)){
											err += reqValue ? reqValue : isNotEmail.replace('{FIELD}',reqName);
											err += "\n";
											if(theElem.className.indexOf(errorClass) == -1){
												theElem.setAttribute('orgClass',theElem.className);
												theElem.className +=  " " + errorClass;
											}
											if(breakByAlert){
												alert(err);
												theElem.focus();
												return err;
											}
										}else{
											theElem.className = theElem.className.replace(errorClass,'');
										}
										break;
									case "phone":
										if(!IsNumeric(inpValue)){
											err += reqValue ? reqValue : isNotPhone.replace('{FIELD}',reqName);
											err += "\n";
											if(theElem.className.indexOf(errorClass) == -1){
												theElem.setAttribute('orgClass',theElem.className);
												theElem.className +=  " " + errorClass;
											}
											if(breakByAlert){
												alert(err);
												theElem.focus();
												return err;
											}
										}else{
											theElem.className = theElem.className.replace(errorClass,'');
										}
										break;
									case "price":
										if(!IsPrice(inpValue)){
											err += reqValue ? reqValue : isNotPrice.replace('{FIELD}',reqName);
											err += "\n";
											if(theElem.className.indexOf(errorClass) == -1){
												theElem.setAttribute('orgClass',theElem.className);
												theElem.className +=  " " + errorClass;
											}
											if(breakByAlert){
												alert(err);
												theElem.focus();
												return err;
											}
										}else{
											theElem.className = theElem.className.replace(errorClass,'');
										}
										break;
									case "hebrew":
										if(!IsHebrew(inpValue)){
											err += reqValue ? reqValue : isNotHeb.replace('{FIELD}',reqName);
											err += "\n";
											if(theElem.className.indexOf(errorClass) == -1){
												theElem.setAttribute('orgClass',theElem.className);
												theElem.className +=  " " + errorClass;
											}
											if(breakByAlert){
												alert(err);
												theElem.focus();
												return err;
											}
										}else{
											theElem.className = theElem.className.replace(errorClass,'');
										}
										break;
									case "english":
										if(!IsEnglish(inpValue)){
											err += reqValue ? reqValue : isNotEng.replace('{FIELD}',reqName);
											err += "\n";
											if(theElem.className.indexOf(errorClass) == -1){
												theElem.setAttribute('orgClass',theElem.className);
												theElem.className +=  " " + errorClass;
											}
											if(breakByAlert){
												alert(err);
												theElem.focus();
												return err;
											}
										}else{
											theElem.className = theElem.className.replace(errorClass,'');
										}
										break;
									case "password":
										if(extParams && extParams!=''){
											if(inpValue!=eval('document.'+frmName+'.'+extParams[1]).value){
												err += reqValue ? reqValue : isNotEqualPassword.replace('{FIELD}',reqName);
												err += "\n";
												if(theElem.className.indexOf(errorClass) == -1){
													theElem.setAttribute('orgClass',theElem.className);
													theElem.className +=  " " + errorClass;
												}
												if(breakByAlert){
													alert(err);
													theElem.focus();
													return err;
												}
											}else{
												theElem.className = theElem.className.replace(errorClass,'');
											}
										}
										break;
									default:
										break;
								}
							}
							break;
						default:
							break;
					}
				}
			}
		}
	}
	if(err!=''){
		return "<err />" + err;
	}else{
		return "<ok />";
	}
}	

function is_inArray(str, arr){
	var i = 0;
	for(i=0;i<arr.length;i++){
		if(str == arr[i]){
			return true;
		}
	}
	return false;
}

function IsNumeric(sText){
	return (ChkStrBy(sText,forms_DIGITS));
}

function IsPrice(sText){
	return (ChkStrBy(sText,"0123456789."));
}

function IsHebrew(sText){
	return (ChkStrBy(sText,forms_HEBREW));
}

function IsEnglish(sText){
	return (ChkStrBy(sText,forms_ENGLISH));
}

function ChkStrBy(sText, sValidChars){
	var ret = true;
	var i = 0;
	if (sText.length==0) return (false);
	for (i = 0 ; i < (sText.length) && (ret==true) ; i++){ 
		if (sValidChars.indexOf(sText.charAt(i)) == -1){
			ret = false;
		}
	}
	return (ret);
}

function IsEmail(sText) {
	var at="@"
	var dot="."
	var lat=sText.indexOf(at)
	var lstr=sText.length
	var ldot=sText.indexOf(dot)
	if (sText=="" || sText==null){ return false }
	if (sText.indexOf(at)==-1 || sText.indexOf(at)==0 || sText.indexOf(at)==lstr){ return false }
	if (sText.indexOf(dot)==-1 || sText.indexOf(dot)==0 || sText.indexOf(dot)==lstr){ return false }
	if (sText.indexOf(at,(lat+1))!=-1){ return false }
	if (sText.substring(lat-1,lat)==dot || sText.substring(lat+1,lat+2)==dot){ return false }
	if (sText.indexOf(dot,(lat+2))==-1){ return false }
	if (sText.indexOf(" ")!=-1){ return false }
 	return true					
}

function IsPassword(sText,min,max){
	if ((min>0)&&(sText.length<min)) return (false);
	if ((max>0)&&(sText.length>max)) return (false);
	return (ChkStrBy(sText,forms_ENGLISH + "0123456789_"));
}

function IsPhone(sText){
	return (ChkStrBy(sText,"0123456789-"));
}

function ClearForm(form){
	var vars = form.elements;
	var i = 0;
	for(i=0; i < vars.length; i++){
		switch(vars[i].type){
			case 'textarea'   :
			case 'text'       : vars[i].value = ''; break;
			case 'select-multiple':
			case 'select-one' : vars[i].selectedIndex = 0; break;
			case 'checkbox'   :
			case 'radio'      : vars[i].checked = false; break;  			
  		}
	}
}

function Trim(strValue){
	return LTrim(RTrim(strValue));
}

function LTrim(strValue){
	var LTRIMrgExp = /^\s */;
	return strValue.replace(LTRIMrgExp, '');
}

function RTrim(strValue){
	var RTRIMrgExp = /\s *$/;
	return strValue.replace(RTRIMrgExp, '');
}