/*****************************************
@  Author : George Abraham
@  Company : 
@  File : Form_Vaild.js
@  Functions : Functions for  checking  fields
@
@
*******************************************/

 lang = Array();
 lang['alert_inputdata'] = "Please Enter ";
 lang['alert_chkdata'] = "U dient akkoord te gaan met de "; // please check
 lang['alert_confirmdelete'] = 'Are You Sure to Delete';
 lang['alert_selecttodelete'] = 'Please Select One Item to Delete';
 lang['alert_selecttoedit'] = 'Please Select One Item to Edit';

 function popupWindow(url) {
  window.open(url,'popupWindow','toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=yes,copyhistory=no,width=100,height=100,screenX=150,screenY=150,top=150,left=150')
}

// validates that the entry is formatted as an email address
function isEMailAddr(elem) {
    var str = elem.value;
    var re = /^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]{2,7}$/;
    if (!str.match(re)) 
        return false;
    else 
        return true;
}

function isAlphaValue(str)
{
	var re = /^[a-zA-Z\s]+$/;
    if (!str.match(re)) 
        return false;
    else 
        return true;

}
function Validate_Form_Objects(frm, fieldRequired,fieldEmail,fieldConfirm,fieldNumeric)
  {
	if(!(fieldConfirm)) fieldConfirm = Array ();
	if(!(fieldEmail)) fieldEmail = Array();	
	if(!(fieldNumeric)) fieldNumeric = Array();	
	
    var alertMsg =  lang['alert_inputdata'];
   	var l_Msg = alertMsg.length;
	var e = / /g;
   	for (var i = 0; i < fieldRequired.length; i++)
   	{
  		var obj = frm.elements[fieldRequired[i]];
   		if (obj)
       		{
            	switch(obj.type)
        		{
               	case "select-one":
                				if (obj.selectedIndex == -1 || obj.options[obj.selectedIndex].text == "" || obj.options[obj.selectedIndex].value == "" || obj.options[obj.selectedIndex].value == '-')
                    					alertMsg += "  " + obj.title + "\n";
								obj.focus();		
                   				break;
       			case "select-multiple":
                    			if (obj.selectedIndex == -1)
                        					alertMsg += "  " + obj.title  + "\n";
								obj.focus();					
                        		break;
                case "text":
								var temp_value = obj.value.replace(e,"");
								if (temp_value.length == 0 || obj.value == null)
                         					alertMsg += "  " + obj.title + "\n";
								obj.focus();					
								break;
                case "password":
                        		var temp_value = obj.value.replace(e,"");
								if (temp_value.length == 0 || obj.value == null)
                         					alertMsg += "  " + obj.title + "\n";
								obj.focus();				
								break;
                
				case "textarea":
                        		var temp_value = obj.value.replace(e,"");
								if (temp_value.length == 0 || obj.value == null)
                         					alertMsg += "  " + obj.title + "\n";
								obj.focus();					
                   				break;
                   				// START madalina@novisites.nl July 26, 2006                   				
                case "checkbox": 
					if (!obj.checked)
             			alertMsg = lang['alert_chkdata'] +"  " + obj.title + "\n";
					obj.focus();	
                	break;
                // END madalina@novisites.nl July 26, 2006       
				case "undefined":
								var temp_value = obj.value.replace(e,"");
								if (temp_value.length == 0 || obj.value == null)
                         					alertMsg += "  " + obj.title  + "\n";
								obj.focus();					
								break;				
                }   

			
				if (alertMsg.length != l_Msg)
				{
					alert(alertMsg);
					obj.focus();
					return false;
				}	
		} // END IF (obj)
  	} // END FOR
	
	if (alertMsg.length == l_Msg)
   	{
		
		// Email Validation 
		for (var i = 0; i < fieldEmail.length; i++)
	   	{
  			var obj = frm.elements[fieldEmail[i]];
			if (obj)
			{
//			  if(obj.length < 5 || obj.value.indexOf("@")==-1 || obj.value.indexOf(".")==-1 || (obj.value.indexOf(".")- obj.value.indexOf("@")) <= 2)
			  		if(!isEMailAddr(obj))
			  		{
				 		var alertEmail = obj.title + ' not seems valid ';
						alert(alertEmail);
						obj.focus();
			   			return false;
					 }
			}	// END IF obj
		} // END IF FOR
		
	   // Password Confirmation 
		for (var i = 0; i < fieldConfirm.length; i++)
	   	{
			var obj1 = frm.elements[fieldConfirm[i]];
			var obj2 = frm.elements[fieldConfirm[i+1]];
			if (obj1 && obj2)
			{
			 if(obj1.value != obj2.value)
			  {
				 		alertConfirm  = obj1.title + " and " + obj2.title +" Not Matching";
						alert(alertConfirm);
						obj1.focus();
			 			return false;
			  } // END IF obj1.value
			} // END IF obj1
		} // END IF FOR	
		
	
	   /************ Numeric Validation ************/
		for (var i = 0; i < fieldNumeric.length; i++)
	   	{
  			var obj = frm.elements[fieldNumeric[i]];
			if (obj)
			{
			  if(isNaN(obj.value))
			  		{
						alert('Enter A Numeric Value');
						obj.focus();
			   			return false;
					 }
			}	// END IF obj
		} // END IF FOR
		// fields that must contain only letter
		
		if(Validate_Form_Objects.arguments.length > 5)
		{
			var fieldAlpha = Validate_Form_Objects.arguments[5];
			for (var i = 0; i < fieldAlpha.length; i++)
		   	{
	  			var obj = frm.elements[fieldAlpha[i]];
				if (obj)
				{
				  if(!isAlphaValue(obj.value))
				  		{
							alert(obj.title + ' must contain only letters');
							obj.focus();
				   			return false;
						 }
				}	// END IF obj
			} // END IF 
			if(Validate_Form_Objects.arguments.length > 6)
			{
				var fieldOneDigit = Validate_Form_Objects.arguments[6];
				for (var i = 0; i < fieldOneDigit.length; i++)
			   	{
		  			var obj = frm.elements[fieldOneDigit[i]];
					if (obj)
					{
					  if(!obj.value.match(/^.*\d+.*$/))
					  		{
								alert(obj.title + ' must contain at least one digit');
								obj.focus();
					   			return false;
							 }
					}	// END IF obj
				} // END IF 
			}
		}
		return true;	
  	 } // END IF (alertMsg.length == l_Msg)
	else
 	{
		alert(alertMsg);
   		return false;
   	}
}

// END



function Validate_GenForm_Objects(frm, fieldRequired,fieldMessge,fieldEmail,fieldConfirm,fieldNumeric)
  {
	if(!(fieldConfirm)) fieldConfirm = Array ();
	if(!(fieldEmail)) fieldEmail = Array();	
	if(!(fieldNumeric)) fieldNumeric = Array();	
	
    var alertMsg =  " ";
   	var l_Msg = alertMsg.length;
	var e = / /g;
   	for (var i = 0; i < fieldRequired.length; i++)
   	{
  		var obj = frm.elements[fieldRequired[i]];
   		if (obj)
       		{
            	switch(obj.type)
        		{
               	case "select-one":
                				if (obj.selectedIndex == -1 || obj.options[obj.selectedIndex].text == "" || obj.options[obj.selectedIndex].value == "")
                    					alertMsg += "  " + fieldMessge[i] + "\n";
								obj.focus();		
                   				break;
       			case "select-multiple":
                    			if (obj.selectedIndex == -1)
                        					alertMsg += "  " + fieldMessge[i]  + "\n";
								obj.focus();					
                        		break;
                case "text":
								var temp_value = obj.value.replace(e,"");
								if (temp_value.length == 0 || obj.value == null)
                         					alertMsg += "  " + fieldMessge[i] + "\n";
								obj.focus();					
								break;
                case "password":
                        		var temp_value = obj.value.replace(e,"");
								if (temp_value.length == 0 || obj.value == null)
                         					alertMsg += "  " + fieldMessge[i] + "\n";
								obj.focus();				
								break;
                
				case "textarea":
                        		var temp_value = obj.value.replace(e,"");
								if (temp_value.length == 0 || obj.value == null)
                         					alertMsg += "  " + fieldMessge[i] + "\n";
								obj.focus();					
                   				break;
				case "undefined":
								var temp_value = obj.value.replace(e,"");
								if (temp_value.length == 0 || obj.value == null)
                         					alertMsg += "  " + fieldMessge[i]  + "\n";
								obj.focus();					
								break;				
                }   

			
				if (alertMsg.length != l_Msg)
				{
					alert(alertMsg);
					obj.focus();
					return false;
				}	
		} // END IF (obj)
  	} // END FOR
	
	if (alertMsg.length == l_Msg)
   	{
		
		// Email Validation 
		for (var i = 0; i < fieldEmail.length; i++)
	   	{
  			var obj = frm.elements[fieldEmail[i]];
			if (obj)
			{
			  if(obj.length < 5 || obj.value.indexOf("@")==-1 || obj.value.indexOf(".")==-1)
			  		{
				 		var alertEmail = obj.title + ' is ongeldig ';
						alert(alertEmail);
						obj.focus();
			   			return false;
					 }
			}	// END IF obj
		} // END IF FOR
		
	   // Password Confirmation 
		for (var i = 0; i < fieldConfirm.length; i++)
	   	{
			var obj1 = frm.elements[fieldConfirm[i]];
			var obj2 = frm.elements[fieldConfirm[i+1]];
			if (obj1 && obj2)
			{
			 if(obj1.value != obj2.value)
			  {
				 		alertConfirm  = obj1.title + " and " + obj2.title +" Not Matching";
						alert(alertConfirm);
						obj1.focus();
			 			return false;
			  } // END IF obj1.value
			} // END IF obj1
		} // END IF FOR	
		
	
	   /************ Numeric Validation ************/
		for (var i = 0; i < fieldNumeric.length; i++)
	   	{
  			var obj = frm.elements[fieldNumeric[i]];
			if (obj)
			{
			  if(isNaN(obj.value))
			  		{
						alert('Enter A Numeric Value');
						obj.focus();
			   			return false;
					 }
			}	// END IF obj
		} // END IF FOR
		
		return true;	
  	 } // END IF (alertMsg.length == l_Msg)
	else
 	{
		alert(alertMsg);
   		return false;
   	}
}

// END

function popInternal(control,destn,uniqueid)
{
 	windowURL = 'docUpload/image.php?objname='+control+'&destn='+destn+'&uniqueid='+uniqueid;
 	if(popInternal.arguments.length > 3)
 		windowURL += '&objid=' + popInternal.arguments[3];
	windowFeatures = 'top=100,left=100,width=660,height=600';
	windowName = 'upload';
	var wnd = window.open(windowURL, windowName, windowFeatures);
	wnd.focus();
	return false; 
}

function imgUpload(control,destn,uniqueid)
{
   // windowURL = 'imgupload.php?control='+control+'&destn='+destn+'&uniqueid='+uniqueid;
    windowURL = 'imgUpload/image.php?objname='+control+'&destn='+destn+'&uniqueid='+uniqueid;
	windowFeatures = 'top=100,left=100,width=660,height=600';
	windowName = 'upload';
	 var wnd = window.open(windowURL, windowName, windowFeatures);
	 wnd.focus();
	 return false; 
}



function delConfirm(selectID)
{
 var found_it;
 selectID = eval(selectID);
 if (selectID.checked)  {
		found_it = selectID.value
 }
 for (var i=0; i<selectID.length; i++)  {
	 if (selectID[i].checked)  {
		found_it = selectID[i].value
	}
 }

  if(found_it > 0 || found_it != "")
  	return confirm(lang['alert_confirmdelete']);
  else  {
    alert(lang['alert_selecttodelete']);
	return false;
   }
   return true;	
}


function selEdit(selectID)
{
 var found_it;
 selectID = eval(selectID);
 if (selectID.checked)  {
		found_it = selectID.value;
	 }
 for (var i=0; i<selectID.length; i++)  {
	 if (selectID[i].checked)  {
		found_it = selectID[i].value;
	}
 }
  if(found_it > 0 || found_it != "")
  	return true;
  else  {
    alert(lang['alert_selecttoedit']);
	return false;
   }
}


function imgRemove(imgUpload,uploadUrl)
{
  
  var remImage = eval(imgUpload+'_rem');
  var imgUpload2 = eval(imgUpload+'_img');
  document.getElementById(imgUpload).value='';
  document.getElementById(imgUpload2).src= uploadUrl+'spacer.gif';
  document.imgUpload.width='0';
  document.imgUpload.height='0';
  document.remImage.src = uploadUrl+'spacer.gif';
}


// function to open a new window
function openWin(windowURL, windowName, windowFeatures)
{ 
	 var wnd = window.open(windowURL, windowName, windowFeatures);
	 wnd.focus();
	 return false; 
}

// to simulate the clicking of the browser back button
function fn_back()
{
	window.history.back();
}	


// function to check indiger field
function IsInteger(snum)
{
	var reInteger = /^\d+$/
    return reInteger.test(snum)
}

// Check whether string s is empty.
function isEmpty(s)
{   
	return ((s == null) || (s.length == 0) || (s.substr(0,1) == " "))
}

function isEmail (p_sEmail)
{
 var regEmail = /^[\w-]+(?:\.[\w-]+)*@(?:[\w-]+\.)+[a-zA-Z]{2,7}$/;
 return regEmail.test (p_sEmail);
}

function isUser (p_sUser)
{
 var regUser = /^[0-9a-zA-Z_]{4,16}$/;
 return regUser.test (p_sUser);
}

// function to check Price value ( with two decimal places )
function isPrice(s)
{  
	var reFloat = /^[\d\.]((\d+(\.\d{0,2})?)|((\d*\.)?\d{0,2}))$/	
	return reFloat.test(s)	   	
}

// function to check float/decimal fileds
function isFloat(s)
{  
	var reFloat = /^((\d+(\.\d*)?)|((\d*\.)?\d+))$/	
	return reFloat.test(s)	   	
}

// function to check username fields
function usernameCheck (s)
{
  // this is done to avoid any special characters
  var reUsername = /^[a-zA-Z0-9][a-zA-Z0-9_]*$/
  
  if (isEmpty(s))
  {
  	 alert("Please enter a  Username. Minimum 8 characters.\n No spaces, blanks or special characters , except '_'.");
	 return false; 
  } 
  else
  {
   	 var matchArray = s.match(reUsername); // is the format ok? 
	 if (matchArray == null) 
	 { 
		alert("Username should contain only \n alphabets, digits or underscore '_'.\n '_' should not be the first character.");
		return false; 
	 }	 	
	 else
	 { 
	  	 if(s.length<8){		
			alert("Username should be minimum of 8 characters");	
			return false; 
			 }	
     }			
  }      	 
  return true;
}

// function to check username fields
function passwordCheck (s)
{
  // this is done to avoid any special characters
  var rePassword = /^[a-zA-Z0-9][a-zA-Z0-9~!@#$%^&*()]*$/
  
  if (isEmpty(s))
  {
  	 alert("Please enter a desired Password. Minimum 8 characters.\nNo spaces and blanks allowed.");
	 return false; 
  } 
  else
  {
   	 var matchArray = s.match(rePassword); // is the format ok? 
	 if (matchArray == null) { 
		alert("Password should contain only alphabets, digits\nor only these special characters ~!@#$%^&*()$\nbut not the first character.");
		return false; 
	 }	 	
	 else{ 
	  	 if(s.length<8){		
			alert("Password should be minimum of 8 characters");	
			return false; 
		 }	
	 }			
  }      	 
  return true;
}
	



function emailCheck(emailStr) {

	var emailPat=/^(.+)@(.+)$/

	var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]"

	var validChars="\[^\\s" + specialChars + "\]"

	var quotedUser="(\"[^\"]*\")"

	var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/

	var atom=validChars + '+'

	var word="(" + atom + "|" + quotedUser + ")"

	// The following pattern describes the structure of the user
	var userPat=new RegExp("^" + word + "(\\." + word + ")*$")

	/* The following pattern describes the structure of a normal symbolic
	   domain, as opposed to ipDomainPat, shown above. */
	var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$")
	

	/* Begin with the coarse pattern to simply break up user@domain into
	   different pieces that are easy to analyze. */
	var matchArray=emailStr.match(emailPat)
	if (matchArray==null) {
	  /* Too many/few @'s or something; basically, this address doesn't
	     even fit the general mould of a valid e-mail address. */
		alert("Email address seems incorrect (check @ and .'s)")
		return false
	}
	var user=matchArray[1]
	var domain=matchArray[2]
	
	// See if "user" is valid 
	if (user.match(userPat)==null) {
	    // user is not valid
	    alert("The username doesn't seem to be valid.")
	    return false
	}
	
	/* if the e-mail address is at an IP address (as opposed to a symbolic
	   host name) make sure the IP address is valid. */
	var IPArray=domain.match(ipDomainPat)
	if (IPArray!=null) {
	    // this is an IP address
		  for (var i=1;i<=4;i++) {
		    if (IPArray[i]>255) {
		        alert("Destination IP address is invalid!")
			return false
		    }
	    }
	    return true
	}
	
	// Domain is symbolic name
	var domainArray=domain.match(domainPat)
	if (domainArray==null) {
		alert("The Domain Name doesn't seem to be valid.")
	    return false
	}
	
	/* Now we need to break up the domain to get a count of how many atoms
	   it consists of. */
	var atomPat=new RegExp(atom,"g")
	var domArr=domain.match(atomPat)
	var len=domArr.length
	if (domArr[domArr.length-1].length<2 || 
	    domArr[domArr.length-1].length>3) {
	   // the address must end in a two letter or three letter word.
	   alert("The address must end in a three-letter domain, or two letter country.")
	   return false
	}
	
	// Make sure there's a host name preceding the domain.
	if (len<2) {
	   var errStr="This E-mail address is missing a hostname!"
	   alert(errStr)
	   return false
	   }
	   // If we've gotten this far, everything's valid!
	return true	   
}
// end o

function doprint() {
	window.open(printURL,'print','width=600,height=600');
}	

function isValidEmail(sValue)
{
	var re = /^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]{2,7}$/;
    if (!sValue.match(re))
        return false;
    return true;
}


function checkTellAFriendForm(oForm)
{
	var bRet = true, oElem;
	for(var i=0; i<oForm.elements.length; i++)
	{
		oElem = oForm.elements[i];
		if(oElem.type != 'text') continue;
		document.getElementById(oElem.name + 'Err').style.display = "none";
		if(oElem.tagName.toLowerCase() == 'input' && !oElem.value)
		{
			document.getElementById(oElem.name + 'Err').style.display = "inline";
			bRet = false;
		}
		if(oElem.name.indexOf('Email') != -1 && !isValidEmail(oElem.value))
		{
			document.getElementById(oElem.name + 'Err').style.display = "inline";
			bRet = false;
		}
	}
	return bRet;
}
