/* 
*  Script contains definition of the javascript functions for client-side 
*  validation of the web forms. 
*  To validate your web form initialize the array of validator objects (see Validator declaration below),
*  and set onSubmit event handler of your form to validateForm function passing the array as an argument.
*/ 

/*
*  Validator object declaration. Contains an ID of the document element being tested with test string expression.  
*  Test expression should be "key=value" formatted and compatible with validateData function requirements
*/
function Validator(elementID, test, message) {
    this.elementID = elementID;
    this.test = test;
    this.message = message;
}

/* function validateData 
*  Checks each field in a form 
*  Called from validateForm function 
*/ 
function validateData(objValue,strValidateStr,strError) 
{ 
    var epos = strValidateStr.search("="); 
    var  command  = ""; 
    var  cmdvalue = ""; 
    if(epos >= 0) 
    { 
     command  = strValidateStr.substring(0,epos); 
     cmdvalue = strValidateStr.substr(epos+1); 
    } 
    else 
    { 
     command = strValidateStr; 
    } 

    switch(command) 
    { 
        case "req": 
        case "required": 
        { 
           if(eval(objValue.value.length) == 0) 
           { 
              if(!strError || strError.length ==0) 
              { 
                strError = objValue.name + " : Required Field"; 
              }//if 
              alert(strError); 
              return false; 
           }//if 
           break;             
        }//case required 
        case "maxlength": 
        case "maxlen": 
        { 
             if(eval(objValue.value.length) >  eval(cmdvalue)) 
             { 
               if(!strError || strError.length ==0) 
               { 
                 strError = objValue.name + " : "+cmdvalue+" characters maximum "; 
               }//if 
               alert(strError + "\n[Current length = " + objValue.value.length + " ]"); 
               return false; 
             }//if 
             break; 
        }//case maxlen 
        case "minlength": 
        case "minlen": 
           { 
             if(eval(objValue.value.length) <  eval(cmdvalue)) 
             { 
               if(!strError || strError.length ==0) 
               { 
                 strError = objValue.name + " : " + cmdvalue + " characters minimum  "; 
               }//if               
               alert(strError + "\n[Current length = " + objValue.value.length + " ]"); 
               return false;                 
             }//if 
             break; 
            }//case minlen 
        case "alnum": 
        case "alphanumeric": 
           { 
              var charpos = objValue.value.search("[^A-Za-z0-9]"); 
              if(objValue.value.length > 0 &&  charpos >= 0) 
              { 
               if(!strError || strError.length ==0) 
                { 
                  strError = objValue.name+": Only alpha-numeric characters allowed "; 
                }//if 
                alert(strError + "\n [Error character position " + eval(charpos+1)+"]"); 
                return false; 
              }//if 
              break; 
           }//case alphanumeric 
        case "num": 
        case "numeric": 
           { 
              var charpos = objValue.value.search("[^0-9]"); 
              if(objValue.value.length > 0 &&  charpos >= 0) 
              { 
                if(!strError || strError.length ==0) 
                { 
                  strError = objValue.name+": Only digits allowed "; 
                }//if               
                alert(strError + "\n [Error character position " + eval(charpos+1)+"]"); 
                return false; 
              }//if 
              break;               
           }//numeric 
        case "alphabetic": 
        case "alpha": 
           { 
              var charpos = objValue.value.search("[^A-Za-z]"); 
              if(objValue.value.length > 0 &&  charpos >= 0) 
              { 
                  if(!strError || strError.length ==0) 
                { 
                  strError = objValue.name+": Only alphabetic characters allowed "; 
                }//if                             
                alert(strError + "\n [Error character position " + eval(charpos+1)+"]"); 
                return false; 
              }//if 
              break; 
           }//alpha 
        case "phone":
          { 
               if(!validatePhone(objValue.value)) 
               { 
                 if(!strError || strError.length == 0) 
                 { 
                    strError = objValue.name+": Enter a valid Phone number "; 
                 }//if                                               
                 alert(strError); 
                 return false; 
               }//if 
           break; 
          }//case phone 
        case "email": 
          { 
               if(!validateEmail(objValue.value)) 
               { 
                 if(!strError || strError.length ==0) 
                 { 
                    strError = objValue.name+": Enter a valid Email address "; 
                 }//if                                               
                 alert(strError); 
                 return false; 
               }//if 
           break; 
          }//case email 
        case "lt": 
        case "lessthan": 
         { 
            if(isNaN(objValue.value)) 
            { 
              alert(objValue.name+": Should be a number "); 
              return false; 
            }//if 
            if(eval(objValue.value) >=  eval(cmdvalue)) 
            { 
              if(!strError || strError.length ==0) 
              { 
                strError = objValue.name + " : value should be less than "+ cmdvalue; 
              }//if               
              alert(strError); 
              return false;                 
             }//if             
            break; 
         }//case lessthan 
        case "gt": 
        case "greaterthan": 
         { 
            if(isNaN(objValue.value)) 
            { 
              alert(objValue.name+": Should be a number "); 
              return false; 
            }//if 
             if(eval(objValue.value) <=  eval(cmdvalue)) 
             { 
               if(!strError || strError.length ==0) 
               { 
                 strError = objValue.name + " : value should be greater than "+ cmdvalue; 
               }//if               
               alert(strError); 
               return false;                 
             }//if             
            break; 
         }//case greaterthan 
        case "regexp": 
         { 
            if(!objValue.value.match(cmdvalue)) 
            { 
              if(!strError || strError.length ==0) 
              { 
                strError = objValue.name+": Invalid characters found "; 
              }//if                                                               
              alert(strError); 
              return false;                   
            }//if 
           break; 
         }//case regexp 
        case "dontselect": 
         { 
            if(objValue.selectedIndex == null) 
            { 
              alert("BUG: dontselect command for non-select Item"); 
              return false; 
            } 
            if(objValue.selectedIndex == eval(cmdvalue)) 
            { 
             if(!strError || strError.length ==0) 
              { 
              strError = objValue.name+": Please Select one option "; 
              }//if                                                               
              alert(strError); 
              return false;                                   
             } 
             break; 
         }//case dontselect 
    }//switch 
    return true; 
} 

/* 
* function validateForm 
* the function that can be used to validate any form 
* returns false if the validation fails; true if success 
* arguments : 
*   arrValidators : an array of Validator objects describing the validations to conduct on each 
*        input item. See Validator object declaration.
*
*/ 

function validateForm() 
{ 
    try {
        var count = arrValidators.length;
    } catch(e) {
        // if arrValidators is not defined return true
        // alert("Validators array is not defined");
        return true;
    } 

    var result = false;
    for(var i = 0; i < count; i++) 
    { 
        var validator = arrValidators[i];
        var element = document.getElementById(validator.elementID);
        if(element != null) {
            if(validateData(element, validator.test, validator.message) == false) 
            { 
                element.focus();
                return false; 
            }
        }
    }
    return true;
}

/*  checks the validity of an email address entered 
*   returns true or false 
*/ 
function validateEmail(email)
{
	// if email is empty string do not validate it, return true
	if(email == '') {
		return true;
	}

    var splitted = email.match("^(.+)@(.+)$");
    if(splitted == null) return false;
    if(splitted[1] != null )
    {
      var regexp_user=/^\"?[\w-_\.]*\"?$/;
      if(splitted[1].match(regexp_user) == null) return false;
    }
    if(splitted[2] != null)
    {
      var regexp_domain=/^[\w-\.]*\.[A-Za-z]{2,4}$/;
      if(splitted[2].match(regexp_domain) == null) 
      {
        var regexp_ip =/^\[\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\]$/;
        if(splitted[2].match(regexp_ip) == null) return false;
      }// if
      return true;
    }
return false;
}

/*  checks the validity of an phone number entered 
*   returns true or false 
*/ 
function validatePhone(phone)
{
    
	// if phone is empty string, do not check, return true 
	if(phone == '') {
		return true;
	}
    // check alpha-chars
    var re = /[A-Za-z_\!\|\:\,]+/g;
    if(phone.match(re)) {
		return false;
    }	
    // check non-digit
    re = /\D+/g;
    var result = phone.replace(re, '');
    if(!result.match(/^\d{7,}$/)) 
    {
        alert('Phone number has less than 7 digits');
        return false;
    }
    return true;
}



/*  checks to see how many banners the user is trying to publish 
*   returns true or false 
*/
function validateBannerCheckboxes(form) {
	var checkcount = 0;
	
	for (var i = 0; i < form.elements.length; i++) {   
		var el = form.elements[i];

		if (el.type == "checkbox") {
			if (el.checked)	{
				checkcount++;
			}  
		}
	}
	
	if(checkcount == 0) {
		alert("You have not selected any banners to publish.");
		return false;
	}
	
	if(checkcount > 3) {
		alert("You have selected more than the maximum of three banners that you may publish.");
		return false;
	}
	

	return true;
}

/*  makes user confirm deletion of an image
*   returns true or false 
*/
function confirmDeleteImage() {
	if(confirm("Delete this image? Are you sure?")) {
		return true;
	}
	return false;
}
