var minYear=1900;
var maxYear=2100;
var dtCh="/";
function Chr(CharCode)
{
	return String.fromCharCode(CharCode);
}
	
function isInteger(s){
	var i;
    for (i = 0; i < s.length; i++){   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag){
	var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function isValidTime(S) {
  return /^(24):(00)|([01][0-9]|2[0-3]):([0-5][0-9])$/.test(S);
}
  
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 isDate(dtStr){
	var daysInMonth = DaysArray(12);
	var pos1=dtStr.indexOf(dtCh);
	var pos2=dtStr.indexOf(dtCh,pos1+1);
	var strMonth=dtStr.substring(pos1+1,pos2);
	var strDay=dtStr.substring(0,pos1);
	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);
	if (pos1==-1 || pos2==-1){
		alert("The date format should be : dd/mm/yyyy");
		return false;
	}
	if (strMonth.length<1 || month<1 || month>12){
		alert("Please enter a valid month");
		return false;
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		alert("Please enter a valid day");
		return false;
	}
	if (strYear.length != 4 || year==0){
		alert("Please enter a valid 4 digit year");
		return false;
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		alert("Please enter a valid date");
		return false;
	}
return true;
}

function isDateWithDash(dtStr){
	var daysInMonth = DaysArray(12);
	var pos1=dtStr.indexOf('-');
	var pos2=dtStr.indexOf('-',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);
	if (pos1==-1 || pos2==-1){
		alert("The date format should be : mm-dd-yyyy");
		return false;
	}
	if (strMonth.length<1 || month<1 || month>12){
		alert("Please enter a valid month");
		return false;
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		alert("Please enter a valid day");
		return false;
	}	
	if (strYear.length != 4 || year==0){
		alert("Please enter a valid 4 digit year");
		return false;
	}
	if (dtStr.indexOf('-',pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, '-'))==false){
		alert("Please enter a valid date");
		return false;
	}
return true;
}

	/*
	*	Validateing whether Field contain Numeric Data
	*/

	function validateFieldIsNumeric(txtField,errorMessage)
	{
		var strAllowed='0123456789.-';
		var isNumeric = true;
		for(i=0;i<value.length;i++)
		{
			if(strAllowed.indexOf(value.charAt(i)) == -1)
			{
				isNumeric=false;
				break;
			}
		}
		if(!isNumeric)
		{
			alert(errorMessage);
			txtField.focus();
			return false;
		}

		return true;
	}

	function isNumeric(value)
	{
		 /*
		  var expression = new RegExp(/^\d+$/);//exression to find out no exist.
		  var test=expression.test(value);
  	  if(!test && value.length!=0)
		  {
				return false;
		  }
		*/
			var strAllowed='0123456789.-';
			var isNumeric = true;
			for(i=0;i<value.length;i++)
			{
				if(strAllowed.indexOf(value.charAt(i)) == -1)
				{
						isNumeric=false;
						break;
				}
			}
			return isNumeric;
	}
	
	function isNumericUnsigned(value)
	{
			var strAllowed='0123456789.';
			var isNumeric = true;
			for(i=0;i<value.length;i++)
			{
				if(strAllowed.indexOf(value.charAt(i)) == -1)
				{
						isNumeric=false;
						break;
				}
			}
			return isNumeric;
	}

	function validateFieldIsEmail(strEmail)
	{
		  var value=strEmail;
		  var expression = new RegExp(/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/);//exression to find out no exist.
		  var test=expression.test(value);
	  	  if(!test && value.length!=0)
		  {
			return false;
		  }
		  return true;
	}

	function isEmail(value)
	{
		  /*
			var expression = new RegExp(/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/);//expression to find out no exist.
		  var test=expression.test(value);
  	  if(!test && value.length!=0)
		  {
				return false;
		  }
		  return true;
			*/
			var EmailOk  = true
			var AtSym    = value.indexOf('@')
			var Period   = value.lastIndexOf('.')
			var Space    = value.indexOf(' ')
			var Length   = value.length - 1   // Array is from 0 to length-1
			
			if ((AtSym < 1) ||                     // '@' cannot be in first position
	  	  		(Period <= AtSym+1) ||             // Must be atleast one valid char btwn '@' and '.'
		   		(Period == Length ) ||             // Must be atleast one valid char after '.'
			    (Space  != -1))                    // No empty spaces permitted
		   {  
    		  EmailOk = false
		   }
			return EmailOk;
	}



	function SetAllCheckBoxes(FormName, FieldName, CheckValue)
	{
		if(!document.forms[FormName])
			return;
		var objCheckBoxes = document.forms[FormName].elements[FieldName];
		if(!objCheckBoxes)
			return;
		var countCheckBoxes = objCheckBoxes.length;
		if(!countCheckBoxes)
			objCheckBoxes.checked = CheckValue;
		else
			// set the check value for all check boxes
			for(var i = 0; i < countCheckBoxes; i++)
				objCheckBoxes[i].checked = CheckValue;
	}

	function checkAll(formName,chkBoxName)
	{
		if(document.forms[formName].chkAll.checked == true)
		{
			SetAllCheckBoxes(formName,chkBoxName, true);
		}
		else
		{
			SetAllCheckBoxes(formName,chkBoxName, false);
		}
	}
	//open a window
	function my_win1(intProductID)
	{
		window.open('pm_setSortOrder.cfm?intProductID='+intProductID,'mywindow1','width=400,height=400,left=10,top=10,toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,copyhistory=no,resizable=no');
	} //END IF

	//validating textarea field
	function countDown(inputField,formName,strCountField,maxNumber)
	{
		var inputStr;
		var strlength;
		var inputStr=inputField.value
		if (inputStr != "")
		{
			strlength= inputStr.length;
			if (strlength > maxNumber )
			{
				inputField.value=inputStr.substring(0,maxNumber);
				charleft = 0;
			}
			else	
			{
				charleft = maxNumber - strlength;
			}
			document.forms[formName].elements[strCountField].value=charleft;
		}	
	}
	//for hiding div on click
	function hideDiv(chkBox,dvID)
	{		
		var dv=document.getElementById(dvID);
		dv.style.display = "none";
		if (!chkBox.checked)
		{
			dv.style.display = "none";
		}
		else if(chkBox.checked)
		{
			dv.style.display = "";
		}
	}//end function
	
	//general validation routine for empty field
	function isValid(rField,formIndex)
	{
		for (var n_key in rField) 
		{
			var obj=document.forms[formIndex][n_key];
			if(!obj)
			{	
				alert("Error: ["+n_key+"] not defined in the form");
				return false;
			}
			//field validation
			switch(rField[n_key]['type'])
			{
				case 'text':
					if(isEmpty(obj,rField[n_key]))
						return false;
					//checking minimum length
					if(rField[n_key]['min_char'])
					{
						if(rField[n_key]['echo']) obj.value.length;
						if(obj.value.length < rField[n_key]['min_char'])
						{
							alert('Error! [ '+rField[n_key]['name']+' ] at least '+rField[n_key]['min_char']+' charecter long.' );
							obj.focus();
							return false;
						}
					}
					break;
				case 'numeric':
					if(!isInteger(obj.value))
					{
						alert('Error! in-valid [ '+rField[n_key]['name']+' ]');
						obj.focus();
						return false;
					}
					//checking minimum length
					if(rField[n_key]['min_char'])
					{
						if(rField[n_key]['echo']) obj.value.length;
						if(obj.value < rField[n_key]['min_char'])
						{
							alert('Error! [ '+rField[n_key]['name']+' ] at least '+rField[n_key]['min_char']+' charecter long.' );
							obj.focus();
							return false;
						}
					}
					break;
				case 'select':
					if(!isSelected(obj,rField[n_key]))
						return false;
					break;
				case 'radio':
					if(!isChecked(obj,rField[n_key]))
						return false;
					break;
				case 'email':
					if(isEmpty(obj,rField[n_key]))
						return false;
					else if(!isEmail(obj.value))
					{
						alert('Error! in-valid [ '+rField[n_key]['name']+' ]');
						obj.focus();
						return false;
					}
					break;
				case 'date':
					if(isEmpty(obj,rField[n_key]))
						return false;
					else if(!isDate(obj.value))
					{
						alert('Error! in-valid [ '+rField[n_key]['name']+' ]');
						obj.focus();
						return false;
					}
					break;
			}//end switch
		}
		return true;
	}
	//checking empty text fields
	function	isEmpty(obj,rField)
	{
		if(obj.value=="")
		{
			alert('Error! Empty [ '+rField['name']+' ] field is not allowed');
			obj.focus();
			return true;
		}
		return false;
	}
	//checking empty select fields
	function	isSelected(obj,rField)
	{
		if(obj.selectedIndex==0)
		{
				alert('Error! Select any option of [ '+rField['name']+' ] ');
				obj.focus();
				return false;
		}
		return true;
	}
	//checking redio fields selection 
	function	isChecked(rObj,rField)
	{
		var isChecked=false;
		for(i=0;i<rObj.length;i++)
		{
				if(rObj[i].checked)
				{
					isChecked=true;
					break;
				}
		}
		if(!isChecked)
		{
			alert('Error! Select any option of [ '+rField['name']+' ] ');
			rObj[0].focus();
			return false;
		}
		return true;
	}

	function validMinimumChar(obj,rField)
	{
		if(obj.value.length < rField['min_char'])
		{
			alert('Error! [ '+rField['name']+' ] at least '+rField['min_char']+' charecter long.' );						
			obj.focus();
			return false;
		}
	}
	function isArray(obj)
	{
		return(typeof(obj.length)=="undefined")?false:true;
	}


/*Functions for trimming the string*/
function xreplace(checkMe,toberep,repwith)
{
	var temp = checkMe;		
	var i = temp.indexOf(toberep);
	
	while(i > -1)	
	{		
		temp = temp.replace(toberep, repwith);			
		i = temp.indexOf(toberep, i + repwith.length + 1);		
	}		
	return temp;	
}

function Trim(sString) 
{
	while (sString.substring(0,1) == ' ')
	{
		sString = sString.substring(1, sString.length);
	}
	while (sString.substring(sString.length-1, sString.length) == ' ')
	{
		sString = sString.substring(0,sString.length-1);
	}	
	
	sString=trimAllWithCaret(sString);
	
	return sString;
}

function trimAllWithCaret(sString) 
{	
	while (sString.substring(0,1).charCodeAt(0) == 13)
	{
		sString = sString.substring(1, sString.length);
	}
	while (sString.substring(0,1).charCodeAt(0) == 10)
	{
		sString = sString.substring(1, sString.length);
	}
	while (sString.substring(sString.length-1, sString.length).charCodeAt(0) == 13)
	{
		sString = sString.substring(0,sString.length-1);
	}
	while (sString.substring(sString.length-1, sString.length).charCodeAt(0) == 10)
	{
		sString = sString.substring(0,sString.length-1);
	}
	return sString;
}

function formatFloat(aFloat, aPrecision)
{
	try
	{
		precision = default_precision;
		if(!isNaN(aPrecision))
			if(Math.abs(aPrecision)<=10)
				precision = aPrecision;
	}
	catch(e)
	{
		precision = default_precision;
	}
	try 
	{
		number = parseFloat(aFloat+'');
		if(isNaN(number))
			return "NaN";
	}
	catch(e)
	{
		return "NaN";
	}

	number = Math.round(number * Math.pow(10, precision)) / Math.pow(10,precision);
	integerpart = '' + ((number<0) ? Math.ceil(number) :
	Math.floor(number));
	decimalpart = Math.abs(Math.round((number - integerpart)*(Math.pow(10,precision))));
	if(decimalpart<10)
		decimalpart="0"+decimalpart;
		
	if(decimalpart==0)
		decimalpart="00";
		
	var buff = "";
	
	for(j=-1, i=integerpart.length; i>=0; i--, j++)
	{
		if((j%3) == 0 && j>1)
		buff = thousand_sep + buff;
		buff = integerpart.charAt(i) + buff;
	}
	
	if(precision>0)
		return buff+decimal_point+decimalpart;
		
	return buff;
}

function formatInt(aInt)
{
	return formatFloat(aInt,0);
}


function noCopyMouse(e) {
        var isRight = (e.button) ? (e.button == 2) : (e.which == 3);
        if(isRight) {
            alert('Copy & Paste is disabled on this input!');
            return false;
        }
        return true;
    }

    function noCopyKey(e) {
        var forbiddenKeys = new Array('c','x','v');
        var keyCode = (e.keyCode) ? e.keyCode : e.which;
        var isCtrl;

        if(e)
            isCtrl = e.ctrlKey
        else
            isCtrl = (window.Event) ? ((e.modifiers & Event.CTRL_MASK) == Event.CTRL_MASK) : false;
    
        if(isCtrl) {
            for(i = 0; i < forbiddenKeys.length; i++) {
                if(forbiddenKeys[i] == String.fromCharCode(keyCode).toLowerCase()) {
                    alert('Copy & Paste is disabled on this input!');
                    return false;
                }
            }
        }
        return true;
    }