 
 /*
 * Created By       : Rashmi Khamitkar
 * Date             : 14 July 2011
 * Description      : Javascript functions to validate controls
 * Dependent        : JSConstants.js,JSValidations.js,JSSpecialValidations.js
 --------------------------------------------------------------------------------------------------------
          Change History (Source Safe)
---------------------------------------------------------------------------------------------------------
   Date:			Author:                 Description:
---------------------------------------------------------------------------------------------------------

14 July 2011     Rashmi Khamitkar           Created
---------------------------------------------------------------------------------------------------------*/

var flagRequiredField=false;
var objAttributes ={
						"myType" : new String(),
					 	 maxLength : new Number(),
						 minLength : new Number(),
						 "requiredField" :new String(),
						 "title" : new String()
					}

					
//Function to highlight the control with invalid values
function HighlightControl(control)
{
	     //Set style for textbox.
         control.style.borderStyle = constBorderstyle;
         control.style.borderWidth = constBorderwidth;
         control.style.borderColor= constBordercolor;
}//End of function to highlight the control with invalid values

//Function to reset style of control when it has valid values
function ResetControlStyle(control)
{
    //Set style for textbox.
    control.style.borderStyle = "";
    control.style.borderWidth = "";
    control.style.borderColor= "";
}//End of function to reset style of control when it has valid values

//Function to clear the object that contains attribute values
function ClearAttributeObject()
{
        var obj =objAttributes
		obj.myType= "";
		obj.requiredField="";          	
        obj.minLength="";
        obj.maxLength="";
        obj.title= "";	
}
//function GetAttributeObject
//#region
//Function to get attributes values  in an object
function GetAttributeObject(cntrl)
{
        //Call function to clear the object
        ClearAttributeObject();
        
		var obj =objAttributes
		obj.myType= cntrl.getAttribute(constMyType);
		obj.requiredField=cntrl.getAttribute(constRequiredField);          	
        obj.minLength=cntrl.getAttribute(constMin);
        obj.maxLength=cntrl.getAttribute(constMax);
        obj.title= cntrl.title;	
    	return obj; 
    	
}//End of function to get attributes values  in an object
//#endregion

//function ValidateDiv(divId)
//#region
//Function to Validate div(Main function that is to be called on the event where u have to validate the control in the specific div)
function ValidateDiv(divId,msgContainer)
{

    var validationErrorList=[];
    if(!msgContainer)
    {
        msgContainer = 'messageContainer';
    }
    
        if(divId!="")
        {
            var div=document.getElementById(divId);
           
            //For concate validate message and required field message.
            var errorMessage="";
            
            var varMgs="";
            
	        if(!div) 
            {        
                return false;  
            }  
            
            div = typeof div === "string" ? document.getElementById(div) : div; 
            //Get the controls in the div  
            var cntrls = div.getElementsByTagName("*"); 
            
            //for loop to iterate throungh the controls
            for(var i = 0, maxI = cntrls.length; i < maxI; ++i)
            {
                 var cntrl = cntrls[i];     
                 //Call CheckControlValidations function
       	         varMgs = CheckControlValidations(cntrl);
       	         if(varMgs!='')
       	         {                        
       	          ValidationErrorLength= validationErrorList.length;
                  validationErrorList[ValidationErrorLength]=varMgs;
                }//if(varMgs!='')
                                   
            }//End of for loop to iterate throungh the controls
               
            
        }
        return AddErrorMsg(flagRequiredField,validationErrorList,msgContainer);
	   // return false;

} //End of function to Validate div					
//#endregion

//function CheckControlValidations
//#region
//Function to check validations for required field and regular expression
function CheckControlValidations (cntrl)
{

	//For validate field error message
    var validationErrorList =[];
    //For validate field error message
    var validationmessage ="";
    var requiredFieldMessage='';
	var flag=false;
	var ValidationErrorLength=0;
	 // Get Attribute object.
	var objAttr = GetAttributeObject(cntrl);
	//Get value
	var cntrlValue = cntrl.value;	
	
	// Switch to Control
	switch (cntrl.type)
	{   
		case "select-one" : //Check if the control is required field
		                    if(objAttr.requiredField == constRequiredFieldTrue)
			                {  
			                        //Check if the selected index is Zero
                                    if(document.getElementById(cntrl.id).selectedIndex==0)
                                    {
                                        //Cal the function to Highlight control
                                        HighlightControl(cntrl);  
                                        flagRequiredField=true;
                                        
                                    }//End of checking if the selected index is Zero
                                    
                                    else
                                    {
                                         //Set style for textbox.  
                                         ResetControlStyle(cntrl);
                                    }//End of if else for checking if the selected index is Zero
                                    
			                  }//End of checking if the control is required field
			                  
			                  break;
			                  
		case "select-multiple": //Check if the control is required field
		                         if(ValidateRequiredField(objAttr.requiredField,cntrl)!='')
		                         flagRequiredField=true;
			                     break;
			                     
		case "text" : //Check if the control is required field
//		            if(cntrl.title=="URL")
//		            {
//		                cntrlValue=cntrlValue.substring(7);
//		            }
		          if(objAttr.requiredField == constRequiredFieldTrue && cntrlValue == "")
			       {
			           //Set the page level flag to true         
                       flagRequiredField=true; 
                       //this flag used within function 
                       flag=true;
                          
			        }//End of checking if the control is required field
			        else
			        flag=false;
			        //Check if the text value is not blank and the flag is set to false
			        if(cntrlValue != "" && !flag)
			        {
			             //Call the function that cal the function to validate text with regular expression
                        validationmessage = ValidateRegularExpression(objAttr,cntrl);
                         //Check if message received is not blank
                         if(validationmessage!="")
                         {
                            //Set flag to true
                            flag=true;
                            
                         }//End of checking if message received is not blank
                         else flag=false;
			        }//End of checking if the text value is not blank and the flag is set to false
			        
			        //check if flag is true
			        if(flag) HighlightControl(cntrl);
			        
			        else ResetControlStyle(cntrl);
			        
			        break;
			         
	    case "textarea": //Check if the control is required field
		                 if(ValidateRequiredField(objAttr.requiredField,cntrl)!='')
		                 flagRequiredField=true;
		                 
		                 
			             break;
			                     
		case "checkbox": //Check if the control is required field
		                    if(objAttr.requiredField == constRequiredFieldTrue)
			                {  
			                        //Check if the checkbox is checked
                                     if(objAttr.requiredField == constRequiredFieldTrue && cntrlValue == "")//For dropdown selected index -1
                                    {
                                         //Cal the function to Highlight control
                                         HighlightControl(cntrl);
		                                    flagRequiredField =true;
                                        
                                    }//End of checking if the checkbox is checked
                                    
                                    else
                                    {
                                         //Set style for textbox.  
                                         ResetControlStyle(cntrl);
                                         
                                    }//End of else-if for checking if the checkbox is checked
                                    
			                  }//End of checking if the control is required field
			                  break;
			                  
	   case "radio": //Check if the control is required field
		                    if(objAttr.requiredField == constRequiredFieldTrue)
			                {  
			                        //Check if the radio button is checked
                                    if(document.getElementById(cntrl.id).checked==false)
                                    {
                                         
                                        HighlightControl(cntrl);  
		                                flagRequiredField=true;
                                    }
                                    else
                                    {
                                         //Set style for textbox.  
                                         ResetControlStyle(cntrl);
                                    }//End of else-if for checking if the radio button is checked
                                    
			                  }//End of checking if the control is required field
			                  break;
			                  
	    case "file" : //Check if the control is required field
		                    if(objAttr.requiredField == constRequiredFieldTrue)
			                {  
			                        //Check if the selected index is Zero
                                    if(cntrl.value=="")
                                    {
                                        //Cal the function to Highlight control
                                        HighlightControl(cntrl);  
                                        flagRequiredField=true;
                                        
                                    }//End of checking if the selected index is Zero
                                    
                                    else
                                    {
                                         //Set style for textbox.  
                                         ResetControlStyle(cntrl);
                                    }//End of if else for checking if the selected index is Zero
                                    
			                  }//End of checking if the control is required field
			                  
			                  break;
	                    
		
	}//End of switch
	

		
return validationmessage;  //return error messages
	
} //End of CheckControlValidations Function
//#endregion

//function ValidateRequiredField
//#region
//Function to find whether a control is required field and do the required
function ValidateRequiredField(requiredField,cntrl)
{
     var varRequiredErrorMessage="";
     //Check if control RequiredField attribute set to true
     if(requiredField == constRequiredFieldTrue)
	 {
		  //Check if control value is blank                     
          if(cntrl.value == "")
          {
                //Call the function to highlight the control 
                HighlightControl(cntrl);  
                //Set error message to a variable
                varRequiredErrorMessage = constRequiredFieldError;
                
          }//End of checking if control value is blank
          
          //If not blank than else
          else
          {
                //Set style for textbox.  
                ResetControlStyle(cntrl);
                
          }//End of else
          
	 }//End of checking if control RequiredField attribute set to true
	 
	 //return error message
	 return varRequiredErrorMessage;
	 
}//End of ValidateRequiredField function
//#endregion

//function ValidateForm
//#region
//Function to validate controls on form
function ValidateForm(formId)
{
 var validationErrorList=[];

            var varMgs="";
            var form1=document.getElementById(formId);
            form1 = typeof form1 === "string" ? document.getElementById(form1) : form1; 
            //Get the controls in the div  
            var cntrls = form1.getElementsByTagName("*");
            for(var j=0;j<form1.length;j++)
            {
                var frm=form1[j];
                varMgs = CheckControlValidations(frm);
                 if(varMgs!='')
       	         {                        
       	          ValidationErrorLength= validationErrorList.length;
                  validationErrorList[ValidationErrorLength]=varMgs;
                }//if(varMgs!='')
            }

               
            //ErrorMessage=requiredFieldMessage+validationmessage ;
            errorMessage=varMgs;
            
             return AddErrorMsg(flagRequiredField,validationErrorList,'messageContainer');
            
}
//#endregion

//function ValidateControlText
//#region
//Function to validate the text value of control according to regular expression			
function ValidateControlText(objControlAttributes,strText)
{
	
    var flag=true;
    //to set required field / exceed length msg
    var msg='';
    //Get value of min attribute 
    var strMin=objControlAttributes.minLength;
    //Get value of min attribute
    var strMax=objControlAttributes.maxLength;
	
	//Check if min and max length fot text value length is provided
	if((strMin!=null && strMax!=null && strMin!="" && strMax!="") || (strMax!=null && strMax!="") || (strMin!=null && strMin!=""))
	{
	    //Call the function to check lenght and the the flag
		flag = ValidateInputLength(strMin,strMax,strText);
		
	}//End of checking if min and max length fot text value length is provided
	
	//Check if flag is true
	if(flag)
	{
	  //switch case
	  switch (objControlAttributes.myType)
		{

		    case constAlphaNum :flag = AlphaNum(strText);
							    break;
    		  
		    case constAlphaNum_NoNum :flag =  AlphaNum_NoNum(strText);
								  break;
								  
            case constAlphaNum_Space_NoNum :flag = AlphaNum_Space_NoNum(strText);
							            break;
    		  
		    case constAlphaNum_Dash_NoNum :flag =  AlphaNum_Dash_NoNum(strText);
								       break;
								      
			case constAlphaNum_Space_Dash_NoNum:flag = AlphaNum_Space_Dash_NoNum(strText);
							                 break;
    		  
		    case constAlphaNum_Space_Dash_Dot_NoNum :flag =  AlphaNum_Space_Dash_Dot_NoNum(strText);
								                 break;
            
            case constAlphaNum_Space_Num :flag = AlphaNum(strText);
							          break;
    		  
		    case constAlphabets :flag =  Alphabets(strText);
							 break;	
								     
            case constAlphabets_Space :flag =  Alphabets_Space(strText);
								   break;
								   
			case constAlphabets_Space_Dash :flag =  Alphabets_Space_Dash(strText);
								        break;	
								        
			case constAlphabets_Space_Dash_Dot:flag = Alphabets_Space_Dash_Dot(strText);
							                break;
    		  
		    case constValidateInt :flag =  ValidateInt(strText);
							   break;
            
            case constValidateIntNonZero :flag =  ValidateIntNonZero(strText);
							          break;
							   
            case constValidateDecimal:flag =  ValidateDecimal(strText);
							       break;	
							   
			case constValidateDecimalNonZero:flag =  ValidateDecimalNonZero(strText);
							              break;
							              
            case constValidateEmail :flag =  ValidateEmail(strText);
							     break;
							   
            case constValidateMobile :flag =  ValidateMobile(strText);
							      break;
							      
            case constValidatePhone :flag =  ValidatePhone(strText);
							     break;
							   
            case constValidateWebsite :flag =  ValidateWebsite(strText);
							       break;
							       
			case constValidateHttpUrl :flag =  ValidateHttpUrl(strText);
							       break;
							       
             case constValidateCountryCode :flag =  ValidateCountryCode(strText);
							            break;
							   
            case constValidatePinCode :flag =  ValidatePinCode(strText);
							       break;
							       
            case constValidateDate_DMY :flag =  ValidateDate_DMY(strText);
							     break;
							   
            case constValidateDate_MDY :flag =  ValidateDate_MDY(strText);
							       break;
							       
            case constValidateDate_YMD :flag =  ValidateDate_YMD(strText);
							            break;		
							       
            case constValidateVATorCST :flag =  ValidateVATorCST(strText);
							            break;
							       
            case constValidateECC :flag =  ValidateECC(strText);
							       break;
							       
            case constValidatePAN :flag =  ValidatePAN(strText);
							       break;
							       
            case constValidateIP :flag =  ValidateIP(strText);
							       break;
							       
            case constValidateGUID :flag =  ValidateGUID(strText);
							        break;
							       
            case constValidateMacAddress :flag =  ValidateMacAddress(strText);
                                     break;
			case constOpen :
							              break;							       							       							       					       							       								       							      							            						   							   							     							                 
	   
		}//End of switch case
		if(!flag)
		msg=msgM102.replace(PlaceHolder,objControlAttributes.title);
		
	 }//End of checking if flag is true
	 else
	 {
	    msg=msgM103.replace(PlaceHolder,objControlAttributes.title);
	 }
	 
	//return flag 
	return msg;
	
}//End of function to validate the text value of control according to regular expression				
//#endregion

//function ValidateInputLength
//#region
//Function to validate whether control text value has length between the min and max value provided
function ValidateInputLength(varMin,varMax,inputText)
{
    //Check if Both minimum and maximum values are provided
    if(varMin!=null && varMax!=null && varMin!="" && varMax!="")
    {
        //Check if the control text value is greater than minimum length value and less than maximum length value
        if((inputText.toString().length >= varMin) && (inputText.toString().length <= varMax))
        {
            return true;
            
        }//End of checking if the control text value is greater than minimum length value and less than maximum length value
        
    } //End of checking if Both minimum and maximum values are provided
    
    //Check if maximum length value is provided
    else if(varMax!=null && varMax!="")
    {
        //Check if the control text value less than maximum length value
        if((inputText.toString().length <= varMax))
        {
            return true;
            
        }//End of checking if the control text value less than maximum length value
        
    }//End of checking if maximum length value is provided
    
    //Check if minimum length value is provided
    else if(varMin!=null && varMin!="")
    {
        //Check if the control text value is greater than minimum length value
        if((inputText.toString().length >= varMin))
        {
            return true;
            
        }//End of checking if the control text value is greater than minimum length value
        
    }//End of checking if minimum length value is provided
    
    return false;
    
}//End of function to validate whether control text value has length between the min and max value provided
//#endregion

//#region
//Function to validate text for specified regular expression and return error message if any
function ValidateRegularExpression(objAttr,cntrl)
{
    var cntrlValue=cntrl.value;
    
    var varValidationError="";
    
   //If loop-when Mytype is null
   if(objAttr.myType!=null)
   {
        var msg='';
        msg=ValidateControlText(objAttr,cntrlValue);
       if(msg != '')
       {
           //relace message to the placeholder.
          varValidationError = msg;
                  
       }     
      else
      {
         //Set style for textbox.  
         ResetControlStyle(cntrl);
      }
              
   }//end of if loop-when Mytype is null
   
   return varValidationError;
                            
} //End of ValidateRegulaeExpression function
//#endregion

//To check if at least one checkbox is checked
function ValidateCheckboxInGrid(Grid)
{
    var flg = false;
    var ErrorMessage = '';
    
    $(Grid).find('input[type = checkbox]').each(function()
    {
        if(this.checked)
        {
            flg = true;
        }
    });
   
    if(!flg)
    {
        var  notify =notifyError() ;
        notify.addText(msgM118);//Please select at least one record
        notify.display('messageContainer')
        return false;
    }
   
    return true;
}


////Function is used on client side validations
//adds messages to list
function AddErrorMsg(flag,ErrorList,divID)
{
 var ReturnFlag=true ;
 var  notify =notifyError() ;
if(flag)
{
notify.addText(msgM105);
ReturnFlag=false;
}
//adds invalid field msg in list

if(ErrorList.length>0)

{    var i=0;
    ReturnFlag=false;
    for(i=0 ;i<ErrorList.length;i++)
    {
       notify.addText(ErrorList[i]);
       
    }
}
flagRequiredField=false;
if(ReturnFlag)notify.EmptyError(divID)
else 
notify.display(divID);
return ReturnFlag;
}//End of AddErrorMsg

//Function is used on server side for validations
function AddErrorMessageFromServer(ErrorMessage,divID )
{ 
 var  notify =notifyError() ;
 var Errorlist=ErrorMessage.split(strSplitString);
if(Errorlist.length>0)
{
     for(i=0 ;i<Errorlist.length;i++)
        {
        if(Trim(Errorlist[i])!='')
           notify.addText(Trim(Errorlist[i]));
           
        }//End of for
     notify.display(divID);
 }//End of if
 else
 {
 notify.EmptyError(divID)
 }
}//End of AddErrorMessageFromServer
//--------------------------------------Custom-To be removed for other projets--------------------------------------------
//Added by anuprita
function CompareMinMax(ddlMin,ddlMax )
{
var MinValue=$('[id$='+ddlMin+']').val();
var MaxValue=$('[id$='+ddlMax+']').val();
if(MinValue!=FirstIndexMin)
{
MinValue=Trim(MinValue.replace(LAC,' '));
MinValue=Trim(MinValue.replace(Thousand,' '));
}
else
MinValue='';
if(MinValue!=FirstIndexMax)
{
MaxValue=Trim(MaxValue.replace(Thousand,' '));
MaxValue=Trim(MaxValue.replace(LAC,' '));
}
else
MaxValue='';
if(MinValue=='' || MaxValue=='')
return '';

if(parseInt(MinValue)<=parseInt(MaxValue))
return '';
else
return msgM116;
}

//Called on master page for search validation
function ValidateHomeSearch (IsResedential,spanID)
{
msg=''
if(IsResedential)
msg=CompareMinMax('ddlBudgetFrom','ddlBudgetTo')
else
msg=CompareMinMax('ddlBudgetFromCommercial','ddlBudgetToCommercial')
$('#'+spanID).attr('innerHTML',msg);

if(msg=='')
return true;
return false;
}//function ValidateHomeSearch


//Used to validate post requirement page
function ValidateRequirement(divID)
{

BudgetRangeMsg= CompareMinMax('ddlMinBudget','ddlMaxBudget');//Check if budget dropdown range is valid
var isValid=ValidateDiv(divID);//validate rest of the div
if(isValid && (BudgetRangeMsg==''))
return true;

if(BudgetRangeMsg!='')
{
if(!isValid)
AppendnotifyError('messageContainer',BudgetRangeMsg);
else
{
    var  notify =notifyError() ;
    notify.addText(BudgetRangeMsg);
    notify.display('messageContainer');
}
HighlightControl($('[id$=ddlMinBudget]')[0]);
HighlightControl($('[id$=ddlMaxBudget]')[0]);
}
return false;

}//End of ValidateRequirement(divID)

//function is used to validate Inquiry page
function ValidateInquiry(divToValidate,divMessage)
{
var isValid=ValidateDiv(divToValidate,divMessage);//validate rest of the div
if(!isValid)
 {
    var  notify =notifyError() ;
    notify.addText(msgM117);
    notify.display(divMessage);
    return false;
 }
return true;

}//End of ValidateInquiry()

