//pre-condition:
//	negative and non-numeric values are guarded at host page
//
//check class order
//if total = 0 => false
//else
//	check if grade/class code duplicate
//	if yes => false
//
function checkClassOrderForm(form, total, mainCount, dessertCount, isDessertExisted){
	var i, j;
	
	for(i=0; i<mainCount; i++){
		if(checkMain_0(i)==false)
			return false;
	}

	//check grade/class code duplication
	var grade, classCode;
	for(i=0; i<total; i++){	//check main
		if(checkMain(i) == false)
			return false;

		grade = form.elements["grade_main_"+i].value;
		classCode = form.elements["classCode_main_"+i].value;

		if(form.elements["main_A_"+i].value > 0 || form.elements["main_B_"+i].value > 0 || form.elements["main_C_"+i].value > 0 || form.elements["main_D_"+i].value > 0){
			for(j=i+1; j<total; j++){
				if(form.elements["main_A_"+j].value > 0 || form.elements["main_B_"+j].value > 0 || form.elements["main_C_"+j].value > 0 || form.elements["main_D_"+j].value > 0){
					if(grade == form.elements["grade_main_"+j].value && classCode == form.elements["classCode_main_"+j].value){
						//alert("Duplicate grade/class for MAIN dish!");
						alert("相同班或級在主菜訂單!");
						return false;
					}
				}
			}
		}
	}

	if(isDessertExisted==true){	//check dessert
		for(i=0; i<dessertCount; i++){
			if(checkDessert_0(i)==false)
				return false;
		}

		for(i=0; i<total; i++){	
			if(checkDessert(i) == false)
				return false;
	
			grade = form.elements["grade_dessert_"+i].value;
			classCode = form.elements["classCode_dessert_"+i].value;

			if(form.elements["dessert_A_"+i].value > 0 || form.elements["dessert_B_"+i].value > 0 || form.elements["dessert_C_"+i].value > 0 || form.elements["dessert_D_"+i].value > 0){
				for(j=i+1; j<total; j++){
					if(form.elements["dessert_A_"+j].value > 0 || form.elements["dessert_B_"+j].value > 0 || form.elements["dessert_C_"+j].value > 0 || form.elements["dessert_D_"+j].value > 0){
						if(grade == form.elements["grade_dessert_"+j].value && classCode == form.elements["classCode_dessert_"+j].value){
							//alert("Duplicate grade/class for DESSERT!");
							alert("相同班或級在甜品訂單!");
							return false;
						}
					}
				}
			}
		}
	}

	return true;
}
/////////////////////////////////// END CLASS ORDER /////////////////////////////////////////	
	
	
	
//check if count field is valid - Integers
//check if choice field is A/B/C/D
//check if choice and count are both set
function checkAddTopupOrderForm(form, total, numOfChoice){
	if(form.elements["start_eff_date"].value==""){
		//alert("Please select a date!");
		alert("請選擇日期!");
		return false;
	}
	
	if(form.elements["contactPerson"].value==""){
		//alert("Please input a contact person!");
		alert("請輸入聯絡人!");
		return false;
	}
	
	
	var i;
	var validChar = "ABCD";
	var count, choice;
	var atLeastOne = false;
	for(i=0; i<total; i++){	//for each choice/count
		choice = trim(form.elements["choice_"+i].value);
		count = trim(form.elements["count_"+i].value);
		
		if(isNaN(count)){	//not valid integer
			//alert("Count must be numerics!");
			alert("請輸入數字在數量欄位!");
			return false;
		}else if(count==""){	//empty count
			if(choice!=""){		//but choice is set
				//alert("Please set the count!");
				alert("請輸入數字!");
				return false;
			}
		}else{	//valid count
			if(choice==""){	//no choice set for the count
				//alert("Please set the choice!");
				alert("請輸入選擇!");
				return false;
			}
			
			if(numOfChoice == 1 && choice!=validChar.charAt(0)) {
				alert("請確認選擇為A!");
				return false;
			}
			if(numOfChoice == 2 && choice!=validChar.charAt(0) && choice!=validChar.charAt(1)) {
				alert("請確認選擇為A/B!");
				return false;
			}
			if(numOfChoice == 3 && choice!=validChar.charAt(0) && choice!=validChar.charAt(1) && choice!=validChar.charAt(2)) {
				alert("請確認選擇為A/B/C!");
				return false;
			}
			if(numOfChoice == 4 && choice!=validChar.charAt(0) && choice!=validChar.charAt(1) && choice!=validChar.charAt(2) && choice!=validChar.charAt(3)) {
				alert("請確認選擇為A/B/C/D!");
				return false;
			}
			
			if(count!=0)
				atLeastOne = true;
		}
	}
	
	if(atLeastOne)
		return true;
	else		
		return false;
}

function checkModifyTopupOrderForm(form, total, numOfChoice){
	if(form.elements["start_eff_date"].value==""){
		//alert("Please select a date!");
		alert("請選擇日期!");
		return false;
	}
	
	if(form.elements["contactPerson"].value==""){
		//alert("Please input a contact person!");
		alert("請輸入聯絡人!");
		return false;
	}
	
	
	var i;
	var validChar = "ABCD";
	var count, choice;
	for(i=0; i<total; i++){	//for each choice/count
		choice = trim(form.elements["choice_"+i].value);
		count = trim(form.elements["count_"+i].value);
		
		if(isNaN(count)){	//not valid integer
			//alert("Count must be numerics!");
			alert("請輸入數字在數量欄位!");
			return false;
		}else if(count==""){	//empty count
			if(choice!=""){		//but choice is set
				//alert("Please set the count!");
				alert("請輸入數字!");
				return false;
			}
		}else{	//valid count
			if(choice==""){	//no choice set for the count
				//alert("Please set the choice!");
				alert("請輸入選擇!");
				return false;
			}

			if(numOfChoice == 1 && choice!=validChar.charAt(0)) {
				alert("請確認選擇為A!");
				return false;
			}
			if(numOfChoice == 2 && choice!=validChar.charAt(0) && choice!=validChar.charAt(1)) {
				alert("請確認選擇為A/B!");
				return false;
			}
			if(numOfChoice == 3 && choice!=validChar.charAt(0) && choice!=validChar.charAt(1) && choice!=validChar.charAt(2)) {
				alert("請確認選擇為A/B/C!");
				return false;
			}
			if(numOfChoice == 4 && choice!=validChar.charAt(0) && choice!=validChar.charAt(1) && choice!=validChar.charAt(2) && choice!=validChar.charAt(3)) {
				alert("請確認選擇為A/B/C/D!");
				return false;
			}
		}
	}
	
	return true;
}



//STUDENT ORDER FORM related
//check whether seat number is between 1 and 999
function checkSeatNumber(seatNumber){
	var temp = trim(seatNumber);
	
	if(isNaN(temp)){
		//alert("Seat number must be a number!");
		alert("請輸入數字在座號欄位!");
		return false;
	}
	
	//special handling for seat number
	//if the seat number is empty
	//it's regarded as valid since it can be entered later
	if(temp=='')	
		return true;
		
	if(temp < 1 || temp > 999){
		//alert("Seat number must lie between 1 and 999!");
		alert("座號應介乎 1 至 999 !");
		return false;
	}
	
	return true;
}

//check coupon to see if it is numbers only
function checkCoupon(coupon){
	var temp = trim(coupon);
	
	if(isNaN(temp)){
		//alert("Coupon must be a number!");
		alert("請輸入數字在代用券欄位!");
		return false;
	}
	
	if(temp < 0 || temp > 31){	//max coupon count each time cannot exceed the monthly order - max 30 orders
		//alert("Coupon must be positive and less than 100!");
		alert("代用券數目應介乎 1 至 100 !");
		return false;
	}
	
	return true;
}

//check if paid amount is numerics and greater than zero
function checkPaidAmount(paidAmount){
	var temp = trim(paidAmount);
	
	if(isNaN(temp)){
		//alert("Paid amount should be numerics and greater than zero!");
		alert("應付金額應為正數及大於零!");
		return false;
	}
	
	if(temp < 0){
		//alert("Paid amount should be numerics and greater than zero!");
		alert("應付金額應為正數及大於零!");
		return false;
	}
	
	return true;
}

//check meal choice
//only choice A/B/C/D/X are valid
function checkChoice(form, name, index, len, numOfChoice){
	var i, j;
	var temp;
	
	for(i=0; i<len; i++){
		temp = form.elements[name+"_"+index+"_"+i].value;
		if(	temp!="X" && !((numOfChoice>=1 && temp=="A") || (numOfChoice>=2 && temp=="B") || (numOfChoice>=3 && temp=="C") || (numOfChoice>=4 && temp=="D")) ){
			//alert("Meal choice is invalid!");
			alert("選擇不正確!");
			return false;
		}
		
	}
	
	return true;
}

//This function is called
//when it's sure that the main and dessert orders are valid
//whenever there is a dessert, make sure all orders have dessert as well
function checkBoth(form, main, dessert, len, numOfChoice){
	var i, j;
	var temp, temp2;
	var dessertSelected = false;
	
	for(i=0; i<len; i++){
		temp = form.elements[main+"_"+i].value;	
		temp2 = form.elements[dessert+"_"+i].value;	

		if( (numOfChoice>=1 && temp=="A") || 
			(numOfChoice>=2 && (temp=="A" || temp=="B")) || 
			(numOfChoice>=3 && (temp=="A" || temp=="B" || temp=="C")) || 
			(numOfChoice>=4 && (temp=="A" || temp=="B" || temp=="C" || temp=="D"))){	//main is valid
			if(	(numOfChoice>=1 && temp2=="A") || 
				(numOfChoice>=2 && (temp2=="A" || temp2=="B")) || 
				(numOfChoice>=3 && (temp2=="A" || temp2=="B" || temp2=="C")) || 
				(numOfChoice>=4 && (temp2=="A" || temp2=="B" || temp2=="C" || temp2=="D"))){
				dessertSelected = true;
				break;
			}
		}
	}
	
	for(i=0; i<len; i++){
		temp = form.elements[main+"_"+i].value;	
		temp2 = form.elements[dessert+"_"+i].value;	
		
		if(	(numOfChoice>=1 && temp=="A") || 
			(numOfChoice>=2 && (temp=="A" || temp=="B")) || 
			(numOfChoice>=3 && (temp=="A" || temp=="B" || temp=="C")) || 
			(numOfChoice>=4 && (temp=="A" || temp=="B" || temp=="C" || temp=="D"))) {	//main is valid
			if(temp2=="X"){
				if(dessertSelected)
					return false;
			}else if(temp2!="A" && temp2!="B" && temp2!="C" && temp2!="D"){
				return false;
			}
		}else if(temp=="X"){
			if(temp2!="X"){
				return false;
			}
		}else
			return false;
	}
	
	return true;
}




function echeck(str) {

		var at="@"
		var dot="."
		var lat=str.indexOf(at)
		var lstr=str.length
		var ldot=str.indexOf(dot)
		if (str.indexOf(at)==-1){
		   //alert("Invalid E-mail ID")
		   alert("電郵地址不正確!")
		   return false
		}

		if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
		   //alert("Invalid E-mail ID")
		   alert("電郵地址不正確!")
		   return false
		}

		if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		    //alert("Invalid E-mail ID")
		    alert("電郵地址不正確!")
		    return false
		}

		 if (str.indexOf(at,(lat+1))!=-1){
		    //alert("Invalid E-mail ID")
		    alert("電郵地址不正確!")
		    return false
		 }

		 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		    //alert("Invalid E-mail ID")
		    alert("電郵地址不正確!")
		    return false
		 }

		 if (str.indexOf(dot,(lat+2))==-1){
		    //alert("Invalid E-mail ID")
		    alert("電郵地址不正確!")
		    return false
		 }
		
		 if (str.indexOf(" ")!=-1){
		    //alert("Invalid E-mail ID")
		    alert("電郵地址不正確!")
		    return false
		 }

		//check for invalid characters
		 if (str.indexOf("'")!=-1 || str.indexOf("\"")!=-1 || str.indexOf("!")!=-1 || str.indexOf("#")!=-1 || str.indexOf("$")!=-1 || str.indexOf("%")!=-1 ||
		 	str.indexOf("^")!=-1 || str.indexOf("&")!=-1 || str.indexOf("*")!=-1 || str.indexOf("(")!=-1 || str.indexOf(")")!=-1 || str.indexOf("[")!=-1 || str.indexOf("]")!=-1 ||
		 	str.indexOf("{")!=-1 || str.indexOf("}")!=-1 || str.indexOf("|")!=-1 || str.indexOf("~")!=-1 || str.indexOf("`")!=-1 || str.indexOf("/")!=-1 || str.indexOf("\\")!=-1 || str.indexOf(">")!=-1 || str.indexOf("<")!=-1 ||
		 	str.indexOf(",")!=-1 || str.indexOf(";")!=-1 || str.indexOf(":")!=-1 || str.indexOf("?")!=-1){
		    //alert("Invalid E-mail ID")
		    alert("電郵地址不正確!")
		    return false
		 }
		 
		 
 		 return true					
	}

function validateEmail(emailID){
	if ((emailID.value==null)||(emailID.value=="")){
		//alert("Please Enter your Email ID")
		alert("請輸入電郵地址!")
		emailID.focus()
		return false
	}
	if (echeck(emailID.value)==false){
		emailID.value=""
		emailID.focus()
		return false
	}
	return true
 }

function checkEmail(emailAddr) {
	if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(emailAddr.value)){
		return (true)
	}
	
	//alert("Invalid E-mail Address! Please re-enter.")
	alert("電郵地址不正確! 請重新輸入!")
	return (false)
}


function noWildChar(inputString, fieldName){
	var validChar = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
	
	for(i=0; i<inputString.length; i++){
		if(validChar.indexOf(inputString.charAt(i))==-1){
			//alert("Only allow 0-9, a-z, A-Z for "+fieldName+" field!");
			alert(fieldName+ " 只接受 0-9, a-z, A-Z!");
			return false;
		}
	}
	
	return true;
}

function checkUserID(userID){
	var user_id = trim(userID);
	if(user_id .length < 6){
		//alert("Min 6 characters for user id!");
		alert("登入名最少六個字!");
		return false;
	}
	
	return noWildChar(user_id, "user id");
}

function checkPassword(password, confirmPassword){
	pwd = trim(password);
	if(pwd.length < 6){
		//alert("Min 6 characters for password!");
		alert("密碼最少六個字!");
		return false;
	}
	
	if(!noWildChar(pwd, "password"))
		return false;
		
	if(pwd==confirmPassword)
		return true;
		
	//alert("Please confirm your password!");
	alert("請確認密碼!");
	return false;
}


function onlyEnglishAndSymbol(inputString){
	var validString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789~!@#$%^&*()_+-*/=\[]{}:;'\",.?<>| ";

	for(i=0; i<inputString.length; i++){
		if(validString.indexOf(inputString.charAt(i))==-1){
			alert("英文的文字欄不可用中文字!");
			return false;
		}
	}
	
	return true;
}


function onlyNumeric(inputString){
	var validString = "0123456789";
	var temp = trim(inputString);
	
	/* 
	if(temp.length <= 0){
		alert("請輸入繳費聆號碼!");
		return false;
	}*/
		
	for(i=0; i<temp.length; i++){
		if(validString.indexOf(temp.charAt(i))==-1){
			alert("繳費聆號碼只可輸入0-9的數字!");
			return false;
		}
	}
	
	return true;
}

function checkPpsRef(paymentMethod, ppsRef){
	/*if(paymentMethod=="PP" or paymentMethod=="OK")
		
		if(trim(ppsRef).length > 0)
			return true;
		else{
			alert("請輸入繳費聆付款編號!");
			return false;
		}
	else
		return true;*/
	return true;
}

function trim(inputString) {
   // Removes leading and trailing spaces from the passed string. Also removes
   // consecutive spaces and replaces it with one space. If something besides
   // a string is passed in (null, custom object, etc.) then return the input.
   if (typeof inputString != "string") { return inputString; }
   var retValue = inputString;
   var ch = retValue.substring(0, 1);
   while (ch == " ") { // Check for spaces at the beginning of the string
      retValue = retValue.substring(1, retValue.length);
      ch = retValue.substring(0, 1);
   }
   ch = retValue.substring(retValue.length-1, retValue.length);
   while (ch == " ") { // Check for spaces at the end of the string
      retValue = retValue.substring(0, retValue.length-1);
      ch = retValue.substring(retValue.length-1, retValue.length);
   }
   while (retValue.indexOf("  ") != -1) { // Note that there are two spaces in the string - look for multiple spaces within the string
      retValue = retValue.substring(0, retValue.indexOf("  ")) + retValue.substring(retValue.indexOf("  ")+1, retValue.length); // Again, there are two spaces in each of the strings
   }
   return retValue; // Return the trimmed string back to the user
} // Ends the "trim" function