/*-------------------------------------------------------------------------------------------------------------------
*Name of file	: CommonJSFunctions.js
*Description	: Common JS that includes common functions for validation of fields
*Positioning	: Included in all JSPs with a script tag.
*Functions		: shiftFocusTo, testBlank, checkSpecialChar, isName, isBlank, checkPhone,
				  Trim, TrimLeft, TrimRight, matchPassword, changeModeValue, validData, 
				  insertHyphensGeneric, ZeroCheck, NumericCheck, DateValidate, fcompare
				  closeChildWindow
*Author			: TFA
*-------------------------------------------------------------------------------------------------------------------
*/

/*
 * The variable childWindow has been declared global, to be used by function closeChildWindow
 */

var childWindow = null;


/* This function shifts focus to specific field and selects it
 * Input Parameters : form element
 * Return Value : None
 */

function shiftFocusTo(field)
{
	
	field.focus();
	field.select();
}

// This function checks if a field is blank or not 


function testBlank(field)
{
	val = field.value;
	if ((val=="")||(val==null))
		{
			alert(field.tag+" cannot be blank");
			
			return false;
		}
	else
		return true;
}


/* This function checks for special characters in a field
 * Input Parameters : field value, tag name
 * Return Value :  true / false
 */

function checkSpecialChar(val,tag)
{
	rmexp = new RegExp("\[~!@#$%^*()&-+ ]"); 
	if(rmexp.test(val))
	{
		alert("Invalid "+tag+", "+tag+" cannot contain special characters or blank spaces.");
		return false;
	}
	else
		return true;
}

/* This function checks for special characters in a field
 * It doesnt makes a check for blank space.
 * Input Parameters : field value, tag name
 * Return Value :  true / false
 */

function checkSpecialCharAllowsBlank(val,tag)
{
	rmexp = new RegExp("\[~!@#$%^*()&-+]"); 
	if(rmexp.test(val))
	{
		alert("Invalid "+tag+", "+tag+" cannot contain special characters or blank spaces.");
		return false;
	}
	else
		return true;
}

/* This function checks for alphabets in a field
 * Input Parameters : field value
 * Return Value :  true / false
 */

function isName(str) 
{	var str1=Trim(str);
	var r2 = new RegExp("^[a-zA-Z ]{1,}$");
  	
	if(str == "")
	{
		return true;
	}
	else if(!r2.test(str1))
	{
	
	return false;
	}
	else
	 return true;
}

/* This function checks if a field is blank or not 
 * Input Parameters : field object, display name, message
 * Return Value :  true / false
 */


function isBlank(fld,displayName,message)
{
	if(message==null)
	message="On";
	if(Trim(fld.value)=="")
	{
		if(message=="On")
		{
		alert(displayName+" cannot be Blank");
		fld.select();
		fld.focus();
		}
	return false;
	}
else
return true;
}

/* This function checks for numeric value.
 * Input Parameters : field object, display name, message
 * Return Value :  true / false
 */

function NumericCheck(fld,txtfldname,message)
{
	if(message==null)
		message="On";
	if(isNaN(Trim(fld.value)-0))
	{
		
		// Check for : the field does not have numeric data entered
		if(message=="On")
		{
			alert("Invalid "+txtfldname+", "+txtfldname+" can have a numeric value only.");
			fld.focus();
			fld.select();
		}
		return false;
		
	}
	else
		return true;
}


/* This function checks format of an email field(abc@abc.com)
 * Input Parameters : field value
 * Return Value :  true / false
 */

function isEmail(str)
 {
  // are regular expressions supported?
  var supported = 0;
  if (window.RegExp) {
    var tempStr = "a";
    var tempReg = new RegExp(tempStr);
    if (tempReg.test(tempStr)) supported = 1;
  }
  if (!supported) 
    return (str.indexOf(".") > 2) && (str.indexOf("@") > 0);
  var r1 = new RegExp("(@.*@)|(\\.\\.)|(@\\.)|(^\\.)");
  var r2 = new RegExp("^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$");
  return (!r1.test(str) && r2.test(str));
}


/* This function checks if there is no other char other than - _ and . before @ 
 * and other than . after @ in email
 * Input Parameters : field value
 * Return Value :  true / false
 */

function yokoEmail(str)
{
	

	var len = str.length;
	
	var r3 = str.indexOf("@");
	
	
	
	var firstStr = str.substring(0,r3);
	
	var lastStr = str.substring(r3+1,len);
	

	if((firstStr.indexOf('{') != -1)||(firstStr.indexOf('}') != -1)||(firstStr.indexOf(',') != -1)||
	(firstStr.indexOf('?') != -1)||(firstStr.indexOf(':') != -1)||(firstStr.indexOf(';') != -1)||
	(firstStr.indexOf('>') != -1)||(firstStr.indexOf('<') != -1)||(firstStr.indexOf('=') != -1))
	{
		alert("Invalid Email, only Characters allowed are - and _");
		return false;
	}

	rmexp = new RegExp("\[~!@#$%^*()&+]"); 
	if(rmexp.test(firstStr))
	{
		alert("Invalid Email, only Characters allowed are - and _");
		return false;
	}

	if((lastStr.indexOf('{') != -1)||(lastStr.indexOf('}') != -1)||(lastStr.indexOf(',') != -1)||
	(lastStr.indexOf('?') != -1)||(lastStr.indexOf(':') != -1)||(lastStr.indexOf(';') != -1)||
	(lastStr.indexOf('>') != -1)||(lastStr.indexOf('<') != -1)||(lastStr.indexOf('_') != -1)
	||(lastStr.indexOf('-') != -1))
	{
		alert("Invalid Character Found after @");
		return false;
	}

	rmexp = new RegExp("\[~!@#$%^*()&+]"); 
	if(rmexp.test(lastStr))
	{
		alert("Invalid Character after @");
		return false;
	}
	
	else
		return true;
	
} 



/* This function checks format of a phone field(xxx-yyy-zzzz)
 * Input Parameters : field value, field name, display name
 * Return Value :  true / false
 */




function checkPhone(fldValue1,fldName,displayName)
{
	var fldValue=Trim(fldValue1);

	var r2 = new RegExp("^[0-9]{3}[-]{1}[0-9]{3}[-]{1}[0-9]{4}$");

	if(fldValue.length<12)
	{
		alert("Invalid "+displayName+", "+displayName+" can contain 10 digits only.");
		fldName.select();
		fldName.focus();	
		return false;	
	}

  	if(!r2.test(fldValue))
	{
		
		alert("Invalid "+displayName+", "+displayName+" can contain Numeric digits only, in format 111-111-1111.");
		fldName.select();
		fldName.focus();
		return false;
	}
		
	return true;
}

function Trim(str)
{
	var resultStr = "";
	resultStr = TrimLeft(str);
	resultStr = TrimRight(resultStr);
	return resultStr;
}//  end Trim

function TrimLeft(str)
{
	var resultStr = "";
	var i = len = 0;
	// Return immediately if an invalid value was passed in
	if (str+"" == "undefined" || str == null)	
		return null;
	// Make sure the argument is a string
	str += "";
	if (str.length == 0) 
		resultStr = "";
	else 
	{	
	// Loop through string starting at the beginning
	// as long as there are spaces.
		len = str.length;
		while ((i <= len) && (str.charAt(i) == " "))
			i++;
	
	//When the loop is done, we're sitting at the first non-space char,
	//so return that char plus the remaining chars of the string.
  		resultStr = str.substring(i, len);
  	}
  	return resultStr;
}//  end TrimLeft
			
function TrimRight(str)
{
	var resultStr = "";
	var i = 0;
	// Return immediately if an invalid value was passed in
	if (str+"" == "undefined" || str == null)	
		return null;
	// Make sure the argument is a string
	str += "";
	if (str.length == 0) 
		resultStr = "";
	else 
	{
		//Loop through string starting at the end
		//as long as there are spaces.
  		i = str.length - 1;
  		while ((i >= 0) && (str.charAt(i) == " "))
 			i--;
		//When the loop is done, we're sitting at the last non-space char,
		//so return that char plus all previous chars of the string.
	  	resultStr = str.substring(0, i + 1);
	  }
	  return resultStr;  	
}//  end TrimRight


function matchPassword(password,confirmPassword)
	{
		if (password.value != confirmPassword.value)
		{
			alert("Password and Confirm Password should have the same value.");
			return false;
 		}
	}


/* This function sets value of mode field
 * Input Parameters : form name, field value
 * Return Value :  None
 */

    
	
	 function changeModeValue(frmName,val)
    {
	alert(frmName);
	  frmName.mode.value = val;
    }	
       

   


/* This function checks if field is alphanumeric or not
 * Input Parameters : field value
 * Return Value :  true / false
 */

function validData(field,tagName)
{
	
	var ret = isNaN(field.value);
	
	if(ret==false)
	{
		
		alert("Invalid "+tagName+", "+tagName+" can have an AlphaNumeric value only.");	
		return false;
		 
	}
	else
		return true;
}


/* This function inserts hyphens in the format 111-111-1111
 * Input Parameters : field value
 * Return Value :  field value
 */

function insertHyphensGeneric(fldvalue)
{
	var phone=Trim(fldvalue);
	if(phone.length==3)
	{
		fldvalue=fldvalue+"-";
		return fldvalue;
	}

	if(phone.length==7)
	{
		fldvalue=fldvalue+"-";
		return fldvalue;
	}

	return fldvalue;
}

function insertSlashesGeneric(fldvalue)
{
	var dateField=Trim(fldvalue);
	if(dateField.length==2)
	{
		fldvalue=fldvalue+"/";
		return fldvalue;
	}

	if(dateField.length==5)
	{
		fldvalue=fldvalue+"/";
		return fldvalue;
	}

	return fldvalue;
}


/* This function checks for zero.
 * Input Parameters : field object, display name, message
 * Return Value :  true / false
 */

function ZeroCheck(fld,txtfldname,message)
{
	if(message==null)
		message = "On";
	if((Trim(fld.value)-0)<=0)
	{
		if(message=="On")
		{
			alert("Invalid "+txtfldname+", "+txtfldname+" should have a value greater than zero. ");
			fld.select();
			fld.focus();
		}
		return false;
	}
	return true;
}


//This function validates a date String in format mm/dd/yyyy 

function DateValidate(dateStr)
     {
	var month;
	var year;
	var day;
        
	if(dateStr=="")      
	{
		return true;
	}
	var datePat = /^(\d{1,2})(\/)(\d{1,2})\2(\d{4})$/;

	var matchArray = dateStr.match(datePat);//  is the format ok?
	if (matchArray == null)
	{
		alert("Date is not in a valid format. The valid format is MM/DD/YYYY.")
		return false;
	}
	month = matchArray[1];//  parse date into variables
	day = matchArray[3];
	year = matchArray[4];

	
	if(year=="0000")
	{
	alert("Year is not valid");
        
	return false;
	}
	
	if (month < 1 || month > 12)
	{ 
		// check month range
		alert("Month must be between 1 and 12.");
		return false;
	}
	if (day < 1 || day > 31) 
	{
		alert("Day must be between 1 and 31.");
		return false;
	}
	if ((month==4 || month==6 || month==9 || month==11) && day==31) 
	{
		alert("Month "+month+" doesn't have 31 days!");
		return false;
	}
	if (month == 2) 
	{// 	 check for february 29th
		var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
		if (day>29 || (day==29 && !isleap)) 
		{
		alert("February " + year + " doesn't have " + day + " days!");
		return false;
	   	}
	}
        dtret = fcompare(month,day,year);
        if (dtret == false)
        {
              alert("Delivery date cannot exceed today's date");
              return(false);
	}             
	return true;
     }   

    function fcompare(m,d,y)
    {
        date= new Date();
        var currentday = date.getDate();
      
        var currentmonth = date.getMonth()+1;
        
        var currentyear = date.getFullYear();
        
        if((y<currentyear)||((y == currentyear)&&(((m == currentmonth)&&(d<=currentday))||(m<currentmonth))))
             return true;
                 
        else
             return false; 
 
    }  


/*
 *	This function closes the catalog child window in case it is open.
 */

function closeChildWindow()
{
	if(childWindow=='[object]')
	{
		if(!(childWindow.closed))
		{
			childWindow.close();
		}
	}
}



/*
 *	This function formats a number to specfied places of decimals.Works for 1,2 and 3 places of decimals.
 * Input Parameters : number to be formatted, places of decimal
 * Return Value :  formatted number
 */


function formatNumber(numField,decimalIndex)
{
	if(numField!="")
	{
		index = numField.indexOf('.');
		if(index==-1)
			decimalPosition=-1;
		else
			decimalPosition = numField.length - index - 1;
	}
	if(decimalIndex==3)
	{
		if(decimalPosition == -1)
			numField = numField + ".000";
		else if(decimalPosition == 0)
			numField = numField + "000";
		else if(decimalPosition == 1)
			numField = numField + "00";
		else if(decimalPosition ==2)
			numField = numField + "0";
	}
	if(decimalIndex==2)
	{
		if(decimalPosition == -1)
			numField = numField + ".00";
		else if(decimalPosition == 0)
			numField = numField + "00";
		else if(decimalPosition == 1)
			numField = numField + "0";
	}
	if(decimalIndex==1)
	{
		if(decimalPosition == -1)
			numField = numField + ".0";
		else if(decimalPosition == 0)
			numField = numField + "0";
	}
	return numField;
}

/*
 *	This function checks whether the number is a Decimal Number. 
 * Input Parameters : number to be checked
 * Return Value :  true/false
 */

function checkDecimal(val)
{
	decimalIndex = val.indexOf('.');
		if(decimalIndex!=-1)
		{
			return false;
		}
		else return true;
}