/// InputField Smart Web Validator ///////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//  This client-side code should be supplemented to InputField Custom Control.  //
//  It will enable validation on client side, in addition to the server-side    //
//  checks. Note that some CSS classes should be added to activate visual       //
//  effects.                                                                    //
//																				//
//  For more information, questions and improvements, contact Sharon D.         //
//////////////////////////////////////////////////////////////////////////////////

/// ValidateForm  ////////////////////////////////////////////
//////////////////////////////////////////////////////////////
// For use with inputField Validator						//
//  validateForm(htmlObj)								    //
//															//
//	Will engage validation on all inputfield elements.		//
//////////////////////////////////////////////////////////////

function validateForm(element)
{   
  var rtn=true;
	
  if (!element)
  {
    element=window.document.forms[0]
  }
    
  var inputFields=element.getElementsByTagName('input');	
  for (var i=inputFields.length-1; i>=0; --i)
  {
    if(inputFields[i].getAttribute("skipValidation")=="true"){
       continue;
    }
    if (inputFields[i].className.indexOf('IWInputField')>-1)
    {
      var f = inputFields[i];
      if (f.attributes["EvaluationID"]==null)
        activateIWElement(f);
          
      if (!eval(f.attributes["EvaluationID"].value+".isValid()"))
	    rtn=false;								
    }
  }
    	
  return rtn;
}


function unValidateForm(element)
{   
  var rtn=true;
	
  if (!element)
  {
    element=window.document.forms[0]
  }
    
  var inputFields=element.getElementsByTagName('input');	
  for (var i=inputFields.length-1; i>=0; --i)
  {
    if(inputFields[i].getAttribute("skipValidation")=="true"){
       continue;
    }
    if (inputFields[i].className.indexOf('IWInputField')>-1)
    {
      var f = inputFields[i];
      if (f.attributes["EvaluationID"]==null)
        activateInputField(f)
          
      eval(f.attributes["EvaluationID"].value+".markPassedValidation()")
    }
  }
}

String.prototype.trim = function() { return this.replace(/^\s+|\s+$/, ''); };

function InputField(evalID, IFelement) 
{
    this.isValid=function(doFocus)
    {
	    if (this.validateInput())
		    return true;
    	
	    window.setTimeout(this.getElementAttribute("EvaluationID")+".blinkErrMsg()",50);
    	
	    if (doFocus!=false)
	     this.element.focus();
    	 
	    return false;
    }

    this.blinkErrMsg=function()
    {
      var errorSpan=document.getElementById(this.element.id+'ErrSpan');
	    if (this.times>0)		
	    {
		    --this.times;
		    if (errorSpan!=null)
		    {
			    var curStatus=errorSpan.style.visibility;			
			    errorSpan.style.visibility=((curStatus=="visible") ? "hidden" : "visible");	
			    window.setTimeout(this.getElementAttribute("EvaluationID")+".blinkErrMsg()",100);
		    }
	    }
	    else
	    {
		    this.times=this.getElementAttribute("blinkingTimes");
		    if (errorSpan!=null)
			    errorSpan.style.visibility="visible";	
	    }
    }

    this.doFormat=function()
    {
        var FORMAT=this.getElementAttribute("format");
	    if (this.element.value!="" && FORMAT!=null && FORMAT.toLowerCase().indexOf('commadelimiter')>-1)
	    {
		    this.element.value=parseFloat(this.element.value.replace(new RegExp(/,/g), ""));

		    var idx=(this.element.value.lastIndexOf('.')>-1) ? this.element.value.lastIndexOf('.') : this.element.value.length;
    				
		    for (var i=idx-1; i>0; --i)
		    {
			    if (((i-idx)%3)==0)
				    this.element.value=this.element.value.substr(0,i)+","+this.element.value.substr(i,this.element.value.length);
		    }	
	    }
    }

    this.undoFormatting=function()
    {
        var FORMAT=this.getElementAttribute("FORMAT");
	    var rtn=this.element.value;
    	
	    if (FORMAT!=null && FORMAT.toLowerCase().indexOf('commadelimiter')>-1)
		    rtn=this.element.value.replace(new RegExp(/,/g), "");
    	
	    return rtn;
    }
    this.getElementAttribute=function(attName)
    {
        attValue=this.element.attributes[attName];
        return attValue!=null ? attValue.value : attValue;
    }
    this.setElementAttribute=function(attName, attValue)
    {
        this.element.setAttribute(attName, attValue);
    }
    
    // Initialize the element
    this.initialize=function()
    {	
	    if (this.getElementAttribute("allowed_chars")==null)
		    this.setElementAttribute("allowed_chars","");
		    
		  this.ALLOWED_CHARS=this.getElementAttribute("allowed_chars");
	    if (this.getElementAttribute("accepts")!=null)
		    this.fillAllowedChars();	

	    if (this.getElementAttribute("blinkingTimes")==null)
		    this.setElementAttribute("blinkingTimes",7);
    		
	    this.times=this.getElementAttribute("blinkingTimes");
    	
	    this.doFormat();
	    this.handlePropertyChange();	
    }

    this.handlePropertyChange=function()
    {
      var REQUIRED=this.getElementAttribute("required");
	    if (REQUIRED!=null && REQUIRED!=false && this.element.className.toLowerCase().indexOf('required')<0)
	    {	
		    this.element.className+=" required";
		    this.setElementAttribute("required","TRUE")
	    }
	    if (this.getElementAttribute("readonly")==true && this.element.className.toLowerCase().indexOf('readonly')<0 )
	    {
		    this.element.className+=" "+readonlycss;
	    }	
    }

    this.markFailedValidation=function()
    {
		    this.element.className=this.element.className.replace(' failedvalidation','');
		    this.element.className+=" failedvalidation";
		    if (document.getElementById(this.element.id+'ErrSpan')!=null)
			    document.getElementById(this.element.id+'ErrSpan').style.visibility="visible";

		    return false;
    }

    this.markPassedValidation=function()
    {
		    this.element.className=this.element.className.replace(' failedvalidation','');
    		
		    if (document.getElementById(this.element.id+'ErrSpan')!=null)
			    document.getElementById(this.element.id+'ErrSpan').style.visibility="hidden";
    			
		    return true;
    }



    // Internal function to assist validate ID numbers
    function f_add_digits(al_num)  {

	    var ls_num=String(al_num);

	    var ll_sum=0
	    for (var i=0;i<ls_num.length;i++)  {
		    ll_sum+=parseInt(ls_num.substr(i,1));
	    }
	    if (ll_sum>9)  {
		    return f_add_digits(ll_sum);
	    }
	    else  {
		    return ll_sum;
	    }
    }

    this.validateNumericRange=function (rawValue)
    {
	    var numericValue=parseInt(rawValue);

        maxValue=this.getElementAttribute("maxValue");
        minValue=this.getElementAttribute("minValue");
	    return ((maxValue==null || numericValue<=maxValue) && (minValue==null || numericValue>=minValue));
    }

    this.validateInput=function()
    {
	    this.element.value=this.element.value.replace(/^\s+|\s+$/, '');
    	
	    this.markPassedValidation();

	    if (this.element.disabled)
		    return true;
    	
	    if (this.element.value.length==0)
	    {
		    if (this.getElementAttribute("required"))
			    return this.markFailedValidation();
		    else
			    return true;
	    }

	    var rawValue=this.undoFormatting();
	    if (rawValue.length<this.getElementAttribute("MinLength") || !this.validateNumericRange(rawValue))
		    return this.markFailedValidation();

    	VALIDATE=this.getElementAttribute("validate");
        VALIDATE=(VALIDATE!=null ? VALIDATE.toLowerCase() : "");
        
	    // Email Validation
	    if (VALIDATE=="email")
	    {
		    if (this.element.value.search(/\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/)==-1)
			    return this.markFailedValidation();
	    }
	    else
	    // Israel ID Number
	    if (VALIDATE=="tznum")
	    {
		    var ll_sum=0;
		    ls_num=this.element.value;
			    // Get the number and the "Sifrat Bikoret"
		    ll_idnum=ls_num.substr(0,ls_num.length-1);
		    ll_sb=ls_num.substr(ls_num.length-1);

		    // Add 0's to the number, if less than 8 digits
		    for (var i=0;i<(9-ls_num.length);i++)  {
			    ll_idnum='0'+ll_idnum;
		    }
		    // Calculate the resulting number
		    for (var i=0;i<8;i++)  {
			    ll_multi=i % 2;
			    ll_multi++;
			    var ll_digit=f_add_digits(parseInt(ll_idnum.substr(i,1))*ll_multi);
			    ll_sum+=ll_digit;
		    }
    		
		    // Calculate the Sifrat Bikoret
		    ll_csb=10-(ll_sum % 10);
		    if (ll_csb==10) ll_csb=0;
		    if (String(ll_csb)!=String(ll_sb))
			    return this.markFailedValidation();
		    else 
			    this.element.value=ll_idnum+ll_sb;
	    }
	    else
	    // Date DD/MM/YYYY
	    if (VALIDATE=="date")	
	    {
		    var dt = new Date(this.element.value);
            if (dt.toString() == 'NaN')
			    return this.markFailedValidation();
	    }
	    else
	    // Everything Else : handle validate as Regular Expression
		    if (VALIDATE.length!=0 && this.element.value.search(VALIDATE)==-1 )
			    return this.markFailedValidation();

	    return true;
    }

    this.fillAllowedChars=function()
    {    	
        var ACCEPTS=this.getElementAttribute("accepts").toLowerCase();
	    if (ACCEPTS.indexOf('txt')>-1)		//heb, eng, num
	    {
		    this.rangedFill(32,126);			// eng & nums & symbols
		    this.rangedFill(1488, 1514);		// heb
		    
		    this.ALLOWED_CHARS+=" ";
	    }
    	
	    if (ACCEPTS.indexOf('heb')>-1)		//only heb
		    this.rangedFill(1488, 1514);
    		
	    if (ACCEPTS.indexOf('eng')>-1)		//only eng
	    {
		    this.rangedFill(65,90);
		    this.rangedFill(97,122);
	    }
    		
	    if (ACCEPTS.indexOf('num')>-1)		//only num
		    this.rangedFill(48,57);
    	
	    if (ACCEPTS.indexOf('sym')>-1)		//only symbols
	    {
		    this.rangedFill(33,47);
		    this.rangedFill(58,64);
		    this.rangedFill(91,96);
		    this.rangedFill(123,126);
	    }
	    this.setElementAttribute("allowed_chars",this.ALLOWED_CHARS);
    }

    this.rangedFill=function(from, to)
    {
	    for (var i=from; i<=to; ++i)
	    {
		    this.ALLOWED_CHARS+=String.fromCharCode(i);
	    }
    }


    // Checks if certain character exist in a given string
    charExist=function(chr, str)
    {
	    if (str=="" || str==null)
		    return null;
	    else 	
		    return (str.indexOf(chr)>-1);
    }

    // Validate by entered char
    validateLength=function (keyCode)
    {
	    return true;
    }

    
    this.doPaste=function()  
    {
	    var maxAllowedLen=this.getElementAttribute("maxLength")-this.element.value.length;
    	
    	
	    pastedStringBack=clipboardData.getData("Text");
    	
	    var index=0;	
	    var pastedString="";
    	
	    while (index<pastedStringBack.length && pastedString.length<maxAllowedLen)
	    {
		    var ch=pastedStringBack.charAt(index);
    		
		    if ((charExist(ch, this.getElementAttribute("block_chars"))!=true 
				    && charExist(ch, this.getElementAttribute("allowed_chars"))!=false))
			    pastedString+=ch;
    			
		    index++;			
	    }

	    clipboardData.setData("Text",pastedString);
    	
	    setTimeout(function(){clipboardData.setData('Text',pastedStringBack);},100);
    }
    
    
    // Constructor //
    
    this.isIE=document.all && window.ActiveXObject && navigator.userAgent.toLowerCase().indexOf("msie") > -1  && navigator.userAgent.toLowerCase().indexOf("opera") == -1;
    this.containerIDX=InputFieldIdx;
    this.element=IFelement;
    this.element.setAttribute("EvaluationID",evalID);
    this.ALLOWED_CHARS="";
    this.times=7;    
    
    this.initialize();
    
    this.element.onkeypress=function (ev)
    {
  	    if (ev==null) ev=event;
  	    
  	    var keyPressed=eval(this.attributes["EvaluationID"].value+".isIE") ? ev.keyCode : ev.charCode;
  	    
  	    if (keyPressed!=0)
  	    {
  	        var blockedChars=this.attributes["block_chars"];
            passedValidation=(charExist(String.fromCharCode(keyPressed), blockedChars==null ? null : blockedChars.value)!=true &&
			        charExist(String.fromCharCode(keyPressed), this.attributes["allowed_chars"].value)!=false) ;
        }	    
        else
            passedValidation=true;
            
	    if (!passedValidation)
	    {
	        if ( !eval(this.attributes["EvaluationID"].value+".isIE"))
	            ev.preventDefault();
	            
	        ev.returnValue=false;
	        
		    this.className+=" wrongKey";
	        window.setTimeout(this.attributes["EvaluationID"].value+".element.className="+this.attributes["EvaluationID"].value+".element.className.replace(' wrongKey','')", 100);
	    }

	   return passedValidation;
    }
    
    this.element.onkeydown=function(ev)
    {
      	if (ev==null) ev=event;
      	
        var keyPressed=ev.keyCode;

        if (keyPressed==13)
	    {
	        eval(this.attributes["EvaluationID"].value+".doFormat()");
		    if (this.attributes["nextField"]!=null)
		    {
			    if (eval(this.attributes["EvaluationID"].value+".validateInput()"))
			    {				
				    if(this.attributes["nextField"].value.indexOf("javascript:")==0)
					    eval(this.attributes["nextField"].value);
    					
				    nextFieldName=this.attributes["nextField"];

				    if (document.getElementById(nextFieldName.value)!=null)				
					    while(nextFieldName!=null && document.getElementById(nextFieldName.value).disabled==true)
					    {
						    nextFieldObj=document.getElementById(nextFieldName.value);
    						
						    if (nextField!=null)
							    nextFieldName=nextFieldObj.attributes["nextField"];
						    else
							    break;
					    }
				    if (document.getElementById(nextFieldName.value)!=null)
					    document.getElementById(nextFieldName.value).focus();
    				
				    ev.returnValue=false;
			    }
		    }	
	    }
    }
    
    this.element.onblur=function()
    {
        eval(this.attributes["EvaluationID"].value+".validateInput()")
    }
    
    this.element.onpaste=function()
    {
        eval(this.attributes["EvaluationID"].value+".doPaste()")
    }
    this.element.onfocus=function()
    {
        this.select();
    }
    
    var _this_element_onchange = this.element.onchange;
    this.element.onchange=function()
    {   
        eval(this.attributes["EvaluationID"].value+".doFormat();");
        var sFuncTmp = getOriginalHandlerCommandScript(_this_element_onchange);
        if(sFuncTmp!="")eval(sFuncTmp);        
    }
    
    function getOriginalHandlerCommandScript(functionHandler){
        if(functionHandler!=null){
            //alert(functionHandler);
            var sFuncTmp = functionHandler+"";
            sFuncTmp=sFuncTmp.replace(/function[^\(]*\([^\)]*\)/,"");
            if(sFuncTmp!=""){
               return sFuncTmp;
            }            
        }
        return "";
    }
}
function activateIWElement(IWelement, VisElement)
{
	controllingIWobject=IWelement.getAttribute("controllingIWObject");
	
	var IWLogicStatus=eval("typeof("+controllingIWobject+")");
	
	if (IWLogicStatus!="function")
	{
		if(IWLogicStatus=="undefined")
		{
			eval(controllingIWobject+"='loading logic...'");
			loadIWScript(controllingIWobject);
		}
		
		window.setTimeout(function(){activateIWElement(IWelement, VisElement)}, 1);
	}
	else
		bindIWLogic(IWelement, VisElement);
}

function bindIWLogic(IWelement, VisElement)
{
	if (eval("typeof("+controllingIWobject+"Collection)")=="undefined" )
	{
		eval(controllingIWobject+"Collection = new Array()");
		eval(controllingIWobject+"Idx=0");
	}
	
	var currentIdx=eval(controllingIWobject+"Idx");
	var collectionName=controllingIWobject+"Collection";
	
	eval(collectionName+"["+currentIdx+"]=new "+controllingIWobject+"('"+collectionName+"["+currentIdx+"]', IWelement, VisElement)");
	eval(controllingIWobject+"Idx++");
}

function loadIWScript(logicName) {
    var html_doc = document.getElementsByTagName('head').item(0);
    
    var js = document.createElement('script');
    js.setAttribute('language', 'javascript');
    js.setAttribute('type', 'text/javascript');
    js.setAttribute('src', "ClientResources.axd?ResourceName="+logicName);
    
    html_doc.appendChild(js);
}