// ==============================================================================
//                     JS Form Validation
// ==============================================================================
//rewrited and adapted by Alexander Samusenko <himaster at tut.by>  2006
// This is the rule to use to validate a value if none is specified.
defaultValidationRule	= "free";

defaultErrorPrefix	= "При проверке  возникли следующие ошибки :\n";
defaultErrorMessage	= "Значение в поле '[ELEMENT]' имеет неверное значение.";
defaultErrorFieldFocus=1;

function check_maxlen(element,maxlen){
	if (element.value.length > maxlen )
	{
		var cut=element.value.slice(0,maxlen-4);
		element.value=cut+'...';
		return false;
	} else return true;
}

function check_filled(elem){
var pattern=/\S/ ;
return !(pattern.test(elem.value));

}

function validateField(field_name, validation_code) {
	invertResult = false;

  
    if (validation_code.charAt(0) == "("){
   res=false;
   
       
   if(validation_code=='(>0)'){
        var sToReplace=/\s/g; 
        res=(Number(field_name.value.replace(sToReplace,""))>0)&&!invertResult;
   
   }
     return res;
   }
    else   // Check if they supplied a custom RegExp or just a rule name 
	if (validation_code.charAt(0) != "/") {
		// pre-defined rules available
		switch (validation_code.toLowerCase()) {
			case "txt" : 			// Text only allowed
				re = /^[a-z ]*$/i
				break;
			case "num" :			// Only numbers (allow decimal)
				re = /^[\d\.]*$/
				break;
			case "not0":
				re = /^[1-9]([\d \040]{0,10})*$/
				break;
			case "int" :			// Integers only
				re = /^\d*$/
				break;
			case "phone" :			// Phone number characters
				re = /^[\d \-\(\)\+]*$/
				break;
			case "date" :			// Well-formed Dates
				re = /^(()|(\d{1,2}(\/|-)\d{1,2}(\/|-)\d{2,4}))$/
				break;
			case "email" :			// Something valid-ish for an email
				re = /^[a-z\d\.\-_\040]+@[a-z\d\.\-_]{2,}\.[a-z\040]{2,10}$/i
				break;
			case "alnum" :			// Alpha-numeric characters
				re = /^[\w ]*$/i
				break;
			case "curr" :			// Currency (using "$", "," and ".")
				re = /^\$?\d*,?\.?\d{0,2}$/i
				break;
			case "addr" :			// Base Address rule
				re = /^[\w- \.,#]*$/gi
				break;
			case "name" :			// Good for validating names
				re = /^[a-z,\-\. ]*$/gi
				break;
			case "free" :			// Freeform, text, num and some chars
			    re = /\S/;
				//re = /^[\w\-\+\(\)\[\]\\/&, ]*$/i
				break;
			case "nobadsql" :		// Denies SQL which could be harmful
				re = /((delete|drop|update|replace|kill|lock) )/gi
				invertResult = true;
				break;
			case "checkbox":
				re=/^[ab]/;
				break;
			case "notnull" :		// Requires *anything*
				re = /\S/;
				break;
			default :			// Default - See "notnull"
			//	re = /^[\w\-\+\(\)\[\]\\/&, ]*$/i
			re = /\S/;
		}
     return (re.test(field_name.value)&&!invertResult);       
	}
	// This means they specified a RegExp of their own, which should be
	// in the form "/<RegExp>/" and needs to be "eval"ed before using.
	else {
		re = eval(validation_code);
        return (re.test(field_name.value)&&!invertResult);    
	}

	// Do the actual regular expression testing against the string
	// and return the result.
	
}

function getCharCount(form_element){
var ml=0;
for (i in val_id){
if (val_id[i]==form_element.id){
ml=val_ml[i];
if (val_ml[i]&&!check_maxlen(form_element,val_ml[i])){

				alert( "  - " + "Превышена максимально допустимая длина ( "+val_ml[i]+" ) поля "+val_cp[i] + ".\n");
				}
}


}
node=document.getElementById(form_element.id+'counter');

if (!node){

node=document.createElement("div");
node.id=form_element.id+'counter';
form_element.parentNode.appendChild(node);
}
node.innerHTML=('<strong class="char_counter" >осталось символов:'+(ml-form_element.value.length)+'<strong>');

}

// This is the mainline function which needs to be called on form submission to
// check required fields
function validateForm(form) {
	masterErrorMsg = defaultErrorPrefix;
	var toFocus=null;
	var fres;
	var res;
	var re;
	//check regions
    if(form['provinces']) {
        if(form['provinces'].value==0) {
            masterErrorMsg += "  - " + "Не выбрано РАСПОЛОЖЕНИЕ.\n";
        }       
    }
     
    // Loop through every element in the val_id specified.
    
    for (i in val_id){
        rule = "";
		msg  = "";
    	form_element = form[val_id[i]];
    	if (form_element){
    		// Set default validation rule if none is specified
    		if (!val_rl[i]) {
					rule = defaultValidationRule;
			}
			else {
					rule = val_rl[i];
			}
			// And set the default error message
			if (!val_em[i]) {
					error = defaultErrorMessage.replace('[ELEMENT]', form_element.name);
				}
				else {
					error = val_em[i].replace('[cp]',val_cp[i]);
				}

			try {
			res=eval(val_rd[i]);

			}
			catch(e){
			res=false;

			}

			if  (res){
             //check for notnull
            	re = /\S/;
				if (!re.test(form_element.value)||!validateField(form_element, rule)) {
						masterErrorMsg += "  - " + error + "\n";
						if(!toFocus){
							toFocus=form_element;
						}
				}
			//check maxlength
				if (val_ml[i]&&!check_maxlen(form_element,val_ml[i])){
				masterErrorMsg += "  - " + "Превышена максимально допустимая длина ( "+val_ml[i]+" ) поля "+val_cp[i] + ".\n";
				}
			}
    	}
        
    }
   

    if (masterErrorMsg != defaultErrorPrefix) {
			alert(masterErrorMsg);
			if(defaultErrorFieldFocus&& toFocus){
			window.scrollTo(0,toFocus.offsetTop-20);
				toFocus.focus();
			}
			fres=false;
			}
			else {
			fres=true;
			}
	return fres;
}

// Returns true or false based on whether the specified string is found
// in the array.
// This is based on the PHP function of the same name.
function in_array(stringToSearch, arrayToSearch) {
	for (s = 0; s < arrayToSearch.length; s++) {
		thisEntry = arrayToSearch[s];
		if (thisEntry.indexOf(stringToSearch) != -1) {
			return true;
			exit;
		}
	}
	return false;
}