// Form Field Types
var FIELD_TYPE_CHECKBOX = 1;
var FIELD_TYPE_SELEcT = 2;

var DEFAuLT_VALIDATOR_cLASS_NAME = "validator"; // Default class name
var VALIDATOR_cLASS_NAME = DEFAuLT_VALIDATOR_cLASS_NAME; // current class name


var is_valid = true; // Main Flag
var highlighted_errors = false; // Note: when using this feature, don't use <td style="background-color: ...">
								// Note: the validator DIV must be located directly inside the TD (validtor_div.parent. ...)
var highlighted_errors_color = "F49B27"; // color to use as background in cells which have errors.
var validation_language = "he"; // Default language for error messages

function initErrorStrings()
{	
	// Hebrew Error Messages
	if (validation_language == "he")
	{
		ERROR_EMPTY = "אנא מלא שדה זה";
		ERROR_SPAcE_NOT_ALLOWED = "סיסמא אינה יכולה להכיל רווחים"
		ERROR_PASSWORDS_NOT_EQuAL = "הסיסמאות אינן זהות"
		ERROR_INVALID_LENGTH = "אנא הקלד מקסימום %1 תווים";
		ERROR_INVALID_LENGTH2 = "אנא הקלד לפחות %1 תווים";
		ERROR_INVALID_EMAIL = "אנא תקן את פורמט האימייל שלך";
		ERROR_INVALID_NuMBER = "אנא הקלד מספר";
		ERROR_INVALID_uSERNAME = "אנא הקלד אותיות אנגליות וספרות בלבד"
		ERROR_INVALID_SELEcTION = "אנא בחר פריט מתוך הרשימה"
		ERROR_INVALID_MuLTI_SELEcTION = "אנא בחר לפחות פריט אחד"
		ERROR_INVALID_cREDIT_cARD_NuM = "אנא הקלד מס' כרטיס אשראי תקין"
		ERROR_INVALID_ID_NuM = "אנא הקלד מס' תעודת זהות תקין"
		ERROR_INVALID_DATE = "אנא בחר תאריך חוקי"
		ERROR_CHECKBOX_NOT_CHECKED = "יש לסמן וי בשדה זה"
		ERROR_INVALID_PHONE = "מס' הטלפון שהקלדת אינו תקין"
		ERROR_NOT_EQuAL_NuMBER = "המספרים אינם זהים"
		ERROR_EQuAL_NuMBER = "המספרים זהים"
		ERROR_NOT_SMALL_NuMBER = "המספר הראשון אינו קטן מהשני"
		ERROR_NOT_BIG_NuMBER = "המספר הראשון אינו גדול מהשני"
		ERROR_NOT_SMALL_OR_EQuAL_NuMBER = "המספר הראשון אינו קטן או שווה לשני"
		ERROR_NOT_BIG_OR_EQuAL_NuMBER = "המספר הראשון אינו גדול או שווה לשני"
	}
	
}

initErrorStrings(); // call to initialize

// Sets the validation language and reloads the strings
function setValidationLanguage(lang)
{
	validation_language = lang;
	initErrorStrings();
}

function isExplorer()
{
	return navigator.appName.indexOf("Explorer") > -1;
}
function insertTextt(obj, str) {
(element.hasChildNodes())? element.firstChild.data=str : element.appendChild(document.createTextNode(text));
}

function setInnerText(element, text)
{
	if (isExplorer()) 
			element.innerText = text;
		else
			element.textcontent = text;
}

function setValidatorclassName(class_name)
{
	VALIDATOR_cLASS_NAME = class_name;
}

function restoreValidatorclassName()
{
	VALIDATOR_cLASS_NAME = DEFAuLT_VALIDATOR_cLASS_NAME;
}

// Inits the highlighting variables
function setHighlightedErrors(highlight, color)
{
	highlighted_errors = highlight;
	highlighted_errors_color = color;
}

// clears all errors
function clearErrors()
{
	var divs = document.getElementsByTagName("div");
	var validator_div;
	
	for (i=0;i<divs.length;i++) 
	{
		try {
			if (divs[i].tagName == "DIV")				
				if (divs[i].className == VALIDATOR_cLASS_NAME)
				{
					validator_div = divs[i];
					
					try
					{
						validator_div.style.display = "none";
					
						if (highlighted_errors) validator_div.parentNode.style.backgroundcolor = "";
					}
					catch (e)
					{
						alert("Validator <DIV> not found: " + validator_div); 
					}
				}
		}
		catch (e)
		{
		
		}
	}
}

// clears the validation flag
function clearValidationFlag()
{	
	is_valid = true;
	
	clearErrors();
}

// Returns true if all validators passed
function isValid()
{
	return is_valid;
}

//clear the validator error
function clearError(validator_div)
{

}

// Set the validtor error message
function setError(validator_div, err_msg)
{
	if (validator_div == "") return; // Exit if empty validator, allows for using the functions without uI error msgs
	
	var div = document.getElementById(validator_div);
	
	is_valid = false;
	
	try 
	{			
		div.style.display = "block";
	
		//if (div.innerHTML == "") setInnerText(div, err_msg);
		if (div.getAttribute("error") == null) 
			setInnerText(div, err_msg);
		else
			setInnerText(div, div.getAttribute("error"));
			
		if (highlighted_errors) div.parentNode.style.backgroundcolor = highlighted_errors_color;
	}
	catch (e)
	{	
		alert("Validator <DIV> not found: " + validator_div);
	}
}
function validat_draw(validator_div)
{
setError(validator_div, ERROR_EMPTY);
		
if (!document.getElementById(validator_div).hasChildNodes()) {

  document.getElementById(validator_div).appendChild(document.createTextNode('.'));

}
document.getElementById(validator_div).firstChild.nodeValue = ERROR_EMPTY;
}

// Validate a non-empty field
function validateNonEmpty(field, validator_div)
{
	var str = trim(field.value);
	var s = new String();
	
	if (str == "" || str=="null" ||  str.length==0 )
	{
		setError(validator_div, ERROR_EMPTY);
		if (!document.getElementById(validator_div).hasChildNodes()) {

  document.getElementById(validator_div).appendChild(document.createTextNode('.'));

}

document.getElementById(validator_div).firstChild.nodeValue = ERROR_EMPTY;
		return false; // mark as dirty
	} 
	else
	{
		clearError(validator_div);
		return true;	
	}
}

// Validate an e-mail address
function validateEmail(field, validator_div)
{
  var Email = field.value;
  
  if (Email.length > 0 )
	  {
		var i   = Email.indexOf("@")
		var j   = Email.indexOf(".",i)
		var k   = Email.indexOf(",")
		var kk  = Email.indexOf(" ")
		var jj  = Email.lastIndexOf(".") + 1
		var len = Email.length
		
		if (!(i > 0 && j > (i + 1) && k == -1 && kk == -1 && (len - jj) >= 2 && (len - jj) <= 3))
		{
			setError(validator_div, ERROR_INVALID_EMAIL);
			return false; // mark as dirty
		}
  }  
  
  clearError(validator_div);
  return true;
}

// Validates a numeric value
function validateNumber(field, validator_div)
{
 	if (isNaN(field.value))
 	{
		setError(validator_div, ERROR_INVALID_NuMBER);
		return false; // mark as dirty
	}
	
	clearError(validator_div);
	return true;
}

// clears an HTML form, clears all text fields and selections.
function clearHtmlForm(form)
{
	var e;
	
	for (var i=0; i < form.elements.length; i++)
	{				
		e = form.elements[i];
		
		if ((e.tagName == "INPuT") && (e.type == "text")) e.value = "";
		if ((e.tagName == "INPuT") && (e.type == "password")) e.value = "";
		if ((e.tagName == "INPuT") && (e.type == "checkbox")) e.checked = false;
		if ((e.tagName == "INPuT") && (e.type == "radio")) e.checked = false;
		if (e.tagName == "TEXTAREA") e.value = "";
		if (e.tagName == "SELEcT") e.selectedIndex = 0;
	}
}

function addParam(controlText, paramName, paramValue)
{	
	return "<param name='" + paramName + "' value='" + paramValue + "'>";
}

function createFlash(DivID, ObjectID, WIDTH, HEIGHT, MOVIE)
{  
	var s = "<object classid='clsid:d27cdb6e-ae6d-11cf-96b8-444553540000' codebase='http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0' width='" + WIDTH + "' height='"+HEIGHT+"' id='"+ObjectID+"'>";
	
	s += addParam(s, "movie", MOVIE);
	s += addParam(s, "uiMode", "none");
	s += addParam(s, "wMode", "transparent");	
	s += "<EMBED wmode='transparent' src='" + MOVIE + "' quality=high width='" + WIDTH + "'height='" + HEIGHT + "' TYPE='application/x-shockwave-flash' "
	  +  "PLuGINSPAGE='http://www.macromedia.com/go/getflashplayer'> </EMBED>";	
	s += "</object>"
	
	document.getElementById(DivID).innerHTML += s;	
}		


function trim(str)
{
   return str.replace(/^\s*|\s*$/g,"");
}


/*
Form field Limiter script- By Dynamic Drive
For full source code and more DHTML scripts, visit http://www.dynamicdrive.com
This credit MUST stay intact for use
*/

var ns6=document.getElementById&&!document.all

function restrictinput(maxlength,e,placeholder){
if (window.event&&event.srcElement.value.length>=maxlength)
return false
else if (e.target&&e.target==eval(placeholder)&&e.target.value.length>=maxlength){
var pressedkey=/[a-zA-Z0-9\.\,\/]/ //detect alphanumeric keys
if (pressedkey.test(String.fromCharCode(e.which)))
e.stopPropagation()
}
}

function countlimit(maxlength,e,placeholder){
var theform=eval(placeholder)
var lengthleft=maxlength-theform.value.length
var placeholderobj=document.all? document.all[placeholder] : document.getElementById(placeholder)
if (window.event||e.target&&e.target==eval(placeholder)){
if (lengthleft<0)
theform.value=theform.value.substring(0,maxlength)
placeholderobj.innerHTML=lengthleft
}
}


function displaylimit(thename, theid, thelimit){
var theform=theid!=""? document.getElementById(theid) : thename
var limit_text='<b><span id="'+theform.toString()+'">'+thelimit+'</span></b>'
if (document.all||ns6)
document.write(limit_text)
if (document.all){
eval(theform).onkeypress=function(){ return restrictinput(thelimit,event,theform)}
eval(theform).onkeyup=function(){ countlimit(thelimit,event,theform)}
}
else if (ns6){
document.body.addEventListener('keypress', function(event) { restrictinput(thelimit,event,theform) }, true); 
document.body.addEventListener('keyup', function(event) { countlimit(thelimit,event,theform) }, true); 
}
}

function displaylimit2(thename, theid, thelimit){
var theform=theid!=""? document.getElementById(theid) : thename
var limit_text='<b><span id="'+theform.toString()+'">'+thelimit+'</span></b>'
if (document.all||ns6)
document.write(limit_text)
if (document.all){
eval(theform).onkeypress=function(){ return restrictinput(thelimit,event,theform)}
eval(theform).onkeyup=function(){ countlimit(thelimit,event,theform)}
}
else if (ns6){
document.body.addEventListener('keypress', function(event) { restrictinput(thelimit,event,theform) }, true); 
document.body.addEventListener('keyup', function(event) { countlimit(thelimit,event,theform) }, true); 
}
}



// Use this function to save a cookie.
function setCookie(name, value, expires) {
document.cookie = name + "=" + escape(value) + "; path=/" +
((expires == null) ? "" : "; expires=" + expires.toGMTString());
}

// Use this function to retrieve a cookie.
function getCookie(name){
var cname = name + "=";               
var dc = document.cookie;             
    if (dc.length > 0) {              
    begin = dc.indexOf(cname);       
        if (begin != -1) {           
        begin += cname.length;       
        end = dc.indexOf(";", begin);
            if (end == -1) end = dc.length;
            return unescape(dc.substring(begin, end));
        } 
    }
return null;
}

// Function to retrieve form element's value.
function getValue(element) {
var value = getCookie(element.name);
    if (value != null) element.value = value;
}

// Function to save form element's value.
function setValue(element) {
setCookie(element.name, element.value, exp);
}

//Sets the exp date to 31 days
var exp = new Date();                                   
exp.setTime(exp.getTime() + (990 * 60 * 60 * 24 * 31));

// Use this function to delete a cookie.
function delCookie(name) {
document.cookie = name + "=; expires=Thu, 01-Jan-70 00:00:01 GMT" +  "; path=/";
}

function reloadCAPTCHA() {
	document.getElementById('CAPTCHA').src='CAPTCHA_image.asp?'+Date();
}



