/*----------------------------------------------------------------------------------------
	Function Name		: TrimTheString 
	Parameters			: pszStringtoTrim
	Purpose				: Trims the string
-------------------------------------------------------------------------------------------*/
function TrimTheString ( pszStringtoTrim )
{
	var bflag = true;
	var i = 0;
	if ( IsWhitespace ( pszStringtoTrim ) == true )
		return "";
	while ( ( i < pszStringtoTrim.length ) && ( bflag ) )
	{
		retChar = pszStringtoTrim.charAt ( i++ );
		if ( retChar != " " ) bflag = false;
	}
	if ( bflag ) return "";
	var j = pszStringtoTrim.length-1;
	bflag = true;
	while ( ( j >= 0 ) && ( bflag ) ) 
	{
		retChar = pszStringtoTrim.charAt ( j-- );
		if ( retChar != " " ) bflag = false;
	}
	if ( bflag ) return "";
	pszStringtoTrim = pszStringtoTrim.substring ( i-1 ,j+2 );
	return pszStringtoTrim;
}

/*----------------------------------------------------------------------------------------
	Function Name		: IsWhitespace 
	Parameters			: pszStringtoCheck
	Purpose				: Checks for white spaces
-------------------------------------------------------------------------------------------*/
function IsWhitespace ( pszStringtoCheck )
{
	var reWhitespace = /^\s+$/
	return ( IsEmpty ( pszStringtoCheck ) || reWhitespace.test ( pszStringtoCheck ) );
}
	
/*----------------------------------------------------------------------------------------
	Function Name		: IsEmpty 
	Parameters			: pszStringtoCheck
	Purpose				: Checks for empty string
-------------------------------------------------------------------------------------------*/

function IsEmpty ( pszStringtoCheck ) {
	return ( ( pszStringtoCheck == null ) || ( pszStringtoCheck.length == 0 ) )
}


/*----------------------------------------------------------------------------------------
	Function Name		: OpenListenMediaWindow 
	Parameters			: physical file name in the server
	Purpose				: Plays the media file
-------------------------------------------------------------------------------------------*/

function OpenListenMediaWindow(pszFileName) {
	var height = 200;
	var width = 300;
	var windowHeight = 240;
	var windowWidth = 320;

	var strAttributes = "height=" + windowHeight + ",innerHeight=" + height;
	strAttributes += ",width=" + windowWidth + ",innerWidth=" + width;
	if (window.screen) {
		var ah = screen.availHeight - 30;
		var aw = screen.availWidth - 10;
		var xc = (aw - width) / 2;
		var yc = (ah - height) / 2;

		strAttributes += ",left=" + xc + ",screenX=" + xc;
		strAttributes += ",top=" + yc + ",screenY=" + yc;
		strAttributes += ",scrollbars=no,statusbar=no,resizable=no";
	}
	
    var objType = (objType=="wav" || objType=="mpg"||objType=="mpeg")?"video/mpeg":
              (objType=="avi"||objType=="wmv") ?"video/x-msvideo":"video/quicktime";
	var pluginspace = (objType=="video/x-msvideo")?"http://www.microsoft.com/windows/windowsmedia/default.aspx":(objType=="video/quicktime")?"http://www.apple.com/quicktime/download/":"";
	var codebase    = (objType=="video/x-msvideo")?"http://www.microsoft.com/windows/windowsmedia/default.aspx":(objType=="vide/quicktime")?"http://www.apple.com/qtactivex/qtplugin.cab":"";
	
	
	var objListenMedia;
	objListenMedia = window.open(pszFileName,"ListenMedia", strAttributes);
	
	//objListenMedia.document.write("<html><head><title>Listen Media</title></head><body><embed pluginspace='"+ pluginspace + "' src='"+ pszFileName +"' type='" + objType +"' width='"+ width +"' height='"+ height +"'></embed></body></html>");
	if (objListenMedia.closed)
	{
		alert("Window is blocked with pop-up blocker.Please disable the popup blockers.");
	}
	else
	{
		objListenMedia.focus();			
	}
}

/*----------------------------------------------------------------------------------------
	Function Name		: OpenListenMediaWindow 
	Parameters			: physical file name in the server
	Purpose				: Plays the media file
-------------------------------------------------------------------------------------------*/

function OpenGenericWindow(pszFileName,psWindowName,pszParameterValue,piwidth,piheight,locationID) {
	if (piwidth == null && piheight == null)
	{
		var height = 220;
		var width = 280;
	}
	else
	{
		var height = piheight;
		var width = piwidth;
	}

	var strAttributes = "height=" + height + ",innerHeight=" + height;
	strAttributes += ",width=" + width + ",innerWidth=" + width;
	if (window.screen) {
		var ah = screen.availHeight - 30;
		var aw = screen.availWidth - 10;
		var xc = (aw - width) / 2;
		var yc = (ah - height) / 2;

		strAttributes += ",left=" + xc + ",screenX=" + xc;
		strAttributes += ",top=" + yc + ",screenY=" + yc;
		strAttributes += ",scrollbars=yes,statusbar=no,resizable=no";
	}
	var objGenericWindow;
	if(pszParameterValue!=null)
	{
		if(TrimTheString(pszParameterValue) != "")
		{
			var strTempFileName = pszFileName +"?Page="+ pszParameterValue;		
			objGenericWindow = window.open(strTempFileName+"&LocationID="+ locationID,psWindowName, strAttributes);				
		}
	}
	else
		objGenericWindow = window.open(pszFileName,psWindowName, strAttributes)
		
	if (objGenericWindow.closed)
	{
		alert("Window is blocked with pop-up blocker.Please disable the popup blockers.");
	}
	else
		objGenericWindow.focus();
	
}

/**************************************************************************************
	Function Name		: IsValidPhoneNumber 
	Parameters			: Phone Number
	Purpose				: Validates the Phone Number which was entered by the user
**************************************************************************************/
function ASP_IsValidPhoneNumber ( fieldName )
{
	var szStripped = fieldName.replace(/[\(\)\.\-\ ]/g, '');
	if (isNaN(szStripped))
	{
		//alert("Telephone number format should be specified as  ###-###-####");
		//showErrorMessage("Err_General_Phone");
		return false;
	}else if ( ( szStripped.length != 10)) 
	{
		//showErrorMessage("Err_General_Phone");
		return false;
	}
	else
		return true;
}

/**************************************************************************************
	Function Name		: IsValidPhoneNumber 
	Parameters			: Phone Number
	Purpose				: Validates the Phone Number which was entered by the user and display the message
**************************************************************************************/

function IsValidPhoneNumber (fieldvalue,msgtext )
{

	var szStripped = fieldvalue.replace(/[\(\)\.\-\ ]/g, '');
	if (isNaN(szStripped))
	{
		document.getElementById("TopControl_spnMessage").innerText = msgtext + "  format should be specified as  (###) ###-####";
		return false;
	}
	else if ( szStripped.length != 10) 
	{
		document.getElementById("TopControl_spnMessage").innerText = msgtext + "  format should be specified as  (###) ###-####";
		return false;
	}
	else
		return true; 
}


/**************************************************************************************
	Function Name		: IsValidEmail
	Parameters			: Email ID and Message Text to be dispalyed
	Purpose				: Validates the Email ID which was entered by the user
**************************************************************************************/
function IsValidEmail ( pszFieldObj, pszFieldNameToAppend )
{
	var reEmail = /^[_a-z0-9A-Z-]+(\.[_a-z0-9A-Z-]+)*@[a-z0-9A-Z-]+(\.[a-z0-9A-Z-]+)*(\.([a-zA-Z]){2,4})$/
	var szBadStrings = " ~`!#$%^&*()+=[{]}|\<>?,:';";
	var szCurrChar;

	szFieldValue = TrimTheString( eval ( pszFieldObj ).value );
	for ( var i=0 ; i < szFieldValue.length ; i++)
	{
		j = i + 1;
		szCurrChar = szFieldValue.substring ( i , j );
		if ( szBadStrings.indexOf ( szCurrChar ) != -1 )
		{
			//document.getElementById("TopControl_spnMessage").innerText = pszFieldNameToAppend + " contains invalid letters.";
			return false;		// contains badchar.
		}
	}

	if ( reEmail.test ( szFieldValue ) == false )
	{
		//eval ( pszFieldObj ).focus();
		//showErrorMessage("Err_General_Email");
		return false;		// invalid email.
	}
	return true;
}

/**************************************************************************************
	Function Name		: IsValidEmailDomain
	Parameters			: Email ID and Message Text to be dispalyed
	Purpose				: Validates the Email domain which was entered by the user against 
	                        array of invalid domains
**************************************************************************************/
function IsValidEmailDomain (pszFieldObj, pszFieldNameToAppend)
{
    var InvalidDomains = new Array
        ("gmail.com", "qmail.com", "yahoo.com", "aol.com", "hotmail.com", "netzero.com", "earthlink.com", "voiceblast.com", 
        "allusa.us", "mail.com", "freemail.com", "comcast.com", "rr.com", "animail.net", "moose-mail.com",
        "snail-mail.net", "whale-mail.com", "wildmail.com", "bluebottle.com", "canada.com", "boardermail.com",
        "canoemail.com", "cashette.com", "dbzmail.com", "dcemail.com", "didamail.com", "doramail.com", "123india.com",
        "123mail.com", "fastmail.fm", "fastmail.co.uk", "burntmail.com", "fusemail.com", "gnumail.org", "mailandfiles.com",
        "mailsecret.com", "pilot.ac", "contactme.bz", "attorney.ac", "lawyer.ac", "cpa.ac", "dentist.ac", "vet.md",
        "marmotmail.com", "modomail.com", "biogate.com", "bitsmart.com", "cyberjunkie.com", "earthcorp.com", "poboxes.com",
        "allen.net", "zimmermann.com", "popmail.com", "runbox.com", "s-mail.com", "emailgarden.com", "media-email.com",
        "inxsemail.com", "nbay.net", "inboxemail.com", "tuffmail.com", "tuffmail.co.uk", "bsdbigot.com", "hismail.cc",
        "hermail.cc", "phpdude.com", "ricksbar.com", "ebay.com");
        
    var email = TrimTheString( eval ( pszFieldObj ).value ); 
    
    for(i=0; i<InvalidDomains.length; i++)
	{
		var domain = InvalidDomains[i].toString();
		if(email.indexOf(InvalidDomains[i].toString()) >= 0)
		{
			return false;
		}
	}

	return true;                               
}


/***************************************************************************************
	Function Name		: IsDateValid
	Parameters			: Date
	Purpose				: Validates the Date field without any message
***************************************************************************************/
	function IsDateValid(objDateField)
	{
		return IsValidDateWithMessagePassed( objDateField, "date")
	}
/***************************************************************************************
	Function Name		: IsValidDateWithMessagePassed
	Parameters			: Date, Message text
	Purpose				: Validates the Date field
***************************************************************************************/
	function IsValidDateWithMessagePassed(objDateField, strFieldDescription)
	{
		var varErrorMsg = "The " + strFieldDescription + " should be specified as (MM/DD/YYYY) or (M/D/YYYY)";
	   	var strDateField = objDateField.value;

		if (strDateField == "")
		{
			ShowErrorMessageAndFocus ( "Please enter the " + strFieldDescription  + " before proceeding.", objDateField)
			return false;
		}
		if (strDateField.length > 10)
		{
			ShowErrorMessageAndFocus ( varErrorMsg, objDateField)
			return false;
		}
		if(strDateField.length!=10 && strDateField.length!=9 && strDateField.length!=8)
		{
			ShowErrorMessageAndFocus ( varErrorMsg , objDateField)
			return false;
		}
		if(strDateField.length==10)
		{
			if ((strDateField.charAt(2) != "/") || (strDateField.charAt(5) != "/"))
			{
				ShowErrorMessageAndFocus ( varErrorMsg, objDateField)
				return false;
			}
			nummonth = strDateField.charAt(0)+ strDateField.charAt(1)
			numday = strDateField.charAt(3)+ strDateField.charAt(4)
			numyear = strDateField.charAt(6)+ strDateField.charAt(7) + strDateField.charAt(8)+ strDateField.charAt(9)
		}
		if(strDateField.length == 8)
		{
			if ((strDateField.charAt(1) != "/") || (strDateField.charAt(3) != "/"))
			{
				ShowErrorMessageAndFocus ( varErrorMsg, objDateField)
				return false;
			}
			nummonth = strDateField.charAt(0)
			numday = strDateField.charAt(2)
			numyear = strDateField.charAt(4)+strDateField.charAt(5) + strDateField.charAt(6)+strDateField.charAt(7)
		}
		if(strDateField.length == 9)
		{
			if (((strDateField.charAt(1) != "/") || (strDateField.charAt(4) != "/")) &&((strDateField.charAt(2) != "/") || (strDateField.charAt(4) != "/")))
			{
				ShowErrorMessageAndFocus ( varErrorMsg, objDateField)
				return false;
			}
			if (strDateField.charAt(1) == "/")
			{
				nummonth = strDateField.charAt(0)
				numday = strDateField.charAt(2)+ strDateField.charAt(3)
				numyear =strDateField.charAt(5) + strDateField.charAt(6)+strDateField.charAt(7)+ strDateField.charAt(8)
			}
			else
			{
				nummonth = strDateField.charAt(0)+strDateField.charAt(1)
				numday = strDateField.charAt(3)
				numyear =strDateField.charAt(5) + strDateField.charAt(6)+strDateField.charAt(7)+ strDateField.charAt(8)
			}
		}

		if (numyear.length < 4)
		{
			ShowErrorMessageAndFocus ( "Year should is YYYY", objDateField)
			return false;
		}
		if (!IsPositiveIntValue("Month value in date",nummonth))
			return false;
		if (!IsPositiveIntValue("Day value in date",numday))
			return false;
		if (!IsPositiveIntValue("Year value in date",numyear))
			return false;

		day = parseInt(numday,10)
		month = parseInt(nummonth,10)
		year = parseInt(numyear,10)

		if (isNaN(day) || isNaN(month) || isNaN(year))
		{
			ShowErrorMessageAndFocus ( "Invalid Date", objDateField)
			return false;
		}
		if ((day < 0) || (month < 0) || (year < 0))
		{
			ShowErrorMessageAndFocus ( "Invalid character in " + strFieldDescription, objDateField)
			return false;
		}
		if ((day == 0) || (month == 0) || (year == 0))
		{
			ShowErrorMessageAndFocus ( "Invalid" + strFieldDescription, objDateField)
			return false;
		}
		if (month > 12)
		{
			ShowErrorMessageAndFocus ( "Month cannot be greater than 12", objDateField)
			return false;
		}
		if (day > 31 )
		{
			ShowErrorMessageAndFocus ( "Day cannot be greater than 31 for the given month", objDateField)
			return false;
		}
		if ((month==4)||(month==6)||(month==9)||(month==11))
		{
				if (day > 30 )
				{
					ShowErrorMessageAndFocus ( "Day cannot be greater than 30 for this month", objDateField)
					return false;
				}
		}
		if (month==2)
		{
			if  ((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0) ) )
			{
				if (day > 29)
			    {
					ShowErrorMessageAndFocus ("Day cannot be greater than 29 for 'Feb' in the given year", objDateField)
			        return false;
				}
			}
			else
			{
				if (day > 28)
				{
					ShowErrorMessageAndFocus ("Day cannot be greater than 28 for 'Feb' in the given year", objDateField)
					return false;
				}
		    }
		}

		if (numyear < 1900)
		{
			ShowErrorMessageAndFocus ("Year cannot be less than 1900.", objDateField)
			return false;
		}

		return true;
	}
	/***************************************************************************************
	Function Name		: IsPositiveIntValue
	Parameters			: Message Text, Value
	Purpose				: Checks the value whether it is Postivie/Negative
	***************************************************************************************/
	function IsPositiveIntValue(appendMessage, checkValue)
	{
		if (isNaN(checkValue))
		{
			//document.getElementById("TopControl_spnMessage").innerText = appendMessage + " should be a positive number ( -ve is not allowed )"
			return false;
		}
		else if(checkValue <0)
		{
			//document.getElementById("TopControl_spnMessage").innerText = appendMessage + " should be a positive number ( -ve is not allowed )"
			return false;
		}
		else
			return true;
	}	
	
	/***************************************************************************************
	Function Name		: ShowErrorMessageAndFocus
	Parameters			: Message Text, Field Object
	Purpose				: populates the message text and sets the focus over to the field
	***************************************************************************************/
	function ShowErrorMessageAndFocus(varErrorMsg, objFieldtoFocus)
	{
		document.getElementById("TopControl_spnMessage").innerText = varErrorMsg;
		objFieldtoFocus.focus();
		objFieldtoFocus.select();
	}
	/***************************************************************************************
	Function Name	: CloseWindow
	Purpose			: Closes the current window
	***************************************************************************************/
	function CloseWindow()
	{
		window.close();
	}
	function MM_swapImgRestore()
	{ //v3.0
		var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
	}
	function MM_findObj(n, d)
	{ //v4.0
		var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
			d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
		if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
		for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
		if(!x && document.getElementById) x=document.getElementById(n); return x;
	}
	function MM_swapImage() 
	{ //v3.0	
		var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
		if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
	}	
	//Toggles the textbox color in the textbox
	function toggleColor(objElement)
	{
		if (objElement.className=='pretextbox')
			objElement.className='pretextboxfocus';
		else
			objElement.className='pretextbox';
	}
	/*----------------------------------------------------------------------------------------
	Function Name		: IsSmallLongInt 
	Parameters			: pszFieldObj, pszMaxValue
	Purpose				: Validates the Numeric field
	-------------------------------------------------------------------------------------------*/			
	function IsSmallLongInt ( pszFieldObj, pszMaxValue, pszFieldNameToAppend )
	{
		if ( TrimTheString( pszMaxValue ) == "" )
		{
			pszMaxValue = "SMALLINT";
		}
		var pnMaxValue;
		var szFieldValue = eval( pszFieldObj ).value
		szFieldValue = szFieldValue.replace(/\$|\,/g,'');  //Replaces the commas with empty
		if ( isNaN( TrimTheString( szFieldValue ) ) )
		{
					return false;
		}
		else
		{
			if ( TrimTheString( pszMaxValue ).toUpperCase() == "SMALLINT")
				pnMaxValue = 32767;
			else if ( TrimTheString( pszMaxValue ).toUpperCase() == "INT")
				pnMaxValue = 2147483647;
			else
				pnMaxValue = parseInt(pszMaxValue);
		
			if ( szFieldValue > pnMaxValue )
			{			
				return false;
			}
			else
			{
				return true;
			}
		}
	}
	/*----------------------------------------------------------------------------------------
	Function Name		: CheckCreditobjCardNumber
	Parameters			: objCrediCard
	Purpose				: To check the Credit Card Number
	-------------------------------------------------------------------------------------------*/
	function CheckCreditCard(objCardNumber)
	{
		var loopCounter;
		var FirstDigitsSub = 0;
		var SecondDigitsSum = 0;
		var TempSecondSum = "";
		var LoopValue = 0;
		var CurrentNumber = 0;
		var TotalLengthODD = 0;

		// Only if the number passed is numeric and is more than 14 chars length
		if ( IsSmallLongInt (objCardNumber, '9999999999999999') && objCardNumber.value.length >= 14) 
		{
			// Implementation of LUHN Formula.
			if ( (objCardNumber.value.length % 2) == 0)
				TotalLengthODD = 1
			else
				TotalLengthODD = 0

			var objCardNumbervalue = objCardNumber.value;
			for(loopCounter = objCardNumbervalue.length-1; loopCounter >= 0; loopCounter--)
			{
				CurrentNumber = parseInt( objCardNumbervalue.substr(loopCounter, 1))
				if ( ( loopCounter % 2) == TotalLengthODD)
					FirstDigitsSub += CurrentNumber 
				else
				{
					CurrentNumber *= 2;
					if ( CurrentNumber > 9)
					{
						TempSecondSum = "" + CurrentNumber
						CurrentNumber = parseInt( TempSecondSum.substr(0, 1)) + parseInt( TempSecondSum.substr(1, 1))
					}
					CurrentNumber 
					SecondDigitsSum += CurrentNumber;
				}
				LoopValue = CurrentNumber 
			}
			if ( ( (SecondDigitsSum + FirstDigitsSub ) % 10 ) == 0 )
				return true
			else
			{
				//document.getElementById("TopControl_spnMessage").innerText = "Invalid credit card number. Please enter valid credit card number";
				return false
			}
		}
		else
		{
			//document.getElementById("TopControl_spnMessage").innerText = "Invalid credit card number. Please enter valid credit card number";
			return false
		}
	}
	
	/*----------------------------------------------------------------------------------------
	Function Name		: IsValidDateDiff
	Parameters			: LaterDate,EarlierDate,diff Precision etc.
	Purpose				: Checks the Past date or not 
	-------------------------------------------------------------------------------------------*/	
	function IsValidDateDiff ( pszLaterDate, pszEarlierDate, pszDiffPrecision, pnDiffAllowed ) 
	{
		var aDateArr, nMonth, nDay, nYear;
		aDateArr = pszLaterDate.split ( "/" );
		nMonth = aDateArr [ 0 ];
		nDay = aDateArr [ 1 ];
		nYear = aDateArr [ 2 ];
		pszLaterDate = new Date ( nYear, nMonth-1, nDay );

		aDateArr = pszEarlierDate.split ( "/" );
		nMonth = aDateArr [ 0 ];
		nDay = aDateArr [ 1 ];
		nYear = aDateArr [ 2 ];
		pszEarlierDate = new Date ( nYear, nMonth-1, nDay );

		var nThedifference = pszLaterDate.getTime() - pszEarlierDate.getTime();
		var nDaysDifference = Math.floor(nThedifference/1000/60/60/24);

		nThedifference -= nDaysDifference*1000*60*60*24;
		var nHoursDifference = Math.floor(nThedifference/1000/60/60);

		nThedifference -= nHoursDifference*1000*60*60;
		var nMinutesDifference = Math.floor(nThedifference/1000/60);

		nThedifference -= nMinutesDifference*1000*60;
		var nSecondsDifference = Math.floor(nThedifference/1000);

		var nMonthsDifference = Math.round ( parseInt ( nDaysDifference) * 12 / 365.24219878 );
		var nYearsDifference = Math.round ( parseInt ( nDaysDifference) / 365.24219878 );
		
		pnDiffAllowed = "" + pnDiffAllowed;
		pszDiffPrecision = pszDiffPrecision.toUpperCase();
		
		if ( TrimTheString ( pszDiffPrecision ) == "YEARS" )
		{
			if ( nYearsDifference > parseInt ( TrimTheString ( pnDiffAllowed ) ) )
				return false;
			else
				return true;
		}
		else if ( TrimTheString ( pszDiffPrecision ) == "MONTHS" )
		{
			if ( nMonthsDifference > parseInt ( TrimTheString ( pnDiffAllowed ) ) )
				return false;
			else
				return true;
		}
		else if ( TrimTheString ( pszDiffPrecision ) == "DAYS" )
		{
			if ( nDaysDifference > parseInt ( TrimTheString ( pnDiffAllowed ) ) )
				return false;
			else
				return true;
		}
	}

	/*----------------------------------------------------------------------------------------
	Function Name		: ValidateUSAPostalCode
	Parameters			: Postal Code
	Purpose				: Checks for the valid postal code or not
	-------------------------------------------------------------------------------------------*/	
	function ValidateUSAPostalCode(zip) 
	{
		var zip = TrimTheString(zip);
		if (!(zip.length == 5 || zip.length == 9 || zip.length == 10)) 
			return false;
		if ((zip.length == 5 || zip.length == 9) && isNaN(zip))
			return	false;
		if (zip.length == 10 && zip.search && zip.search(/^\d{5}-\d{4}$/)== -1) 
			return false;
		return true;
	}
	/*----------------------------------------------------------------------------------------
	Function Name		: ValidateCanadianZipCode
	Parameters			: Postal Code
	Purpose				: Checks for the valid postal code or not
	-------------------------------------------------------------------------------------------*/	
	function ValidateCanadianZipCode(zip)
	{
		// Check that a Canadian postal code is valid
		if (zip.search) {
		zip = TrimTheString(zip);
		if (zip.length == 6 && zip.search(/^[a-zA-Z]\d[a-zA-Z]\d[a-zA-Z]\d$/)!= -1) return true;
		else if (zip.length == 7 && zip.search(/^[a-zA-Z]\d[a-zA-Z]-\d[a-zA-Z]\d$/) != -1) return true;
		else return false;
		}
		return true;
	}
	
	/*----------------------------------------------------------------------------------------
	Function Name		: FormatNumber
	Parameters			: Number
	Purpose				: Input: 1234 Output: 1,234
	-------------------------------------------------------------------------------------------*/
function FormatNumber(num)
{
	var orgNum = num
	var afternumber = 0;
	var negitiveValue = 0;
	num = num.toString().replace(/\$|\,/g,'');

	if (num.indexOf(".") > 0)
	{
		numberAfterDecimal = num.substring( 0, num.indexOf( ".") + 3)
		afternumber = num.substring( num.indexOf( ".") + 3, num.indexOf( ".") + 7)
		if ( afternumber == 4999 )
			num = parseFloat( numberAfterDecimal ) + 0.01;
	}
	
	if ( num < 0 )
	{
		negitiveValue = 1
		num = num * -1
	}

	num = (Math.round ( num  * 1000 / 10) / 100 )

	if(isNaN(num))
		num = "0";
	sign = (num == (num = Math.abs(num)));

	num = Math.floor(num*100 + 0.50000000001);
	num = Math.floor(num/100).toString();
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
		num = num.substring(0,num.length-(4*i+3)) + ',' + 	num.substring(num.length-(4*i+3));

	num = (((sign)?'':'-') + num)

	if ( negitiveValue == 1 )
		num = "-" + num 

	return num 
}
/*
	Function Name		: ChangeStates
	Parameters			: CountrySelectedValue
	Purpose				: States will displayed based on the country

*/
	function ChangeStates(val, ctrlID)
	{
		var intLoopCounter = 0;	
		//Length of the ddlState values
		var ddlStateLength = document.getElementById(ctrlID).length; 
		//This is for get the CountryId based on Selected country
		for(;intLoopCounter < document.getElementById("hidddlCountry").length;intLoopCounter++) 
		{			
			if(val==document.getElementById("hidddlCountry").options[intLoopCounter].text)
			{
				ddlCountryId = document.getElementById("hidddlCountry").options[intLoopCounter].value;
			}				
		}		
		//This is for clear the existing states in ddlState
		for(intLoopCounter = 0;intLoopCounter < ddlStateLength;intLoopCounter++)  
		{
			document.getElementById(ctrlID).options[0]=null;					 		
		}
		//This is for new index values into ddlState	  	  
		var ddlNewStateIndex = 0; 
		for(intLoopCounter=0;intLoopCounter<document.getElementById("hidddlState").length;intLoopCounter++)
		{
				//Index of special character in hidddlState SelectedValue
		 	var indexsplsymbol = document.getElementById("hidddlState").options[intLoopCounter].value.indexOf("^");
			//Length of the states in hidddlState 
			var lenghtval = document.getElementById("hidddlState").options[intLoopCounter].value.length;
			//For get the CountryId from hidddlState
			hidddlstateCountryId = document.getElementById("hidddlState").options[intLoopCounter].value.substr(indexsplsymbol+1,(lenghtval-indexsplsymbol)+1);	
			if (ddlCountryId==hidddlstateCountryId)
			{		
				ddlStateCode=document.getElementById("hidddlState").options[intLoopCounter].value.substr(0,indexsplsymbol);				
				txtddlState=document.getElementById("hidddlState").options[intLoopCounter].text;				
				document.getElementById(ctrlID).options[ddlNewStateIndex]=new Option(txtddlState,ddlStateCode);				
				ddlNewStateIndex++;
			}
		}
		if (document.getElementById("hidState").value!="0") 
		{
			document.getElementById(ctrlID).value=document.getElementById("hidState").value;
			document.getElementById("hidState").value="0";
		}		
		
	}//End of ChageStates
		
//------------------------------- Added By Mahesh on 19th September 2005 for web grid---

// This file contains java script used by the DropDownGrid.aspx form.
//
// flag to avoid multiple listeners to same mouse-down event
var globalListenerWasCreated = false;
// references to drop-down grids
var dropDownGrids = new Array();
// it is called when drop-down grid is initialized
function initGridEvent(gridName)
{ 
	var oGrid = igtbl_getGridById(gridName);
	if(oGrid == null)
	{
		alert("Error: \"" + gridName + "\" was not found.");
		return;
	}
	oGrid.mainElement = ig_csom.getElementById(gridName + "_main");
	if(oGrid.mainElement == null)
	{
		alert("Error: \"" + gridName + "_main\" was not found.");
		return;
	}
	// ensure absolute position
	// Note: it can be skipped if style in aspx has that
	oGrid.mainElement.style.position = "absolute";
	// assume that grid on start is visible
	// create boolean member variable, which simplifies visibility test
	oGrid.isDisplayed = true;
	// global cash of grid-reference
	dropDownGrids[dropDownGrids.length] = oGrid;
	// hide drop-down grid
	showDropDown(oGrid, null, false);
}
// it is called by date click events of UltraWebGrid
// Note: that name should match with the ClientSideEvents.CellClickHandler property
//  which is set in aspx for UltraWebGrid
function cellClickEvent(gridName, cellId, button)
{
	var oGrid = igtbl_getGridById(gridName);
	var oCell = igtbl_getCellById(cellId);
	if(oGrid == null || oCell == null)
	{
		alert("Error: \"" + gridName + "\" was not found.");
		return;
	}
	// update editor with latest text and hide grid
	showDropDown(oGrid, oCell.getValue(), false, true);
}
// it is called by custom-button click event of WebTextEdit
// Note: that name should match with the ClientSideEvents.CustomButtonPress property
//  which is set in aspx for WebTextEdit
function openDropDownEvent(oEdit, text, oEvent)
{
	// open drop-down grid
	openDropDown(oEdit, dropDownGrids[0]);
}
// it is called by spin and focus events of WebTextEdit
// Note: that name should match with the ClientSideEvents.KeyDown/Spin/Focus/etc. properties
//  which are set in aspx for WebTextEdit
function closeDropDownEvent(oEdit, text, oEvent)
{
	// hide grid
	showDropDown(oEdit.oGrid, null, false);
}
// open grid and attach it to WebTextEdit
// oEdit - reference to the owner of grid (WebTextEdit)
// oGrid - the UltraWebGrid which should be dropped and attached to oEdit
function openDropDown(oEdit, oGrid)
{
	if(oGrid == null) return;
	// add listener to mouse click events for page
	if(!globalListenerWasCreated)
		ig_csom.addEventListener(window.document, "mousedown", globalMouseDown, false);
	globalListenerWasCreated = true;
	// set reference of grid to editor:
	// create member variable, which points to drop-down grid
	oEdit.oGrid = oGrid;
	// if it belongs to another oEdit, then close oGrid
	if(oGrid.oEdit != oEdit)
	{
		showDropDown(oGrid, null, false);
		// set reference in oGrid to this oEdit
		// create member variable, which points to the owner oEdit
		oGrid.oEdit = oEdit;
	}
	// show grid with text from editor
	// if grid is already opened, then hide grid (last param)
	showDropDown(oGrid, oEdit.getText(), true, true, true);
}
// synchronize text in TextEdit with selected cell in grid
// and show/close grid
function showDropDown(oGrid, text, show, update, toggle)
{
	if(oGrid == null) return;
	if(toggle == true && oGrid.isDisplayed == true)
		show = update = false;
	// update editor with latest text
	if(update == true)
	{
		if(oGrid.isDisplayed)
			oGrid.oEdit.setText(text);
		else
		{
			// find cell in grid and select it
			var r = null, c = null;
			for(var row = 0; row < 1000; row++)
			{
				if((r = oGrid.Rows.getRow(row)) == null) break;
				var iColCount = r.Band.Columns.length;
				for(var col = 0; col < iColCount; col++)				
				//for(var col = 0; col < 100; col++)
				{
					if((c = r.getCell(col)) == null) break;
					if(c.getValue() == text){row = 1000; break;}
				}
			}
			if(c != null)
			{
				c.setSelected(true);
				c.activate();
			}
			else
			{
				oGrid.clearSelectionAll();
				oGrid.setActiveCell(null);
			}
		}
	}
	// check current state of grid
	if(oGrid.isDisplayed == show)
		return;
	// show/hide grid
	oGrid.mainElement.style.display = show ? "block" : "none";
	oGrid.mainElement.style.visibility = show ? "visible" : "hidden";
	oGrid.isDisplayed = show;
	if(show)
		positionGrid(oGrid);
}
// set position of grid below/above TextEdit
function positionGrid(oGrid)
{
	var elem = oGrid.oEdit.Element;
	// left and top position of grid
	var x = 0, y = elem.offsetHeight;
	if(y == null) y = 0;
	// width and height of super parent (document)
	var w = 0, h = 0;
	while(elem != null)
	{
		if(elem.offsetLeft != null) x += elem.offsetLeft;
		if(elem.offsetTop != null) y += elem.offsetTop;
		h = elem.offsetHeight;
		w = elem.offsetWidth;
		elem = elem.offsetParent;
	}
	// check if grid fits below editor
	// if not, then move it above editor
	elem = oGrid.mainElement;
	if(y > h + oGrid.oEdit.Element.offsetHeight + window.document.body.scrollTop - y)
		y -= (elem.offsetHeight + oGrid.oEdit.Element.offsetHeight);
	// check if grid fits on the right from editor
	// if not, then move it to the left
	// 20 - extra shift for possible vertical scrollbar in browser
	if(x + elem.offsetWidth + 20 > w + window.document.body.scrollLeft)
		x = w - elem.offsetWidth - 20 + window.document.body.scrollLeft;
	oGrid.mainElement.style.left = x + "px";
	oGrid.mainElement.style.top = y + "px";
}
// process mouse click events for page: close drop-down
function globalMouseDown(evt)
{
	// reference to visible dropped-down grid
	var oGrid = null;
	var i = dropDownGrids.length;
	for(var i = 0; i < dropDownGrids.length; i++) if(dropDownGrids[i].isDisplayed)
	{
		oGrid = dropDownGrids[i];
		break;
	}
	// check if opened grid was found
	if(oGrid == null)
		return;
	// find source element
	if(evt == null) evt = window.event;
	if(evt != null)
	{
		var elem = evt.srcElement;
		if(elem == null) if((elem = evt.target) == null) o = this;
		while(elem != null)
		{
			// ignore events that belong to grid
			if(elem == oGrid.mainElement) return;
			elem = elem.offsetParent;
		}
	}
	// close grid
	showDropDown(oGrid, null, false, false);
}

///This method is to display the error message and set the focus on to the control for ASP site
function _ASP_DisplayErrorMessage(errNumber)
{
	var _strErrorString = new String("");
	var _strErrorNoHtWdth = new String("");
	var _arr_Error = new Array("");
	var _strHeight = new String("");
	var _strWidth = new String("");
	var _arr_Details = new Array("");
	
	var DivRef = document.getElementById('_Alert__msgPanel');
	var IfrRef = document.getElementById('_Alert__iframe_ALert');
	var tbl = document.getElementById('_tbl');
	
	IfrRef.style.display = '';
	IfrRef.style.visibility = '';

	IfrRef.style.width = DivRef.offsetWidth;
	IfrRef.style.height = DivRef.offsetHeight;
	IfrRef.style.top = DivRef.style.top;
	IfrRef.style.left = DivRef.style.left;
	IfrRef.style.zIndex = DivRef.style.zIndex - 1;
	IfrRef.style.display = "block";
	
	//tbl.style.width = DivRef.offsetWidth;
	//tbl.style.height = DivRef.offsetHeight;
	//tbl.style.top = DivRef.style.top;
	//tbl.style.left = DivRef.style.left;	
	
	_strErrorString = document.getElementById('_hdn_Errors').value;
	_arr_Error = _strErrorString.split("~");
	
	if (_arr_Error.length == 1)
	{
		_strErrorNoHtWdth = _arr_Error[0];
		_arr_Details = _strErrorNoHtWdth.split(";")		
		if (_arr_Details.length > 0)
		{
			if (errNumber == _arr_Details[0])
			{
				//document.getElementById("ctl00_Alert_spnMessage").innerText = _arr_Details[3];
				if (document.getElementById("_Alert_spnDescription") != null)
				{
					_DisableFormControls();
					_RemoveLink();
					
					if (window.navigator.appName == "Microsoft Internet Explorer")
						document.getElementById("_Alert_spnDescription").innerText = _arr_Details[4];						
					if (window.navigator.appName == "Netscape")		
					{
						document.getElementById("_Alert_spnDescription").textContent = _arr_Details[4];
					}
				}
				return false;
			}
		}
	}
	else if (_arr_Error.length > 1)
	{
		for(var _iCounter=0; _iCounter<_arr_Error.length; _iCounter++)
		{
			_strErrorNoHtWdth = _arr_Error[_iCounter];
			_arr_Details = _strErrorNoHtWdth.split(";")
			
			if (_arr_Details.length > 0)
			{
				if (errNumber == _arr_Details[0])
				{
					//document.getElementById("ctl00_Alert_spnMessage").innerText = _arr_Details[3];
					//alert(document.getElementById("_Alert_spnDescription").textContent); 
					if (document.getElementById("_Alert_spnDescription") != null)
					{
						_DisableFormControls();
						_RemoveLink();
					
						if (window.navigator.appName == "Microsoft Internet Explorer")
							document.getElementById("_Alert_spnDescription").innerText = _arr_Details[4];						
						if (window.navigator.appName == "Netscape")							
							document.getElementById("_Alert_spnDescription").textContent = _arr_Details[4];						
					}
					return false;
				}
			}
		}
	}
	return false;
}

//This method will disable the controls when the alert box is displayed.
function _DisableFormControls()
{
	if (document.getElementById('UltraWebMenu1_MainM') != null)
	{
		document.getElementById('UltraWebMenu1_MainM').disabled = true;
	}
	for(var iCount=0; iCount<=document.Form1.elements.length-1; iCount++)
	{
		// fix for fogbugz case 668.
		//In IE browser, onmouseover alert message is appearing.
		//We are not checking the button "btn_Save" for disabling this button
		if(document.Form1.elements[iCount].id!="ctl00__btn_Save")
		{
			if (document.Form1.elements[iCount] != null)
			{
				if (document.Form1.elements[iCount].id != '_btn_Close') 
					document.Form1.elements[iCount].disabled = true;
				if (document.Form1.elements[iCount].id == '_btn_Yes') 
					document.Form1.elements[iCount].disabled = false;
				if (document.Form1.elements[iCount].id == '_btn_Cancel') 
					document.Form1.elements[iCount].disabled = false;		
						
			}
		}
		else if(document.Form1.elements[iCount].id=="ctl00__btn_Save")
		{
			if (window.navigator.appName != "Microsoft Internet Explorer")
			{
				document.Form1.elements[iCount].disabled = true;						
			}	
		}		
	}
	window.status = "Done";
	
}

//This method will remove the link when the alert box is displayed.
function _RemoveLink()
{
	//alert(document.getElementsByTagName('a').length);
	if (document.getElementsByTagName('a').length > 0)
	{
		for(var iCount=0; iCount<=document.getElementsByTagName('a').length-1; iCount++)
		{
			if (document.getElementById('_hdn_Menus') != null)
			{
				if (document.getElementById('_hdn_Menus').value=='')
					document.getElementById('_hdn_Menus').value = document.getElementsByTagName('a')[iCount].id + '~' + document.getElementsByTagName('a')[iCount].href;
				else
					document.getElementById('_hdn_Menus').value = document.getElementById('_hdn_Menus').value + '@' + document.getElementsByTagName('a')[iCount].id + '~' + document.getElementsByTagName('a')[iCount].href;
			}
			
			if (document.getElementsByTagName('a')[iCount] != null)
				document.getElementsByTagName('a')[iCount].href = '#';
		}
	}
}

//This method is to enable the controls that are in search dialog. It is triggered when we close the 
//alert box in search dialog.
function _SearchDialogEnableFormControls()
{
	for(var iCount=0; iCount <= document._frmSearch.elements.length-1; iCount++)
	{
		if (document._frmSearch.elements[iCount] != null)
		{
			document._frmSearch.elements[iCount].disabled = false;			
						
		}
	}
	
	if (document.getElementById("_pnlSearchDate")!=null)
	{	
		if (igdrp_getComboById("_dtFromDate")!=null)
		{
			objdtFromDate = igdrp_getComboById("_dtFromDate");
			objdtFromDate.setValue("");
		}
		if (igdrp_getComboById("_dtToDate")!=null)
		{
			objdtToDate = igdrp_getComboById("_dtToDate");
			objdtToDate.setValue("");
		}
	}
	
}

//This method will enable the controls once the alert box is closed
function _EnableFormControls()
{
	if (document.getElementById('UltraWebMenu1_MainM') != null)
	{
		document.getElementById('UltraWebMenu1_MainM').disabled = false;
	}
	for(var iCount=0; iCount <= document.Form1.elements.length-1; iCount++)
	{
		if (document.Form1.elements[iCount] != null)
			document.Form1.elements[iCount].disabled = false;
	}
	if ((document.getElementById("LeftNav1_QuickCampaignCreate1__chk_QckCampaignPhoneNbrs") != null) && (document.getElementById("LeftNav1_QuickCampaignCreate1__txt_QckCampaignPhoneNbrs") != null) && (document.getElementById("LeftNav1_QuickCampaignCreate1__ddl_campaignList") != null))
	{
		if (document.getElementById("LeftNav1_QuickCampaignCreate1__chk_QckCampaignPhoneNbrs").checked)
		{
			document.getElementById("LeftNav1_QuickCampaignCreate1__txt_QckCampaignPhoneNbrs").disabled = false;
			document.getElementById("LeftNav1_QuickCampaignCreate1__ddl_campaignList").disabled = true;
		}
		else
		{
			document.getElementById("LeftNav1_QuickCampaignCreate1__txt_QckCampaignPhoneNbrs").disabled = true;
			document.getElementById("LeftNav1_QuickCampaignCreate1__ddl_campaignList").disabled = false;
		}		
	}
}
//This method will re-assign the value to the href once the alert box is closed
function _AssignLink()
{
	var _hdnString = new String('');
	var _linkArray = new Array();
	var _linkIDHref = new Array();
	
	if (document.getElementById('_hdn_Menus') != null)
	{
		if (document.getElementById('_hdn_Menus').value!='')
		{
			_hdnString = document.getElementById('_hdn_Menus').value;
			_linkArray = _hdnString.split('@');
			
			
			for(var iCount=0; iCount<=_linkArray.length-1; iCount++)
			{
				if (_linkArray.length > 0)
				{
					_hdnString = _linkArray[iCount];
					_linkIDHref = _hdnString.split('~');

					if (_linkIDHref.length > 0)
					{
						if (document.getElementsByTagName('a')[iCount] != null)
						{
							if (document.getElementsByTagName('a')[iCount].id ==_linkIDHref[0])
							{
								document.getElementsByTagName('a')[iCount].href = _linkIDHref[1];
							}
						}
					}
				}
			}
		}
		document.getElementById('_hdn_Menus').value = '';
	}
}

//show custom error message
function _ASP_DisplayCustomMessage(message)
{

	var _strErrorString = new String("");
	var _strErrorNoHtWdth = new String("");
	var _arr_Error = new Array("");
	var _strHeight = new String("");
	var _strWidth = new String("");
	var _arr_Details = new Array("");
	
	var DivRef = document.getElementById('_Alert__msgPanel');
	var IfrRef = document.getElementById('_Alert__iframe_ALert');
	var tbl = document.getElementById('_tbl');
	
	IfrRef.style.display = '';
	IfrRef.style.visibility = '';

	IfrRef.style.width = DivRef.offsetWidth;
	IfrRef.style.height = DivRef.offsetHeight;
	IfrRef.style.top = DivRef.style.top;
	IfrRef.style.left = DivRef.style.left;
	IfrRef.style.zIndex = DivRef.style.zIndex - 1;
	IfrRef.style.display = "block";
	if (message	!= null)
	{
		if (document.getElementById("_Alert_spnDescription") != null)
		{
			 _DisableFormControls();	
			 _RemoveLink();			
			if (window.navigator.appName == "Microsoft Internet Explorer")
				document.getElementById("_Alert_spnDescription").innerText = message;						
			if (window.navigator.appName == "Netscape")							
			{
				document.getElementById("_Alert_spnDescription").textContent = message;
			}
		}
	}
	return false;
}

//show custom error message
function _ASP_LeftNavDisplayCustomMessage(message)
{
	var _strErrorString = new String("");
	var _strErrorNoHtWdth = new String("");
	var _arr_Error = new Array("");
	var _strHeight = new String("");
	var _strWidth = new String("");
	var _arr_Details = new Array("");
	
	var DivRef = document.getElementById('LeftNav1_Alert__msgPanel');
	var IfrRef = document.getElementById('LeftNav1_Alert__iframe_ALert');
	var tbl = document.getElementById('LeftNav1_tbl');
	
	IfrRef.style.display = '';
	IfrRef.style.visibility = '';

	IfrRef.style.width = DivRef.offsetWidth;
	IfrRef.style.height = DivRef.offsetHeight;
	IfrRef.style.top = DivRef.style.top;
	IfrRef.style.left = DivRef.style.left;
	IfrRef.style.zIndex = DivRef.style.zIndex - 1;
	IfrRef.style.display = "block";
	if (message	!= null)
	{
		if (document.getElementById("LeftNav1_Alert_spnDescription") != null)
		{
			 //_DisableFormControls();	
			 //_RemoveLink();			
			if (window.navigator.appName == "Microsoft Internet Explorer")
				document.getElementById("LeftNav1_Alert_spnDescription").innerText = message;						
			if (window.navigator.appName == "Netscape")							
			{
				document.getElementById("LeftNav1_Alert_spnDescription").textContent = message;				
			}
		}
	}
	return false;
}

/*
Added the Applabs - This function will open New window
*/
function OpenNewPage(URL,WindowName)
{
	var	objWindow = window.open(URL,WindowName);

	if ( objWindow == "[object]" )
		objWindow.focus();
	else if (objWindow == null)
		alert( "Window is blocked with pop-up blocker.Please disable the popup blockers.");
}


/*
	Function Name		: CreditCardValidationwithType
	Parameters			: CreditCardNumber,CreditCardType
	Purpose				: To check the Credit Card Number Based On the Credit Card Type

*/

	function CreditCardValidationwithType(cardnumber,cardtype)
	{
		
		var isValid = false;
		var ccCheckRegExp = /[^\d ]/;   //This is for checking the cardNumber contains any Invalid Characters.
		isValid = !ccCheckRegExp.test(cardnumber);
		
		if (isValid)
		{
			var cardNumber = cardnumber.replace(/ /g,"");	 //This is for removing the Spaces. 
			var cardNumberLength = cardNumber.length;        //Card Number Length.
			
			var lengthIsValid = false;                 // This variable using for Length of the Credit Card is Valid or not
			var regexpIsValid = false;                 // This variable using for card number is match with particular regular expression.    
			var cardRegExp;		                       // This variable using to assign the Regulard expression value of the Particular Card      
				 
			switch(cardtype)
			{
				case "1":  // VISA -- 4    -- 13 Or 16 length
				lengthIsValid = (cardNumberLength == 16 || cardNumberLength == 13);
				cardRegExp = /^4/;			
				break;
				
				case "2":   // MasterCard -- 51 through 55 -- 16 length
				lengthIsValid = (cardNumberLength == 16);
				cardRegExp = /^5[1-5]/;
				break;		

				case "3":  // AMEX -- 34 or 37 -- 15 length
				lengthIsValid = (cardNumberLength == 15);
				cardRegExp = /^3(4|7)/;
				break;    
				
				case "4":   // Discover -- 6011 -- 16 length
				lengthIsValid = (cardNumberLength == 16);
				cardRegExp = /^6011/;
				break; 	
			}
	       regexpIsValid = cardRegExp.test(cardNumber);
	       isValid = (regexpIsValid && lengthIsValid);
        }        
		if (isValid)
		{
			 
			 var numberProduct;
			 var numberProductDigitIndex;
			 var checkSumTotal = 0;
				
			for (var digitCounter = cardNumberLength - 1; digitCounter >= 0; digitCounter--)
			{				
				checkSumTotal += parseInt (cardNumber.charAt(digitCounter));							
				digitCounter--;				
				numberProduct = String((cardNumber.charAt(digitCounter) * 2));									
				for (var productDigitCounter = 0;productDigitCounter < numberProduct.length; productDigitCounter++)
				{
				  checkSumTotal += parseInt(numberProduct.charAt(productDigitCounter));				 
			    }
			 }
			
			// Perform the final calculation, if the sum Mod 10 results in 0 then
			// it's valid, otherwise its false.    
			isValid = (checkSumTotal % 10 == 0);			
			return isValid;
		}
		else
		{	
			return isValid;			
		}       
        
    }
    
/*********
Function Name: _ValidatePhoneFormat()
Developed by : Upendra
Dt: 2/21/2006
*/
function _ValidatePhoneFormat(_taPhoneNumbers)
{
	var _isValidate= 0;
	var _taData = _taPhoneNumbers;
	//Replace the \n character
	//_taData = _taData.replace(/\r\n/g,'~');
	_taData = _taData.replace(/\n/g,'~');

	//Replace , # or comma(,), space, or new line with ~ Symbol
	_taData = _taData.replace(/\#|\,/g,'~');

	//Remove the brackets ( and ) and spaces
	_taData = _taData.replace(/\-|\(|\)|\ /g,'');
    _taData = _taData.replace(/[-\]\\!@#$%^&*_+|:"<>?`=;',.\/{}()\x5B\sa-zA-Z]/g, "");   
	//Replace , all double carrage returns or double delemeters without any chars then remove them
	_taData = _taData.replace(/~~/g,'~');

	var _commaString =  _taData.replace(/~/g,',')
	if (_commaString.lastIndexOf(",") == _commaString.length -1)
		_commaString = _commaString.substring(0, _commaString.length-1)

	//return the number of phone numbers in the string
	var _ArrPhoneNumbers = new Array();
	_ArrPhoneNumbers =  _commaString.split(",");
	_isValidate = _ArrPhoneNumbers.length ;

	// replace all comma's with new line so that they can be pasted into CSV
	_commaString = _commaString.replace(/\,/g,'\n');

	return _isValidate + "$$" + _commaString;
/*
	//Store the Phone numbers into Comma Separated String
	for(var intLoopCounter = 0; intLoopCounter < _ArrPhoneNumbers.length;intLoopCounter++)
	{
		var _strTemp = TrimTheString(_ArrPhoneNumbers[intLoopCounter]);	
		if (_strTemp.length > 0)
		{
			if(_commaString == "")
				_commaString = _strTemp;
			else 
				_commaString += "," + _strTemp; 
		}
	}
*/
	//Validate the Phone Numbers
	//Check for Numeric and Length 
	for(var intLoopCounter = 0; intLoopCounter < _ArrPhoneNumbers.length; intLoopCounter++)
	{
		var _strTemp = TrimTheString(_ArrPhoneNumbers[intLoopCounter]);
		
		if (isNaN(_strTemp))
		{
			_isValidate = false;
			break;
		}
		else if (_strTemp.length != 10 && _strTemp.length > 0) 
		{
			_isValidate = false;
			break;
		}
		else
			_isValidate = true;
	}


}


/*
 Name : _ASP_ShowMessage_ByMessage
 Parameter : Message , which will be popuplated on alert 
 Comments : This method is to display the error messages for ASP application
*/
function _ASP_ShowMessage_ByMessage(errMessage)
{
	var DivRef = document.getElementById('_Alert__msgPanel');
	var IfrRef = document.getElementById('_Alert__iframe_ALert');
	var tbl = document.getElementById('_tbl');
	
	IfrRef.style.display = '';
	IfrRef.style.visibility = '';

	IfrRef.style.width = DivRef.offsetWidth;
	IfrRef.style.height = DivRef.offsetHeight;
	IfrRef.style.top = DivRef.style.top;
	IfrRef.style.left = DivRef.style.left;
	IfrRef.style.zIndex = DivRef.style.zIndex - 1;
	IfrRef.style.display = "block";	
	
	_DisableFormControls();
	_RemoveLink();
	//Show the Alert Message 
	if (window.navigator.appName == "Microsoft Internet Explorer")
		document.getElementById("_Alert_spnDescription").innerText = errMessage;						
	if (window.navigator.appName == "Netscape")		
		document.getElementById("_Alert_spnDescription").textContent = errMessage;
	
	return false;
}

	/*Below functions used in Campaign's Bandwidth check. Called from the ASPHome.aspx*/
	//Timer for Bandwidth checking
	function timer()
	{
		var editor = igedit_getById("Timer");
		if(editor == null || !timerOn)
			return;
		var d = editor.getValue();
		if(d == null || d.getMilliseconds == null)
			return; 
		//Timer Increment value    
		var tempIncrementValue = d.getMilliseconds() + 15 * timerDelta;    
		d.setMilliseconds(tempIncrementValue);
		//Store the MilliSeconds into Variable
		countMilliSeconds = countMilliSeconds + tempIncrementValue;
		//Set the Timer value
		editor.setValue(d);
		var updatedjobstatusID = document.getElementById("hidUpdatedValue").value;
		
		//Bandwidth check status is changed
		if( updatedjobstatusID != "11")
		{
			timerOn = false;
			//Redirect the Page to Job Purchase
			if(CampaignID !="" && JobID !="")
				location.href ="ASPHome.aspx?menu=Campaigns&content=Purchase&CampaignID=" + CampaignID + "&jobID="+ JobID;
		}
		//If jobstatus is 11 and reminder of 5 seconds is zero then call the AJAX method
		else if (updatedjobstatusID == "11" && (countMilliSeconds % noOfMilliSecondsToCallAJAXCall == 0))
		{
			xmlhttpPost(strURL);
		}
	}
	/*AJAX Method*/
	function xmlhttpPost(strURL)
	{
		var xmlHttpReq = false;
		var self = this;
		// Mozilla/Safari
		if (window.XMLHttpRequest) {
			self.xmlHttpReq = new XMLHttpRequest();
		}
		// IE
		else if (window.ActiveXObject) {
			self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
		}
		//Open the page using 'post' method
		self.xmlHttpReq.open('POST', strURL, true);
		//Apply the header
		self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		//Check for the state
		self.xmlHttpReq.onreadystatechange = function() {
			if (self.xmlHttpReq.readyState == 4) {
				updatepage(self.xmlHttpReq.responseText);
			}
		}
		self.xmlHttpReq.send(getquerystring());	
	}

	function getquerystring()
	{			
		//Form the Querystring value
		qstr = 'JobID=' + escape(JobID);  // NOTE: no '?' before querystring
		return qstr;
	}

	function updatepage(str)
	{
		//Store the Updated Value from AJAX returned into hidden variable
		document.getElementById("hidUpdatedValue").value = str;	
	}

	/* End of Bandwidth check related functions */
	
	function VerifyUserInput(textValue, fileNameInvalidCharacters)
	{	  
	    var tempValue =  textValue; 
	    for (var loopCounter = 0; loopCounter < tempValue.length; loopCounter++) 
        {
	        if (fileNameInvalidCharacters.indexOf(tempValue.charAt(loopCounter)) != -1)
	        {
		        tempValue = tempValue.replace(tempValue.charAt(loopCounter), '#');  //'#' is temporary replaced character
	        }
        }
        if ((tempValue.indexOf('#') != -1) || (tempValue.indexOf('\\') != -1))
        {
            textValue = tempValue.replace(/\\|\#/g,'');
         }   
	    return textValue;	
	}
	
	/***************************************************************************************
	Function Name		: showInvalidCharacterErrorMessage
	Parameters			: invalidCharacters(list of invalid characters),controlCaption(the caption of the control)
	Purpose				: displays the Error message
	***************************************************************************************/
    function showInvalidCharacterErrorMessage(invalidCharacters,controlCaption)
    {
          if(invalidCharacters != null) 
        {
	        if (document.getElementById("sp_Text")!=null)
	        {
	            //show the error message
		       document.getElementById("sp_Text").innerText = InValidCharacters(invalidCharacters,controlCaption );
	        }
        }
        else if (document.getElementById("sp_Text")!=null) //clear the message control
        {
            document.getElementById("sp_Text").innerText = "";
        }
    }

    function InValidCharacters(invalidCharacters,controlName )
    { 
        return "The characters " + invalidCharacters + " are not allowed for " + controlName + ".";
    }
    
    
    /*
     This function ascertains if the string passed is a valid string.
     Check with the invalid characters list 'FileNameInvalidCharacters' from SRParameter table.
     parameter invalidCharacters holds invalid characters.
     parameter stringToValidate holds string to be validated.
     */
    function ContainsValidCharacters2( stringToValidate, invalidCharacters )
    { 
        var isValid = true;
	    if( TrimTheString( stringToValidate )!= "" )
	    {				
		    for ( var loopCounter = 0; loopCounter < stringToValidate.length; loopCounter++ ) 
		    {
			    if ( invalidCharacters.indexOf(stringToValidate.charAt(loopCounter)) != -1 )
  			    {
  				    isValid = false; //invalid characters present
  				    break;
  			    }
	        }
        }
        return isValid;
    }

        // only allows these 74 chars     
        function ContainsValidCharacters(_stringToValidate)
        {
            if (_stringToValidate.match(/^[\x21\x23\x24\x28\x29\x2B\x2C\x2D\x2E\x30\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3B\x3D\x40\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4A\x4B\x4C\x4D\x4E\x4F\x50\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5A\x5F\x61\x62\x63\x64\x65\x66\x67\x68\x69\x6A\x6B\x6C\x6D\x6E\x6F\x70\x71\x72\x73\x74\x75\x76\x77\x78\x79\x7A\x7E\s]*$/))
	            return true;
            else 
                return false;
        }
        // only allows numbers or dashes
        function ContainsVaildNumDash(_stringToValidate)
        {
            if (_stringToValidate.match(/[\x2D\d]{9,11}/))
	            return true;
            else 
                return false;
        }
        function GenericPageSubmitValidation()
        {
           RemoveInvaildCharacters();
        }
        /// after validation takes place, this will to threw all code if it finds invaild chars ANYWHERE
        /// it will remove it so the page can submit.  
        function RemoveInvaildCharacters()
        {  
            /// For each of the form on the page
            for(frmLoopCntr=0; frmLoopCntr <document.forms.length; frmLoopCntr++)
            {
                /// For each control in the form
                for(elementLoopCntr = 0; elementLoopCntr<document.forms[frmLoopCntr].elements.length; elementLoopCntr++)
                {
                    /// if the control is text box or TextArea then
                    if( document.forms[frmLoopCntr].elements[elementLoopCntr].type == "text" || document.forms[frmLoopCntr].elements[elementLoopCntr].type == "textarea" )
                        if (!document.forms[frmLoopCntr].elements[elementLoopCntr].value.match(/^[\x21\x23\x24\x28\x29\x2B\x2C\x2D\x2E\x2F\x30\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3B\x3D\x40\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4A\x4B\x4C\x4D\x4E\x4F\x50\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5A\x5F\x61\x62\x63\x64\x65\x66\x67\x68\x69\x6A\x6B\x6C\x6D\x6E\x6F\x70\x71\x72\x73\x74\x75\x76\x77\x78\x79\x7A\x7E\s]*$/))
	                        document.forms[frmLoopCntr].elements[elementLoopCntr].value = "";
                }
             }
        }
    // To Display the alert message.
    function AlertMessage(sError)
    {
        document.getElementById('_Alert__msgPanel').style.visibility = '';
        document.getElementById('_btn_Cancel').style.visibility = '';
        if (document.getElementById('_btn_Close')!=null && document.getElementById('_btn_Close').style.display == '')
	    {
			    document.getElementById('_btn_Close').focus();
	    }	
	    if (document.getElementById('_btn_Yes')!=null && document.getElementById('_btn_Yes').style.display == '')
	    {
			    document.getElementById('_btn_Yes').focus();
	    }	
            
        if (window.navigator.appName == "Microsoft Internet Explorer")
		    document.getElementById("_Alert_spnDescription").innerText = sError;						
	    if (window.navigator.appName == "Netscape")							
	       document.getElementById("_Alert_spnDescription").textContent = sError;	
    }

function SetCookieJavaScript(cookieName, cookievalue, expiryDays)
{
	var date = new Date();
	date.setTime(date.getTime() + expiryDays*24*60*60*1000);
	var expires = (expiryDays==0?"":"expires=" + date.toGMTString());
	
	document.cookie = cookieName +"=" + cookievalue + ";" + expires + "; path=/";
}

function GetCookieJavaScript(cookieName)
{
    var theCookie=""+document.cookie;
    var ind=theCookie.indexOf(cookieName);
    
    if (ind==-1 || cookieName=="") 
        return ""; 
    
    var ind1=theCookie.indexOf(';',ind);
    
    if (ind1==-1) ind1=theCookie.length; 
    
    return unescape(theCookie.substring(ind+cookieName.length+1,ind1));
}

/*----------------------------------------------------------------------------------------
    Method Name - removeJavascriptCodeInjectionCharacters()
    Purpose     - this method will remove all the Javascript Code Injection characters from all the text boxes and text areas
    When to Call- This method needs to be called before the validation of the page javascript, so that before the validation is done, the page can be cleaned.
----------------------------------------------------------------------------------------*/
function removeJavascriptCodeInjectionCharacters ()
{
    /// For each of the form on the page
    for(frmLoopCntr=0; frmLoopCntr <document.forms.length; frmLoopCntr++)
    {
        /// For each control in the form
        for(elementLoopCntr = 0; elementLoopCntr<document.forms[frmLoopCntr].elements.length; elementLoopCntr++)
        {
            /// if the control is text box or TextArea then
            if( document.forms[frmLoopCntr].elements[elementLoopCntr].type == "text" || document.forms[frmLoopCntr].elements[elementLoopCntr].type == "textarea" )
                document.forms[frmLoopCntr].elements[elementLoopCntr].value = document.forms[frmLoopCntr].elements[elementLoopCntr].value.replace(/[\\<>()}[{;='"\\/]/g, "").replace(/\x5D/g, "")
                // The following characters will be removed from the text if exists ===>   <>()[]{};'"\/=
                // the cleaned text will be placed back into the same field.
        }
    }
}
/*----------------------------------------------------------------------------------------
	Function Name		: textAreaLimit 
	Parameters			: None
	Purpose				: locks Text Area boxes down at value set by maxlength
	                      should be set on onkeypress
-------------------------------------------------------------------------------------------*/
function textAreaLimit(_maxLength,taObj,eventKeyCode) 
{
    //  8 = backspace , 33 = pageup, 34 = pagedown, 35 = end, 36 = home 
	//37 = leftArrow, 38 = uparrow, 39 = rightarrow, 40 = downarrow
	//45 = ins, 46 = delete
	
	//var taObj=event.srcElement;
	if (taObj.value.length==_maxLength*1) 
	{	
	    if(eventKeyCode == 8 || eventKeyCode == 33 || eventKeyCode == 34 || eventKeyCode == 35 
	    || eventKeyCode == 36  || eventKeyCode == 37 || eventKeyCode == 38 || eventKeyCode == 39 
	    || eventKeyCode == 40 || eventKeyCode == 45 || eventKeyCode == 46);
	    else
	        return false;
	 } 	    
}
/*----------------------------------------------------------------------------------------
	Function Name		: textAreaCount 
	Parameters			: visCnt count field
	Purpose				: locks Text Area boxes down at value set by maxlength
	                      should be set onkeyup
-------------------------------------------------------------------------------------------*/
function textAreaCount(_maxLength,taObj)//visCnt 
{ 
	//var taObj=event.srcElement;
	if (taObj.value.length>_maxLength*1) 
	    taObj.value=taObj.value.substring(0,_maxLength*1);
	//if (visCnt) 
	//    visCnt.innerText=taObj.maxLength-taObj.value.length;
}