/*
	.File name	: utilities.js
	.Implementer: Tran Xuan Dong	
	.Description: 
	.History	: 
		Create date: 04-15-2003
*/
/*-------------------------- Some JavaScript utilities --------------------------------

This file contains source code of some utilities that are used usually  in JavaScript 
programming:
- isDigit : test it a character is a digit or not.
- trimLeft : cut leading blank spaces of a string.
- trimRight: cut trailing blank spaces of a string.
- trim: cut all leading and trailing blank spaces of a string
- isPosInt: test if a string has the format of a positive integer number or not.
- isPosReal: test if a string has the format of a positive real number or not. The decimal 
			 separator must be ".".
- isValidDate: test if a string has the format of a valid date or not. Format :mm/dd/yyyy
- isEmail: test if a string is a valid e-mail address or not
- isZip: test if a string has the format of a US zip code or not.
- getFileName: return the file name form the full file name.
- getFileExt: return the file extenstion from the full file name.
- checkFrmEmpty: is valid of text box.
- checkPhoneNum: Check validate phone number.
- checkInteger:
- myParseInt:
- checkFloat: 
- checkNumberRange:
- checkCardType:

--------------------------------Implementation ---------------------------------------*/
/*Check object is empty true: not empty, false: is empty*/
function checkFrmEmpty(FrmName,FieldName,strMassage){
	var fName = eval("document."+FrmName+"."+FieldName);
	
	if(fName.value==""){
		alert(strMassage);
		fName.focus();
		return false;
	}	
	return true;
}
/*-------- Begin check phone number -----------*/
function checkPhoneNum(obj_val)
{
	var number_format = "0123456789()- ";
	for (var i = 0; i < obj_val.length; i++)
	{
		check_char = number_format.indexOf(obj_val.charAt(i))
		if (check_char < 0)
			return false;
	}
	return true;
}

//Validate file format
function fileFormat(FrmName,FieldName){
	var fName = eval("document."+FrmName+"."+FieldName);
	sValue = fName.value;
	sValue = sValue.toLowerCase();
	if(sValue!="" ){
		nlen = sValue.length
		pos = sValue.indexOf(".",0)
		ext = sValue.substring(pos,nlen)
		if (!((ext==".jpg" )||(ext==".gif")||(ext==".bmp")||(ext==".swf"))){
			alert('You have to input image file in these formats : *.gif, *.jpg, *.bmp, *.swf .')
			fName.select();
			fName.focus();
			return false;
		}    
	}
	return true;
}
//Validate file flash format 
function fileFlash(FrmName,FieldName){
	var fName = eval("document."+FrmName+"."+FieldName);
	sValue = fName.value;
	sValue = sValue.toLowerCase();
	if(sValue!="" ){
		nlen = sValue.length
		pos = sValue.indexOf(".",0)
		ext = sValue.substring(pos,nlen)
		if (!((ext==".swf"))){
			alert('You have to input image file in this format : *.swf.')
			fName.select();
			fName.focus();
			return false;
		}    
	}
	return true;
}

function checkPhone(obj){

    if (obj.length == 0)
        return true;
		
    if (obj.length != 12)
        return false;

	// check if first 3 characters represent a valid area code
    if (!checkInteger(obj.substring(0,3)))
		return false;
    else if (!checkNumberRange((eval(obj.substring(0,3))), 100, 1000))
		return false;

	// check if area code/exchange separator is either a'-' or ' '
	if (obj.charAt(3) != "-" && obj.charAt(3) != " ")
        return false

	// check if  characters 5 - 7 represent a valid exchange
    if (!checkInteger(obj.substring(4,7)))
		return false;
    else if (!checkNumberRange((eval(obj.substring(4,7))), 100, 1000))
		return false;
	
	// check if exchange/number separator is either a'-' or ' '
	if (obj.charAt(7) != "-" && obj.charAt(7) != " ")
        return false;

	// Make sure last for digits are a valid integer
	return checkInteger(obj.substring(8,12));
}
/*-------- End check phone number -----------*/
/*--------Bengin check number------------------*/
function checkInteger(obj_val)
{
	var number_format = "0123456789,.";
	for (var i = 0; i < obj_val.length; i++)
	{
		check_char = number_format.indexOf(obj_val.charAt(i))
		if (check_char < 0)
			return false;
	}
	return true;
}

function myParseInt(str)
{
	while((str.length > 0) && (str.charAt(0) == '0'))
	    str = str.substring(1,str.length);
	if (!checkInteger(str))
		return 0;
	return parseInt(str);
}

function checkFloat(obj_val)
{
	var number_format = "0123456789.";
	for (var i = 0; i < obj_val.length; i++)
	{
		check_char = number_format.indexOf(obj_val.charAt(i))
		if (check_char < 0)
			return false;
	}
	var pos = obj_val.indexOf('.');
	if (pos==0 || (pos>0 && obj_val.indexOf('.',pos+1)>=0))
		return false;
	return true;
}

function checkNumberRange(object_value, min_value, max_value)
{
// check minimum
	if (min_value != null)
	{
		if (object_value < min_value)
			return false;
	}

// check maximum
	if (max_value != null)
	{
		if (object_value > max_value)
			return false;
	}
	
	//All tests passed, so...
	return true;
}
/*-------End check number------------------*/
/*
isDigit
Check if a character is a digit or not
*/
function isDigit(c)
{
if((c=='0')||(c=='1')||(c=='2')||(c=='3')||(c=='4')||(c=='5')||(c=='6')||(c=='7')||(c=='8')||(c=='9'))
	return true;
else
	return false;
}

/*
 trimLeft
 Remove all spaces at the beginning of a string
*/
function trimLeft(s)
{
 var i;
 i=0;
 var n;
 n = s.length;
 while((i<n)&&(s.charAt(i)==' ')) i++;
	s = s.substring(i);
 return(s);
} 

/*
 trimRight
 Remove all spaces at the end of a string
*/
function trimRight(s)
{
 var n;
 n = s.length;
 var i;
 i = s.length-1;
 while((i>=0)&&(s.charAt(i)==' ')) i--;
	s = s.substring(0,i+1);
 return(s);
}

/* 
 trim
 Remove all leading and trailing spaces in a string
*/
function trim(s)
{
 s = trimLeft(s);
 s = trimRight(s);
 return(s);
}  

/*
 isPosInt
 check if a string is a valid positive integer
*/
function isPosInt(s)
{
 var n;
 n = s.length
 if(n==0) return false;
 for(i=0;i<n;i++)
	if(!isDigit(s.charAt(i))) return false;
 return true;
}

/*
 isPosReal
 check if  a string is a valid positive real number or not (. as decimal number)
*/
function isPosReal(s)
{
 var dot;
 s = trim(s);
 dot =0;
 for(i=0;i<s.length;i++)
	if(!isDigit(s.charAt(i))) 
		{
			if(s.charAt(i)=='.') 
				{
					dot++;
					if(i==s.length-1) return false;
					if(dot>1) return false;
				}
			else return false;	
		}
 return true;
}

/*
 isValidDate
 check if a string is a valid date. The format of date can be specified 
 1- is mm/dd/yyyy
 2- is dd/mm/yyyy
 3 -is mm/dd/yy
 4 -is dd/mm/yy 	
*/
function isValidDate(strDate,intFormatDate)
{
 var m;
 var d;
 var y;
 var i1;
 var i2;
 
 if((intFormatDate!=1)&&(intFormatDate!=2)&&(intFormatDate!=3)&&(intFormatDate!=4)) return false;

 strDate=trim(strDate);
 if(strDate=="") return false;
 i1 = strDate.indexOf("/")
 if(i1<0) return false;
 
 if((intFormatDate==1)||(intFormatDate==3))
 	m = strDate.substring(0,i1);
 else
	d = strDate.substring(0,i1);

  
 i2= strDate.indexOf("/",i1+1)
 if(i2<0) return false;

 if((intFormatDate==1) || (intFormatDate==3))
	d = strDate.substring(i1+1,i2);
 else
	m = strDate.substring(i1+1,i2);
 
 y = strDate.substring(i2+1)

 if((m=="")||(d=="")||(y=="")) return false;
 if((m==0)||(d==0)) return false;
 if(!isPosInt(m))
 	 return false;
 else
 	{	
	 m = parseInt(m);
	 if(m>12) return false;
 	}

 if(!isPosInt(y))
 	 return false;
 else
	{
	 y = parseInt(y)
	 if(y>9999) return false;
	 if((y>=100)&&(y<1900)) return false;
	}

 if(!isPosInt(d))
 	 return false;
 else
	{
	 d = parseInt(d)
	 if((m==1)||(m==3)||(m==5)||(m==7)||(m==8)||(m==10)||(m==12))
		 if(d>31) return false;
 	 if((m==4)||(m==6)||(m==9)||(m==11))
		if(d>30) return false;

	 if(m==2)
		{
		 if(d>29) return false;
		 if((y%4)!=0) // not a leap year
		 	if(d>28) return false;
		}
	}

return true
}

/*
    compare two date.
    return :
        start <= end    :   true
        start > end     :   false
*/
function compareDate(start,end){
    
    //check data pass
   // if((start.length == 0) || (end.length==0) ) return false;
    
    //create two Date objects
    var s = new Date(start);
    var e = new Date(end);
    
    //get month, year, date of date objects
    var s_y = parseInt(s.getYear());
    var s_m = parseInt(s.getMonth());
    var s_d = parseInt(s.getDate());
    
    var e_y = parseInt(e.getYear());
    var e_m = parseInt(e.getMonth());
    var e_d = parseInt(e.getDate());
    
    //compare year , month and day of them
    if( s_y <= e_y){ // compare year
        if(s_y == e_y){
            if(s_m <= e_m){//compare month
                if(s_m == e_m ){
                    if(s_d <= e_d){// compare date
                        return true;
                    }else{
                        return false;
                    }//end compare date
                }
                return true;
            }else{
                return false;
            }// end compare month
        }    
        return true;
    }else{
        return false
    }// end compare year
            
}


/*
 isEmail
 check if an email address is valid (format only) 
*/
function isEmail(strEmail)
{
 var intlen;
 var ctmp;
 strEmail = trim(strEmail);
 if(strEmail=='') return false;
 intlen=strEmail.length;
 if(intlen<5) return false;
 if(strEmail.indexOf('@')==-1) return false;
 if(strEmail.indexOf('.')==-1) return false;
 if(intlen - strEmail.lastIndexOf('.') -1 > 3) return false; 
 if((strEmail.indexOf("_")!=-1) && (strEmail.lastIndexOf("_") > strEmail.lastIndexOf("@"))) return false;
 if(strEmail.lastIndexOf(".") <= strEmail.lastIndexOf("@")+1)  return false;
 if(strEmail.indexOf("@")!=strEmail.lastIndexOf("@")) return false;
 if(intlen -1 == strEmail.lastIndexOf('.')) return false;
 if(strEmail.charAt(strEmail.indexOf('@')+1)=='.') return false;
 if(strEmail.indexOf(" ")!=-1) return false;
 if(strEmail.indexOf("..")!=-1) return false;
 
 strEmail=strEmail.toLowerCase();
 for(intcnt=0;intcnt<intlen;intcnt++)
	{
	 ctmp = strEmail.charAt(intcnt)
	 if((!isDigit(ctmp))&& ((ctmp>'z')||(ctmp<'a')) && (ctmp!='-') && (ctmp!='.') && (ctmp!='@') && (ctmp!='_')) return false;
	}

return true	;
}

/*
 isZip
 receive  a string, return true if it has a valid format of US 5 digits zip code.
*/
function isZip(str)
{
 str=trim(str);
 if(str=='') return false;
 if(str.length!=5) return false;
 if(!isPosInt(str)) return false;
 return true;
}

/*
getFileName
receive a full path file name, return only the file name
	ex: input = C:\Windows\myfile.txt
	output = myfile.txt
*/
function getFileName(str)
{
 var bpos
 var filename
 if((str=='')||(str.indexOf("\\")==-1)) return(str);
 bpos = str.lastIndexOf("\\");
 filename = str.substring(bpos+1,str.length)
 return(filename);
}

/* 
 getFileType
 receive a full path file name, return only the file extension
 ex: input = C:\Windows\myfile.txt
  	 output = txt
*/
function getFileType(str)
{
 var filename;
 var fileext;
 var dotpos;
 fileext ='';
 filename = getFileName(str);
 dotpos = filename.lastIndexOf(".");
 
 if(dotpos!=-1)
	{
		fileext = filename.substring(dotpos+1,filename.length);
		fileext = fileext.toLowerCase();
	}
 else
	{
		fileext = '';
	}
 return(fileext);
}
//-->
//	@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
//	@	Description		: This function is to check for user input their card type and card number 
//  @                     
//	@	Pages Affected  : Checkout2.cfm
//  @	Function Name		: cardType()									
//	@	
//	@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
function checkCardType(frmName,nCardNum,nCardType,nMonthExp,nYearExp){
	//var f = document.frmCreditCard;
	var CardNum = eval("document."+frmName+"."+nCardNum);
	var MonthExp = eval("document."+frmName+"."+nMonthExp);
	var YearExp = eval("document."+frmName+"."+nYearExp);
	var CardType = eval("document."+frmName+"."+nCardType);
	
	var date = new Date();
	var month = date.getMonth();
	var year = date.getYear();
	
	if(navigator.appName == "Microsoft Internet Explorer")
	{
		if(year < 100) year = parseInt(year) + 1900;
	}
	else
	{
		year = 1900 + parseInt(year);
	}
	
	if((CardNum.value == "") || (parseInt(valcard(frmName,nCardNum,nCardType)) == 0))	{
		alert("Please enter a valid CardNumber");
		CardNum.focus();
		CardNum.select();
		return false;
	}
	if(parseFloat(MonthExp.options[MonthExp.selectedIndex].value) == 0){
		alert("Please select a expiry month");
		MonthExp.focus();
		return false;
	}
	if(parseFloat(YearExp.options[YearExp.selectedIndex].value) == 0)	{
		alert("Please select a expiry year");
		YearExp.focus();
		return false;
	}
	if((parseFloat(YearExp.options[YearExp.selectedIndex].value) < year)){
		alert("Card expiry year must be greater than current date!");
		YearExp.focus();
		return false;
	}
	if((parseFloat(YearExp.options[YearExp.selectedIndex].value) == year) && (parseFloat(MonthExp.options[MonthExp.selectedIndex].value) < parseInt(month+1))){
		alert("Card expiry month must be greater than current date!");
		MonthExp.focus();
		return false;
	}
	return true;
}
// End of the function cardType(type,option)
//	@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
//	@	Description			: This function is to validate card number.
//	@	Pages Affected  	: checkout2.cfm
//  @	Function Name		: valcard()									
//	@	Input Parameters	: null
//	@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

function valcard(frmName,nCardNum,nCardType)
{	
	//var f = document.frmCreditCard;
	var CardNum = eval("document."+frmName+"."+nCardNum);
	var Type = eval("document."+frmName+"."+nCardType)
	var cardNumber,cardType,Checksum,Flag,Counter,PartNumber,Number;
	
	cardType= Type.options[Type.selectedIndex].value;
		
	cardNumber=trim(CardNum.value);
	var length = cardNumber.length;

	if( length == 0 )
		return(0);				

	var validate=/(^\d+$)/
	if (validate.test(cardNumber)==false)
		 return(0);

	if (cardType == 3){	
			if( length != 15 ) {
				return(0);
			}
			var prefix = parseInt( cardNumber.substring(0,2));
			if( prefix != 34 && prefix != 37 ) {
				return(0);
			}
	}
	else if (cardType == 6){
			if( length != 16 ) {
				return(0);
			}
			var prefix = parseInt( cardNumber.substring(0,4));
			if( prefix != 6011 ) {
				return(0);
			}
	}
	else if (cardType == 5){
			if( length != 16 ) {
				return(0);
			}
			var prefix = parseInt( cardNumber.substring(0,2));
			if( prefix < 51 || prefix > 55) {
				return(0);
			}
	}
	else if (cardType == 4){
			if( length != 16 && length != 13 ) {
				return(0);
			}
			var prefix = parseInt( cardNumber.substring(0,1));
			if( prefix != 4 ) {
				return(0);
			}
	}

	Counter=length;
	Checksum=0;
	Number=0;
	PartNumber='';
	Flag=0;
	while(Counter > 0) {		
		PartNumber = cardNumber.charAt(Counter-1);
		Number = parseInt(PartNumber);
		if (Flag) {
			Number*=2;
			if (Number >= 10) Number-=9;
		}
		Checksum +=	Number;
		Flag=!(Flag)
		Counter = Counter -1;
	}
	if (Checksum%10 == 0)
		return(1); 
	else
		return(0);
		
}
// End of the function valcard()
function doDelete(frmName,MessageName)
{
	var objForm = eval("document."+frmName);
	var nCount = parseInt(objForm.hidRecordCount.value);
	var nCheckedCount = 0;
		
	if (nCount == 0)
	{
		alert('There is no '+MessageName+' to delete!');
		return;
	}

	if (nCount > 1)
	{
		for (i=0;i<nCount;i++)
		{
			if (objForm.chkDelete[i].checked)
			{
				nCheckedCount ++;
			}
		}
	}
	else
	{
		if (objForm.chkDelete.checked)
		{
			nCheckedCount ++;
		}
	}

	if (nCheckedCount == 0)
	{
		alert("You did not select any "+MessageName+" to delete!");
	}
	else
	{
		if (confirm("You are about delete " + nCheckedCount + " "+MessageName+"(s). Do you wish to continue?"))
		{
			objForm.submit();
		}
	}
}

function doActive(frmName,MessageName)
{
	var objForm = eval("document."+frmName);
	var nCount = parseInt(objForm.hidRecordCount.value);
	var nCheckedCount = 0;
	objForm.hdnActive.value = "A";
	if (nCount == 0)
	{
		alert('There is no '+MessageName+' to active!');
		return;
	}

	if (nCount > 1)
	{
		for (i=0;i<nCount;i++)
		{
			if (objForm.chkActive[i].checked)
			{
				nCheckedCount ++;
			}
		}
	}
	else
	{
		if (objForm.chkActive.checked)
		{
			nCheckedCount ++;
		}
	}

	if (nCheckedCount == 0)
	{
		alert("You did not select any "+MessageName+" to active!");
	}
	else
	{
		if (confirm("You are about to active " + nCheckedCount + " "+MessageName+"(s). Do you wish to continue?"))
		{
			objForm.submit();
		}
	}
}
//
function doDisapprove(frmName,MessageName)
{
	var objForm = eval("document."+frmName);
	var nCount = parseInt(objForm.hidRecordCount.value);
	var nCheckedCount = 0;
	objForm.hdnType.value = "D";	
	if (nCount == 0)
	{
		alert('There is no '+MessageName+' to disapprove!');
		return;
	}

	if (nCount > 1)
	{
		for (i=0;i<nCount;i++)
		{
			if (objForm.chkDisa[i].checked)
			{
				nCheckedCount ++;
			}
		}
	}
	else
	{
		if (objForm.chkDisa.checked)
		{
			nCheckedCount ++;
		}
	}

	if (nCheckedCount == 0)
	{
		alert("You did not select any "+MessageName+" to disapprove!");
	}
	else
	{
		if (confirm("You are about disapprove " + nCheckedCount + " "+MessageName+"(s). Do you wish to continue?"))
		{
			objForm.submit();
		}
	}
}

function doApprove(frmName,MessageName)
{
	var objForm = eval("document."+frmName);
	var nCount = parseInt(objForm.hidRecordCount.value);
	var nCheckedCount = 0;
	objForm.hdnType.value = "A";
	if (nCount == 0)
	{
		alert('There is no '+MessageName+' to aprrove!');
		return;
	}

	if (nCount > 1)
	{
		for (i=0;i<nCount;i++)
		{
			if (objForm.chkAppr[i].checked)
			{
				nCheckedCount ++;
			}
		}
	}
	else
	{
		if (objForm.chkAppr.checked)
		{
			nCheckedCount ++;
		}
	}

	if (nCheckedCount == 0)
	{
		alert("You did not select any "+MessageName+" to approve!");
	}
	else
	{
		if (confirm("You are about to approve " + nCheckedCount + " "+MessageName+"(s). Do you wish to continue?"))
		{
			objForm.submit();
		}
	}
}
function Check_Nums() 
{
   if ((event.keyCode < 46) || (event.keyCode > 57)) 
   {
	  return false;
	}
}
//------------------------------------------------
function OnMakeChange(MakeID,frmName,optModelName, optTrimID)
{
	var frm = eval("document."+frmName);
	var oModelName = eval("document."+frmName+"."+optModelName);
	len = oModelName.options.length;
	for(j=len-1;j>0;j--)
		oModelName.remove(j);
	
	if(optTrimID!=null){
		var oName = eval("document."+frmName+"."+optTrimID);
		len = oName.options.length;
		for(k=len-1;k>0;k--)
			oName.remove(k);
		oName.options[0].selected = true;
		
	}	
	
	for(i=0;i<MakeDatas.length;i=i+2)
	{
		if(MakeDatas[i]=="MakeData"+MakeID)
		{
			for(j=0;j<MakeDatas[i+1].length;j=j+2)
			{
				var oOption = document.createElement("OPTION");
				oModelName.options.add(oOption);
				oOption.text = MakeDatas[i+1][j+1];
				oOption.value =MakeDatas[i+1][j];		
			}
			break;
		}
	}
}
//--------------------------------------------------
function loadMake(frmName,optMakeName,MakeID){
	var frm = eval("document."+frmName)
	var oMakeName = eval("document."+frmName+"."+optMakeName);
			
	for(j=0;j<arrMake.length;j=j+2)
	{
		var oOption = new Option();
		oMakeName.options.add(oOption);
		oOption.text = arrMake[j+1];
		oOption.value =arrMake[j];
		if(MakeID==arrMake[j]){
			oOption.selected = true;
		}
	}
}
//Check form login
function frmIsvalid(){
	var frm = document.frmSellerLogin;
	
	if(frm.txtUserName.value==""){
		alert("You must enter user name.");
		frm.txtUserName.focus();
		return false;
	}
	if(frm.txtPassword.value==""){
		alert("You must enter password");
		frm.txtPassword.focus();
		return false;
	}
	return true;
}