var validClassName = 'textField';
var invalidClassName = 'bgred14';
var validDecimalfield = 'inputDecimalField';
var invalidDecimalfield = 'inputInvalidDecimalField';

function isCurrency(elm) {
	var nNum = 0;			// Total numbers for currency value.
	var nDecimal = 0;		// Total times a decimal point occurs.
	var nCommas = 0;		// Total times a comma occurs.
	var txtLen;				// Length of string passed.
	var xTxt;				// Assigned object passed.
	var sDollarVal;			// Assigned dollar amount with or without commas.
	var bComma;				
	var decPos = 0;			// Assigned value of numbers or positions after decimal point.
	var nNumCount = 0;		// Total number between commas.
	var i;					// For forloop indexing.
	var x;					// Assigned each indivual character in string.

	// Set the xTxt variable to the object passed to this function.
	// Assign the length of the string to txtLen.
	xTxt = elm;
	txtLen = xTxt.value.length

	for(i = 0; i < txtLen; i++) {
		// Assign charater in substring to x.
		x = xTxt.value.substr(i, 1);

		if(x == ".") {
			nDecimal = nDecimal + 1; // Sum total times decimal point occurs.
		} else if(x == ",") {
			nCommas = nCommas + 1; // Sum total times comma occurs.
		} else if(parseInt(x) >= 0 || parseInt(x) <= 9) {
			nNum = nNum + 1; // If the character is a number sum total times a number occurs.
		} else {
			// Error occurs if any other character value is in the string
			// other then the valid characters.
//			alert("You have entered an illegal value.");
			return false;
		}
	}

	// check number of decimal point
	if(nDecimal > 1) {
//		alert("You have entered more then one decimal point.");
		return false;
	}

	// check position of decimal point
	if(nDecimal == 1) {
		// Get the number of numbers after the decimal point in
		// the string if there is a decimal point present
		decPos = (txtLen - 1) - xTxt.value.indexOf(".");

		// Floating point cannot be more then two.
		// Valid format after decimal point.
		/**********************************/
		/*   #.##, #.#, .#, .##  */
		/**********************************/
		if(decPos == 0 || decPos > 2) {
//			alert("The decimal point you entered is not in the correct position.");
			return false;
		}
	}

	if(nCommas == 0) {
		// If no commas are present value is a valid currency.
		return true;
	} else {
		// Get total number of dollar number(s), removing floating point numbers or cents.
		nNum = nNum - decPos;
		
		sDollarVal = xTxt.value.substr(0, (nNum + nCommas));
		
		// Determine if a zero is the first number or if a
		// comma is the first or last character in the string.
		if(sDollarVal.lastIndexOf("0", 0) == 0 ) {
//			alert("You cannot start the amount out with a zero.");
			return false;
		} else if(sDollarVal.lastIndexOf(",", 0) == 0) {
//			alert("You cannot start the amount out with a comma.");
			return false;
		} else {
			// Initialize bComma indicating a comma has not been occured yet.
			bComma = false;
			for(i = 0; i < sDollarVal.length; i++) {
				// Assign charater in substring to x.
				x = sDollarVal.substr(i, 1);
				if(parseInt(x) >= 0 || parseInt(x) <= 9) {
					// If x is a number add one to the number counter.
					nNumCount = nNumCount + 1;

					// Sense comma(s) are present number counter cannot be more then three before the first or next comma.
					if(nNumCount > 3) {
//						alert("You have a mis-placed comma.");
						return false;
					}
				} else {
					// If the number counter is less then three and
					// the comma indicator is true the comma is either
					// mis-placed or there are not enough values.

					if(nNumCount != 3 && bComma) {
//						alert("You have a mis-placed comma.");
						return false;
					}

					// Reset the number counter back to zero.
					nNumCount = 0;

					// Set the comma indicator to true indicating
					// that the first comma has been found and that
					// there now MUST be three numbers after each
					// comma until the loop hits the end.
					bComma = true;
				}
			}

			// Determine if after the loop ended that there
			// was a total of three final numbers after the
			// last comma.
			if(nNumCount != 3 && bComma) {
//				alert("You have a mis-placed comma.");
				return false;
			}
		}
	}

	// Return true indicating that the value is a valid
	// currency.
	return true;
}

function currencyToNumber(num) {
	var result = "";
	
	for(i = 0; i < num.length; i++) {
		var x = num.substr(i, 1);
		
		if(parseInt(x) >= 0 || parseInt(x) <= 9 || x == ".") {	
			result = result + x;
		}
	}
	
	return result;	
}

function formatCurrency(num) {
	num = num.toString().replace(/\$|\,/g,'');
	
	if(isNaN(num)) num = "0";
	
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num * 100+0.50000000001);
	cents = num % 100;
	num = Math.floor(num / 100).toString();
	
	if(cents < 10) cents = "0" + cents;
	
	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));
	
	return (((sign) ? '' : '-') + num + '.' + cents);
}

//  Validate  Form
function validateForm(form){
	/* 
		form : the specific form name
		valid class name : the specific class name when validation is true
		invalid class name: the specific class name when validation is false
	*/
	
	// initialize class name
	if (arguments[1] != null) {
		validClassName = arguments[1];
	}

	if (arguments[2] != null) {
		invalidClassName = arguments[2];
	}

	var status = true;
	var len = form.elements.length ; 
	for (var i = 0; i < len; i++) {
		var elm = form.elements[i];
		var name = form.elements[i].name;
		var type = form.elements[i].type;
		
		if (form.elements[i].type == "hidden") {	
		    // check blank	
	    	if (form.elements[i].name== "blank") {
				if (CheckBlank(form.elements[i-1])) {
					status = false;
					form.elements[i-1].className = invalidClassName;
				} else {
					form.elements[i-1].className = validClassName;
				}// End Check  blank
			// check phone
			}else if (form.elements[i].name== "phone") {
			    if (CheckBlank(form.elements[i-1])) {
					if (form.elements[i].faq == "1") {
						form.elements[i-1].className = validClassName;
					} else {
                       	status = false;
					    form.elements[i-1].className = invalidClassName;  
					}
				} else {
					if (CheckTel(form.elements[i-1].value)) {
					 	form.elements[i-1].className = validClassName;
					} else {
						status = false;
						form.elements[i-1].className = invalidClassName;
					}	
				}// End Check  phone
            // check digit				
			}else if (form.elements[i].name== "digit") {
				if (CheckBlank(form.elements[i-1])) {
					if (form.elements[i].faq == "1") {
						form.elements[i-1].className = validClassName;
					} else {
                        status = false;
						form.elements[i-1].className = invalidClassName;  
					}
				} else {
					if (CheckDigit(form.elements[i-1].value)) {
						form.elements[i-1].className = validClassName;
						if(form.elements[i-1].value.indexOf(",")) {
							form.elements[i-1].className = validClassName;
						}
					} else {
						status = false;
						form.elements[i-1].className = invalidClassName;
					}
				}// End Check digit
            // check digit	
            } else if (form.elements[i].name== "amount") {
				if (CheckBlank(form.elements[i-1])) {
					if (form.elements[i].faq == "1") {
						form.elements[i-1].className = validClassName;
					} else {
                        status = false;
						form.elements[i-1].className = invalidClassName;  
					}
				} else {
					if (CheckAmount(form.elements[i-1].value)) {
						form.elements[i-1].className = validClassName;
						if(form.elements[i-1].value.indexOf(",")) {
							form.elements[i-1].className = validClassName;
						}
					} else {
						status = false;
						form.elements[i-1].className = invalidClassName;
					}
				}// End Check Amount
				// check currency
            } else if (form.elements[i].name== "currency") {
				if (CheckBlank(form.elements[i-1])) {
					if (form.elements[i].faq == "1") {
						form.elements[i-1].className = validClassName;
					} else {
                        status = false;
						form.elements[i-1].className = invalidClassName;  
					}
				} else {
					if (CheckCurrency(form.elements[i-1].value)) {
						form.elements[i-1].className = validClassName;
						if(form.elements[i-1].value.indexOf(",")) {
							form.elements[i-1].className = validClassName;
						}
					} else {
						status = false;
						form.elements[i-1].className = invalidClassName;
					}
				}// End Check currency
			// check amount
			} else if (form.elements[i].name== "dateFormat") {
				if (CheckBlank(form.elements[i-1])) {
					status = false;
					form.elements[i-1].className = invalidClassName;
				} else {
					if (CheckDate(form.elements[i-1].value)) {
						form.elements[i-1].className = validClassName;
					} else {
						status = false;
						form.elements[i-1].className = invalidClassName;
					}
				}// End Check dateFormat
			// check email format or blank				
			} else if (form.elements[i].name=="email") {
				if (CheckBlank(form.elements[i-1])) {
					if (form.elements[i].faq == "1") {
						form.elements[i-1].className = validClassName;
					} else {
                        status = false;
						form.elements[i-1].className = invalidClassName;  
					}
				} else {
					if (form.elements[i-1].value.match(/([a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+)/gi) ) {
						form.elements[i-1].className = validClassName;
					} else {
						status = false;
						form.elements[i-1].className = invalidClassName;
					}
				}//End check Email
			//check password. Please put <input type="hidden" name="password"> between password and repassword!!!!!!				
			} else if (form.elements[i].name=="password") {
				if (CheckBlank(form.elements[i-1]) && CheckBlank(form.elements[i+1])){
					status = false;
					form.elements[i-1].className = invalidClassName;
					form.elements[i+1].className = invalidClassName;
				} else {
					if (form.elements[i-1].value != form.elements[i+1].value) {
						status = false;
						form.elements[i-1].className = validClassName;
						form.elements[i+1].className = invalidClassName;							
					} else {
						form.elements[i-1].className = validClassName;
						form.elements[i+1].className = validClassName;							
					}
				}
			}
      	} // if hidden       	
	} // for
	  
	if (status) {
		return true;
	}
} // end func

//  select checkbox before click button
function validateCheckbox(element,form) {
	var lenCheckbox = element.length; 
	if (lenCheckbox == null) {
		if(element.checked) {
			form.submit();
			return true; 
		}
	} else
		for (var j = 0; j < lenCheckbox; j++) {	   
			if (element[j].checked) {
				form.submit();
				return true; 	 
			}//if 
		}//for
		
		alert("กรุณาเลือกอย่างน้อย 1 รายการ");					
		return false;
}

// checke endDate > startDate ???
function checkDate(element1,element2) { 
	var start = element1.value;
	var end = element2.value;
	var d1 = start.substring(0,2);
	var d2 = end.substring(0,2);
	var m1 = start.substring(3,5);
	var m2 = end.substring(3,5);
	var y1 = start.substring(6,10);
	var y2 = end.substring(6,10);

	if ((m2 == m1) && (y2 == y1)) {
		if (d2 > d1) {
			return true;
		}
	} else if (y2 > y1) {
		return true;
	} else if ((m2 > m1) && (y2 == y1)) {
		return true;
	}
	
	alert("วันสิ้นสุดต้องมากกว่าวันเริ่มต้น");
	return false;
}
	
// check browser  Version before load web page
function browserversion() {   
	var name = navigator.appName; 
	var version = parseInt(navigator.appVersion);
	alert(navigator.appVersion);
	
	if (version < 4 || name != "Microsoft Internet Explorer") { 
    	alert("Home page นี้แสดงผลเฉพาะบราวเซอร์ IE version5.5 ขึ้นไป");
	  	history.go(-1); 
    } 
} //end

// validate decimal field with message
function validDecimal(field,message){
	var nDecimal=0;
	var txtLen = field.value.length;
	for(i = 0; i < txtLen; i++) {
		// Assign charater in substring to x.
		x = field.value.substr(i, 1);
		
		if(x == ".") {
			nDecimal = nDecimal + 1; 
		}
				
	}
	if(nDecimal >= 2){
		field.className=invalidDecimalfield;
		alert(message);		
		field.focus();
		return false;
	}
	if(CheckAmount(field.value)){
		field.className=validDecimalfield;	
		return true;
	}else{
		field.className=invalidDecimalfield;
		alert(message);		
		field.focus();
	}
	return false;
}//end

function validTextField(field){
	field.className='inputTextField';
	return;
}

function validComboBox(field){
	field.className='inputSelectField';
	return;
}

// validate currency field with message
function validCurrency(field,message){	
	if(isCurrency(field)){
		field.className=validDecimalfield;	
        var x = currencyToNumber(field.value);
        field.value = formatCurrency(x);
		return true;
	}else{		
		field.className=invalidDecimalfield;
		field.focus();
		alert(message);
	}
	return false;
}//end

// reset text field on click
function highlightText(field){
	field.select();
}

function resetTextField(form,val){
	var len = form.elements.length; 
	
	for (var i = 0; i < len; i++) {
		if (form.elements[i].type == "text") {
			form.elements[i].value = val;
		}				
	}	
	return true;	
}

// reset all field except hidden, button
function resetAll(form){
	var len = form.elements.length;
	
	for (var i = 0; i < len; i++) {
		// input type text
		if (form.elements[i].type == "text") {
			form.elements[i].value = "";
		} 
		// input type radio
		else if (form.elements[i].type == "radio") {
			var elm = document.getElementsByName(form.elements[i].name);
			elm[0].checked = true;
			i = i + elm.length - 1;
		}
		// input type password
		else if (form.elements[i].type == "password") {
			form.elements[i].value = "";
		}
		// input type textarea
		else if (form.elements[i].type == "textarea") {
			form.elements[i].value = "";
		}
		// input type select-one
		else if (form.elements[i].type == "select-one") {
			var elm = form.elements[i].options;
			elm[0].selected = true;
		}
		// input type hidden
		else if (form.elements[i].type == "hidden") {
		
		}
	}	
	
	return true;	
}

function validatePercent(elm,msg1,msg2){
	var x = 0;
	
	if (validDecimal(elm, msg1)) {
		x = elm.value;
		
		if (!isNaN(x)) {
			if (x >= 0 && x <= 100) {
				return true;
			} else {
				alert(msg2);
				elm.className=invalidDecimalfield;
				elm.focus();
			}
		}
	}
	
	return false;
}

// validate percent 100%
function validate100Percent(v ,msg){
	var p = 0;
	p = v.value;
	if( p != 100 ){
		alert(msg);
		return false;
	}else{
		return true;
	}	
}

