/*
----------------------------------------------------------
Page Name	    :	CommonValidation.js
Type		    :	Javasciprt file
*/

var gSendToServer = 0 // 0 in dev, 1 in QA and Live (0 in QA for JavaScript Testing)
var msg_common_required = "Data Required."
var msg_common_allspaces = "Invalid Entry-this field must contain at least one character."
var msg_common_email = "Enter Valid E-mail format(abc@abc.com)."
var msg_common_phone = "Enter valid phone number."
var msg_reports_validmonth = "Enter a valid month"
var msg_reports_validday = "Enter a valid day"
var msg_common_DateFromGreaterDateTo = "End Date must be equal to or greater than the Start Date."
var msg_common_Party = "Select a Party."
var msg_common_PartyName = "Party Name Required."
var msg_common_invalidchars = "Invalid Entry - this field contains invalid characters < (or) >."
var msg_common_state = "Select a State."
var msg_common_zip = "Invalid Entry-Enter valid Postal code."
var msg_common_fax = "Enter valid Fax number."
var msg_common_country = "Select a Country."
var msg_common_Hostess = "Select a Hostess."
var msg_common_customer = "Select a Customer."
var msg_common_validconfirmPwd = "Your password entries didn't match."
var msg_Common_validid = "Enter valid ID."
var msg_common_creditcardexpmonth = "Select expiration month."
var msg_common_creditcardtype = "Select a Card Type."
var msg_common_creditcardexpyear = "Select expiration year."
var msg_common_cardexpired = "Your Card has expired."
var msg_common_daterequired = "Date Required."
var msg_common_invaliddate = "Invalid Date."
var msg_common_LoginName_InvalidCharacters = "Login Name contains invalid characters."
var msg_common_LoginName_InvalidNumberOfCharecters = "SignIn Name must have minimum 4 characters."
var msg_common_Partydate="Invalid Entry-Enter Valid Date of Party."
var msg_common_Partydatemonth="Month must be between 1 and 12."
var msg_common_ValidDay = "Invalid Entry-Enter valid Day."
var msg_common_ValidMonth = "Invalid Entry-Enter valid Month."  
var msg_common_Hours_required = "Hours Required."
var msg_common_Minutes_required = "Minutes Required."
var msg_common_Party_required = "Party Name Required."
var msg_common_Event_required = "Event Name Required."
var msg_common_Notes_required = "Notes Required."
var msg_common_Eventdate="Invalid Entry-Enter Valid Date of Event."

var msg_common_Message="Message Required."
             
var msg_common_americanexpresscardnumber = "Invalid Entry-Enter a valid American Express card number."
//var msg_common_discoverycardnumber = "Invalid Entry-Enter a valid Discovery card number."
var msg_common_discoverynumber = "Invalid Entry-Enter a valid Discover card number."
var msg_common_mastercardnumber = "Invalid Entry-Enter a valid Master card number."
var msg_common_visacardnumber = "Invalid Entry-Enter a valid Visa card number."
var msg_common_validcreditcardnumber = "Invalid Entry-Enter a valid credit card number."
var message_common_id = "ID Required"
var message_common_zip = "Postal Code required."
var message_common_firstname = "First Name Required"
var message_common_lastname = "Last Name Required"
var message_common_address = "Address Required"
var message_common_city = "City Required"
var message_common_phoneno = "Phone Number required"
var message_common_loginname = "Login Name Required"
var message_common_password = "Password Required"
var message_common_nameoncard = "Enter the Name on the Card"
var message_common_sitename = "Site Name Required"
var message_common_contactname = "Site Contact Name Required"
var message_common_emailid = "Email ID Required"
var msg_common_creditcardrequired ="Card Number Required."
var message_common_confirmpwd = "Re-type The Password"
var msg_common_FromAmountrequired = "From amount required." 
var msg_common_ToAmountrequired = "To amount required."
var msg_common_InvalidDateRange = "From-Date cannot be higher than To-Date"
var msg_common_InvalidAmountRange = "From amount must be less than To amount."
var msg_common_NumberRequired= "Number Required."
var msg_common_Extension = "Enter valid Extension."
var msg_signup_donotstartwithnumber="Signin Name can not start with number."
var msg_signup_signinminimumcharacters="SignIn Name must have minimum 4 characters."
var msg_common_signinname="SignIn Name contains invalid characters."


var msg_common_SelectOneOption="Select One Option."
var msg_common_SelectOneCheckBox="Select One CheckBox."
var msg_common_integeronly ="Invalid Entry-this field must contain integer value."
var msg_common_validstateabbr="Enter valid State Abbreviation!";
var msg_common_SpaceBetweenNameNotAllowed="Space between Name not allowed.";
var msg_common_SpaceBetweenCityNameNotAllowed="Space between City Name not allowed.";

//Manage AttributeCategory
var msg_common_AttributeCategory = "Select a Attribute Category.";

//Product management

var msg_producttype_producttype = "Select a product type."
var msg_RPT_productName = "Select a product Name."
var msg_ManageProductType_selectoneoptiondistributororcustomer = "Select one option distributor (or) customer."
var msg_product_price = "Invalid Entry-this field must contain a numeric value from 0.01 to 99999999.99(maximum 2 decimal places)."
var msg_product_price_diff = "Wholesale price should be less than Ratail price."
var msg_product_cv = "Invalid Entry-this field must contain a numeric value from 0.01 to 99999999.99(maximum 2 decimal places)."
var msg_product_weight = "Invalid Entry-this field must contain a numeric value from 0.0001 to 9999.9999(maximum 4 decimal places)."
var msg_producttype_PackageUnit = "Select Package Unit."

/*
//--Global Expression Variables declaration Section Starts-

*/

var regExpEmail = /^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/
var regExpRouting = /^\d{9}$/
var regExpAccount = /^\d{1,16}$/			 
//var regExpDL = /^\w{1,20}$/ 
var regExpDOB = /^((^(10|12|0?[13578])([/])(3[01]|[12][0-9]|0?[1-9])([/])((1[8-9]\d{2})|([2-9]\d{3}))$)|(^(11|0?[469])([/])(30|[12][0-9]|0?[1-9])([/])((1[8-9]\d{2})|([2-9]\d{3}))$)|(^(0?2)([/])(2[0-8]|1[0-9]|0?[1-9])([/])((1[8-9]\d{2})|([2-9]\d{3}))$)|(^(0?2)([/])(29)([/])([2468][048]00)$)|(^(0?2)([/])(29)([/])([3579][26]00)$)|(^(0?2)([/])(29)([/])([1][89][0][48])$)|(^(0?2)([/])(29)([/])([2-9][0-9][0][48])$)|(^(0?2)([/])(29)([/])([1][89][2468][048])$)|(^(0?2)([/])(29)([/])([2-9][0-9][2468][048])$)|(^(0?2)([/])(29)([/])([1][89][13579][26])$)|(^(0?2)([/])(29)([/])([2-9][0-9][13579][26])$))$/
var regExpLoginName = /^([a-zA-Z0-9_.-]{4,20})$/
var regExpLastName = /^([a-zA-Z0-9_.-]{2,20})$/
var regBirthMonth = /^\d{1,2}$/
var regBirthDate = /^\d{1,2}$/

var dtCh = "/";
var minYear = 2001;
var maxYear = 2050;


function Trim(str)
{
	return RTrim(LTrim(str));
}

function LTrim(str)	
{
	var whitespace = new String(" \t\n\r "); 
	var s = new String(str);
	if (whitespace.indexOf(s.charAt(0)) != -1) 
	{
		var j=0, i = s.length;
		while (j < i && whitespace.indexOf(s.charAt(j)) != -1)
			j++;
			s = s.substring(j, i);
	}
	return s;
}
		

function RTrim(str)
{
	var whitespace = new String(" \t\n\r "); 
	var s = new String(str);
	if (whitespace.indexOf(s.charAt(s.length-1)) != -1) 
	{
		var i = s.length - 1;      
		while (i >= 0 && whitespace.indexOf(s.charAt(i)) != -1)
			i--;
			s = s.substring(0, i+1);
	}
	return s;
}
	


function isEmptyAfterTrim(s)
{
	if (Trim(s) == "")
		return true;
		return false;
}

function isEmpty(s)
{
	if ((s == "") || (s == null))
		return true;
		return false;
}

//---------------------------------------------------------------------------	
/* 
function name	:	isValidScriptChars
input			:	string
ouput			:	boolean (true/false)
Purpose			:	to check whether the value provided contains script tags
*/	
	
function isValidScriptChars(val)	
{
	if (val.indexOf('<')==-1 && val.indexOf('>') == -1)
		return true;
	else
		return false;
}
//--------------------------------------------------------------------------	


function isInteger(s) 
{
		var i;
		
		for (i = 0; i < s.length; i++)
		 {
			var c = s.charAt(i);
			if (isIntegerDigit(c)==false) return false;
		}
			return true;
}//end of isInteger

function isIntegerDigit(c)
{
		return ((c >= "0") && (c <= "9"))
}  //end of isIntegerDigit	


function isDigit(c){
	return ((c >= "0") && (c <= "9"))
}//end func isDigit()      


	function isNumber(s)
		{
			var i;			
			for (i = 0; i < s.length; i++) {
			var c = s.charAt(i);
			if (!isDigit(c)) return false;
			}
			return true;
		} //end func isNumber()
		
		function isText(s)
			{
				var i;
				for (i = 0; i < s.length; i++) 
					{
						var c = s.charAt(i);
						if (isSpaceExist(c)) 
						return false;
					}
				return true;
			}

/* 
function name	:	isValidUSZIP
input			:	string
ouput			:	boolean(true/false)
Purpose			:	check whether the ZIP code is valid
*/	
function isValidUSZIP(field) 
	{
		var valid = "0123456789-";
		var hyphencount = 0;

		if (field.length!=5 && field.length!=10) {			
			return false;
		}//end if-loop
		for (var i=0; i < field.length; i++) {
			temp = "" + field.substring(i, i+1);
			if (temp == "-") hyphencount++;
			if (valid.indexOf(temp) == "-1") {			
				return false;
			}//end if-loop
			if ((hyphencount > 1) || ((field.length==10) && ""+field.charAt(5)!="-")) {			
				return false;
			}//end if-loop
		}//end for-loop	
		return true;
	}
//end of isValidUSZIP

// US Phone validation
/* 
function name	:	isValidUSPhone
input			:	string
ouput			:	boolean(true/false)
Purpose			:	check whether the Phone Number is valid
created by		:	Prasad	
*/
function isValidUSPhone(value) 
{	
	var reg = /^\D?(\d{3})\D?\D?(\d{3})\D?(\d{4})$/				
	return reg.test(value);					
}//end of isValidUSPhone



function daysInFebruary (year)
{
	// February has 29 days in any year evenly divisible by four,
	// EXCEPT for centurial years which are not also divisible by 400.
	return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}

function DaysArray(n) 
{
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
	}
	return this
}

function ismyInteger(s)
{
	var i;
	for(i = 0; i < s.length; i++)
	{   
		var c = s.charAt(i);
		if (((c < "0") || (c > "9"))) return false;
	}
	return true;
}

/* 
function name	:	isDecimalNumber(isNumeric)
input			:	string
ouput			:	boolean (true/false)
Purpose			:	to check whether the value provided is Decimal Number
created by		:	Radhika Kilaru	
*/

function isDecimalNumber(s) 
	{
		var i;
		
		for (i = 0; i < s.length; i++)
		 {
			var c = s.charAt(i);
			if (isDecimalDigit(c)==false) return false;
		}
			return true;
	}// end of isDecimalNumber
	
	function isDecimalDigit(c)
	{
		if ((c >= "0") && (c <= "9") || (c == "."))
		{
		return true;
		}
		else
		{
		return false;
		}
	}   //end of isDecimalDigit
	
function stripCharsInBag(s, bag)
{
	var i;
	var returnString = "";
	for (i = 0; i < s.length; i++)
	{   
		var c = s.charAt(i);
		if (bag.indexOf(c) == -1) returnString += c;
	}
	return returnString;
}


function ismyDate(dtStr,lbltxt)
{		
	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	var strMonth=dtStr.substring(0,pos1)
	var strDay=dtStr.substring(pos1+1,pos2)
	var strYear=dtStr.substring(pos2+1)
	strYr=strYear
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
	for (var i = 1; i <= 3; i++) 
	{
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
	}
	month=parseInt(strMonth)
	day=parseInt(strDay)
	year=parseInt(strYr)
	
	var datenull = Trim(dtStr) != "";
	if ((pos1==-1 || pos2==-1) && (datenull==true))
	{				
		//lbltxt.innerText = msg_common_invaliddate;
		alert(msg_common_invaliddate);
		return false
	}

	if ((strMonth.length<1 || month<1 || month>12) && (datenull==true))
	{				
		//lbltxt.innerText = msg_reports_validmonth;
		alert(msg_reports_validmonth);
		return false;
	}
	if ((strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]) && (datenull==true))
	{				
		//lbltxt.innerText = msg_reports_validday;
		alert(msg_reports_validday);
		return false;
	}
	if ((strYear.length != 4 || year==0 || year<minYear || year>maxYear) && (datenull==true))
	{								
		//lbltxt.innerText = msg_common_invaliddate;
		alert(msg_common_invaliddate);
		return false;
	}
	if ((dtStr.indexOf(dtCh,pos2+1)!=-1 || ismyInteger(stripCharsInBag(dtStr, dtCh))==false) && (datenull==true))
	{			
		//lbltxt.innerText = msg_common_invaliddate;
		alert(msg_common_invaliddate);
		return false;
	}
	return true
}

//Functions for Date Pick-up from Calender Control.

var calendar = null;
var last_date = null;

function selected(cal, date, eventTarget) 
	{
		last_date = cal.date;	
		var el = document.getElementById(eventTarget);
		el.style.background="#fff";
		el.value = date;
	}//end function

function closeHandler(cal) 
	{
		last_date = cal.date;		
		cal.destroy();
		calendar = null;
	}//end function

function OpenCalender(eventTarget,lef,top) 
	{
		if (calendar) return;
		var sel = document.getElementById(eventTarget);				
		var cal = new Calendar(true, last_date, selected, closeHandler, eventTarget);
		calendar = cal;
		cal.setRange(1900, 2070);
		var el = cal.element;
		el.style.left = sel.offsetLeft + lef + "px";
		el.style.top = sel.offsetTop + top + "px";
		el.style.visibility = "visible";
	}//End Functions	
	
	
	/* 
function name	:	fillMessage
input			:	string
Purpose			:	to check the browser and fill the corresponding label with the relevant message
*/
	
function fillMessage(lblToFill,msgToFill)
{
	if (navigator.userAgent.indexOf("Firefox")!=-1)			
		lblToFill.textContent = msgToFill;			
	else if (navigator.appName == "Microsoft Internet Explorer")
		lblToFill.innerText = msgToFill;					
}//end function fillMessage()




/*  ================================================================
	FUNCTION	: validateCard()
	 
	INPUT		: cardNumber,cardType,cardMonth,cardYear.ErrorConrolid

	RETURNS		: true, if CreditCard is valid. false, otherwise
	    
	DESCRIPTION	: Causes validation on four major credit cards like
				  visa, master, amex, discover and validates the
				  respective card numbers and expiry date.
				  expiry date shouldn't be less than the current month.
					 
	================================================================ */
    
	function validateCard(cardNumber,cardType,cardMonth,cardYear,Errorcardnumbercontrolid) 
	{
        /*if( cardNumber.length == 0 ) 
        {						//most of these checks are self explanitory
        	alert("Please enter a valid card number.");
        	return false;				
        }*/
        for( var i = 0; i < cardNumber.length; ++i ) 
        {		// make sure the number is all digits.. (by design)
        	var c = cardNumber.charAt(i);


            	if( c < '0' || c > '9' ) 
            	{
            		Errorcardnumbercontrolid.innerText = msg_common_integeronly;
            		return false;
            	}
        }
            var length = cardNumber.length;			//perform card specific length and prefix tests


            switch( cardType )
                {
                case '3':


                    	if( length != 15 )
                    	{
                    		Errorcardnumbercontrolid.innerText = msg_common_americanexpresscardnumber;
                    		return;
                    	}
                    	var prefix = parseInt( cardNumber.substring(0,2));


                        	if( prefix != 34 && prefix != 37 ) 
                        	{
                        		Errorcardnumbercontrolid.innerText = msg_common_americanexpresscardnumber;
                        		return;
                        	}
                        	break;
                        case '4':


                            	if( length != 16 ) 
                            	{
                            		Errorcardnumbercontrolid.innerText = msg_common_discoverynumber;
                            		return;
                            	}
                            	var prefix = parseInt( cardNumber.substring(0,4));


                                	if( prefix != 6011 ) 
                                	{
                                		Errorcardnumbercontrolid.innerText = msg_common_discoverynumber;
                                		return;
                                	}
                                	break;
                        case '3':


                                if( length != 16 ) 
                                {
                                    Errorcardnumbercontrolid.innerText = msg_common_mastercardnumber;
                                    return;
                                }
                                var prefix = parseInt( cardNumber.substring(0,2));


                                    if( prefix < 51 || prefix > 55) 
                                    {
                                        Errorcardnumbercontrolid.innerText = msg_common_mastercardnumber;
                                        return;
                                    }
                                    break;
                                case '1':


                                        if( length != 16 && length != 13 ) {
                                            Errorcardnumbercontrolid.innerText = msg_common_visacardnumber;
                                            return;
                                        }
                                        var prefix = parseInt( cardNumber.substring(0,1));


                                            if( prefix != 4 ) {
                                                Errorcardnumbercontrolid.innerText = msg_common_visacardnumber;
                                                return;
                                            }
                                            break;
                                    }
                                    if( !mod10( cardNumber ) ) { 		// run the check digit algorithm
                                        Errorcardnumbercontrolid.innerText = msg_common_validcreditcardnumber;
                                        return false;
                                    }
                                    if( expired( cardMonth, cardYear ) ) {							// check if entered date is already expired.
                                        Errorcardnumbercontrolid.innerText = "Sorry! The expiration date you have entered would make this card invalid.";
                                        return false;
                                    }
                                    
                                    return true; // at this point card has not been proven to be invalid
                                    }
                                            
  /*  ================================================================
    FUNCTION	:  expired()
 
    INPUT		:  month, year

    RETURNS		:  true, if expiry date is valid. false, otherwise
    
    DESCRIPTION	: Causes validation on the Expiry month and year.
				  Expiry month and year shouldnt be less than the current.
	Created By	: Srinivas	
    ================================================================ */
    
	function expired( month, year )
	{
    var now = new Date();							// this function is designed to be Y2K compliant.
    var expiresIn = new Date(year,month,0,0,0);		// create an expired on date object with valid thru expiration date
    //  expiresIn.setMonth(expiresIn.getMonth()+1);		// adjust the month, to first day, hour, minute & second of expired month
    if( now.getTime() < expiresIn.getTime() ) return false;
    return true;									// then we get the miliseconds, and do a long integer comparison
	}     
		 
		 
/*  ================================================================
    FUNCTION: mod10()
 
    INPUT	   : month, year

    RETURNS	   : true, if cardNumber length and mod 10 is divisible and returns 0,
				 false, otherwise
    
    DESCRIPTION: Causes validation on the Credit Card Number using
				 LUHN Formula for validation of credit card numbers
				 Expiry month and year shouldnt be less than the current.
	Created By : Srinivas
    ================================================================ */
		
		function mod10( cardNumber ) 
		{ 
			// LUHN Formula for validation of credit card numbers.
			var ar = new Array( cardNumber.length );
			var i = 0,sum = 0;

	    	for( i = 0; i < cardNumber.length; ++i ) 
	    	{
    			ar[i] = parseInt(cardNumber.charAt(i));
    		}
    		
    		for( i = ar.length -2; i >= 0; i-=2 ) 
    		{ 
    		// you have to start from the right, and work back.
    		ar[i] *= 2;			
    		
    		// every second digit starting with the right most (check digit)
    		// will be doubled, and summed with the skipped digits.
    		// if the double digit is > 9, ADD those individual digits together 
    		
    		if( ar[i] > 9 ) ar[i]-=9;
    		}
    	
        	for( i = 0; i < ar.length; ++i ) 
        	{
        		sum += ar[i];		 // if the sum is divisible by 10 mod10 succeeds
        	}
        	return (((sum%10)==0)?true:false);	 	
		 }	
		 
// End of Credit Card Validation		 	                                      



/* 
function name	:	isValidSearchAmount(isNumeric)
input			:	string
ouput			:	boolean (true/false)
Purpose			:	to check whether the value provided is Decimal Number for +ve & -ve values with two decimal places
created by		:	Ratnam	
created on		:	06/12/2006
*/

	function isValidSearchAmount(price)
			{
				
				var textafterdecimal;
				if (price.lastIndexOf('.') == -1)
				{
					price += ".";
				}
				textafterdecimal = price.substring(price.indexOf('.')+1, price.length);
				
				if (textafterdecimal.length > 2)
				{
					return false;
				}
				
				var textbeforedecimal;				
			
					textbeforedecimal = price.substring(0,price.indexOf('.'));
					if (textbeforedecimal.substring(0,1) == "-")
						{
							textbeforedecimal = textbeforedecimal.substring(1,textbeforedecimal.length)
						}
					if (textbeforedecimal.length > 8)
					{			
					return false;
					}
							
				return true;
			}	
			

		/* 
		function name	:	isProductPrice(ProductPrice)
		input			:	string
		ouput			:	boolean (true/false)
		Purpose			:	to Check for the price of the product accepts only two decimal places
		created by		:	Radhika Kilaru	
		*/

		function isValidProductPrice(price)
			{
				
				var textafterdecimal;
				if (price.lastIndexOf('.') == -1)
				{
					price += ".";
				}
				textafterdecimal = price.substring(price.indexOf('.')+1, price.length);
				
				if (textafterdecimal.length > 2)
				{
					return false;
				}
				
				var textbeforedecimal;				
			
					textbeforedecimal = price.substring(0,price.indexOf('.'));
					if (textbeforedecimal.length > 8)
					{			
					return false;
					}
							
				return true;
			}	//end of isValidProductPrice
					
		/* 
		function name	:	isValidProductWeight
		input			:	string
		ouput			:	boolean (true/false)
		Purpose			:	to Check for the weight of the product accepts only four decimal places
		created by		:	Radhika Kilaru	
		*/
			
		function isValidProductWeight(weight)
			{
				
				var textafterdecimal;
				if (weight.lastIndexOf('.') == -1)
				{
					weight += ".";
				}
				textafterdecimal = weight.substring(weight.indexOf('.')+1, weight.length);
				
				if (textafterdecimal.length > 4)
				{
					return false;
				}
				var textbeforedecimal;			
	
				textbeforedecimal = weight.substring(0,weight.indexOf('.'));
				if (textbeforedecimal.length > 4)
				{			
				return false;
				}
				return true;
			}	//end of isProductWeight			
					
		/* 
		function name	:	isValidProductCV
		input			:	string
		ouput			:	boolean (true/false)
		Purpose			:	to Check for the cv of the product accepts only two decimal places
		created by		:	Radhika Kilaru	
		*/

		function isValidProductCV(cv)
			{
				
				var textafterdecimal;
				if (cv.lastIndexOf('.') == -1)
				{
					cv += ".";
				}
				textafterdecimal = cv.substring(cv.indexOf('.')+1, cv.length);
				
				if (textafterdecimal.length > 2)
				{
					return false;
				}
				
				var textbeforedecimal;			
	
				textbeforedecimal = cv.substring(0,cv.indexOf('.'));
				if (textbeforedecimal.length > 8)
				{			
				return false;
				}
							
				return true;
			}	//end of isValidProductCV
