/* This script and many more are available free online at
The JavaScript Source :: http://javascript.internet.com
Created by: Travis Beckham :: http://www.squidfingers.com | http://www.podlob.com */

// |||||||||||||||||||||||||||||||||||||||||||||||||||||
//
// Coded by Travis Beckham
// http://www.squidfingers.com | http://www.podlob.com
// If want to use this code, feel free to do so, but
// please leave this message intact.
//
// |||||||||||||||||||||||||||||||||||||||||||||||||||||
// --- version date: 11/21/02 --------------------------

// returns true if the string is empty
function isEmpty(str){
  return (str == null) || (str.length == 0);
}
// returns true if the string is a valid email
function isEmail(str){
  if(isEmpty(str)) return false;
  var re = /^[^\s()<>@,;:\/]+@\w[\w\.-]+\.[a-z]{2,}$/i
  return re.test(str);
}
// returns true if the string only contains characters A-Z or a-z
function isAlpha(str){
  var re = /[^a-zA-Z]/g
  if (re.test(str)) return false;
  return true;
}
// returns true if the string only contains characters 0-9
function isNumeric(str){
  var re = /[\D]/g
  if (re.test(str)) return false;
  return true;
}
// returns true if the string only contains characters A-Z, a-z or 0-9
function isAlphaNumeric(str){
  var re = /[^a-zA-Z0-9]/g
  if (re.test(str)) return false;
  return true;
}
// returns true if the string's length equals "len"
function isLength(str, len){
  return str.length == len;
}
// returns true if the string's length is between "min" and "max"
function isLengthBetween(str, min, max){
  return (str.length >= min)&&(str.length <= max);
}
// returns true if the string is a TW phone number formatted as...
// +886 (02) 2000-1234 , +886(02)2000-1234,886(02)2000-1234,886 (002) 2000-1234,(002) 2000-1234
function isPhoneNumber(str){
  var re = /^[\+]?[0-9]{0,3}?[ ]?[(]?[0-9]{2,3}?[)]?[-]?[ ]?[0-9]{3,4}[-]?[0-9]{3,4}$/g; 
  return re.test(str);
}

// returns true if the string is a valid date formatted as...
// yyyy-dd-mm
function isDate(str){
  var re = /^((((1[6-9]|[2-9]\d)\d{2})-(0?[13578]|1[02])-(0?[1-9]|[12]\d|3[01]))|(((1[6-9]|[2-9]\d)\d{2})-(0?[13456789]|1[012])-(0?[1-9]|[12]\d|30))|(((1[6-9]|[2-9]\d)\d{2})-0?2-(0?[1-9]|1\d|2[0-8]))|(((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))-0?2-29-))$/
  if (!re.test(str)) return false;
  return true;
}
// returns true if "str1" is the same as the "str2"
function isMatch(str1, str2){
  return str1 == str2;
}
// returns true if the string contains only whitespace
// cannot check a password type input for whitespace
function isWhitespace(str){ // NOT USED IN FORM VALIDATION
  var re = /[\S]/g
  if (re.test(str)) return false;
  return true;
}
// removes any whitespace from the string and returns the result
// the value of "replacement" will be used to replace the whitespace (optional)
function stripWhitespace(str, replacement){// NOT USED IN FORM VALIDATION
  if (replacement == null) replacement = '';
  var result = str;
  var re = /\s/g
  if(str.search(re) != -1){
    result = str.replace(re, replacement);
  }
  return result;
}

// returns true if the string is negative number
function isNegativeNumeric(str){

  var re = /^[0-9]*[1-9][0-9]*$/
  if (re.test(str)) return true;
  return false;
}

function isNegativePositiveNumeric(str){
  var re = /^[-]*[0-9]*[0-9][0-9]*$/
  if (re.test(str)) return true;
  return false;
}
//有問題 var re = /[-+]?[0-9]*\.?[0-9]+/    /([+-]?\d+(\.\d+)?)/  /[0-9]*\.?[0-9]?[0-9]?/ 
// (^-?\d{1,10}\.$)|(^-?\d{1,10}$)|(^-?\d{0,10}\.\d{1,9}$)

function isFloatNumeric(str){
  var re = /(^-?\d{0,6}(\.\d{1,2})?$)/
  if (re.test(str)) return true;
  return false;
}

//returns true if the string is ip address
function isIPAddress(str){
	var re = /\b(?:\d{1,3}\.){3}\d{1,3}\b/
	if (!re.test(str)) return false;
  return true;
}

//return true if the string is ID(合法的身分證字號)
function isIDNumber1(input_ID){
  var input_ID,chk_no,chk_str,chk_count;	
	input_ID.toUpperCase();
	
	if (input_ID.length!=10)
	{	
		//alert('身分證字號應為10碼');
		return false;			}
			
	if ((input_ID.charAt(0)<'A') || (input_ID.charAt(0)>'Z'))
	{	
		//alert('身分證字號第一碼應為英文字母');
		return false;			}
			
	if (isNaN(input_ID.substring(1,10)) || (input_ID.substring(1,10).indexOf('-')>=0) || (input_ID.substring(1,10).indexOf('.')>=0) || (input_ID.substring(1,10).indexOf('+')>=0))
	{		
		//alert('身分證字號後九碼應為1~9的數字');
		return false;			}
			
	if ((input_ID.charAt(1)<'1') || (input_ID.charAt(1)>'2'))
	{	
		//alert('身分證第二碼性別碼只能為1或2');
		return false;		
	}
	//進行驗證檢查碼的動作
	//轉換第一碼
	chk_no = changeOneChar(input_ID.charAt(0));
							
	chk_str=chk_no + input_ID.substring(1,10);		
	chk_count=0;
	for (var i=1;i<=9;i++) 
	{
		chk_count+=parseInt(chk_str.charAt(i))*(10-i);
	}	
	chk_count+=parseInt(chk_str.charAt(0));
	chk_count+=parseInt(chk_str.charAt(10));
	
	if ((chk_count % 10)!=0)
	{
		//alert('身分證字號驗證錯誤,請重新輸入!');
		return false;
	}	
	return true;	
}

//轉換身分證第一碼
function changeOneChar(Str)
{
	switch(Str)
	{
		case 'A':
		{
			chk_no='10';
			break;	}
		case 'B':
		{
			chk_no='11';			
			break;	}
		case 'C':
		{
			chk_no='12';			
			break;	}
		case 'D':
		{
			chk_no='13';			
			break;	}
		case 'E':
		{
			chk_no='14';			
			break;	}
		case 'F':
		{
			chk_no='15';			
			break;	}
		case 'G':
		{
			chk_no='16';			
			break;	}
		case 'H':
		{
			chk_no='17';			
			break;	}			
		case 'J':
		{
			chk_no='18';			
			break;	}
		case 'K':
		{
			chk_no='19';			
			break;	}
		case 'L':
		{
			chk_no='20';			
			break;	}
		case 'M':
		{
			chk_no='21';			
			break;	}
		case 'N':
		{
			chk_no='22';
			X2=2;
			break;	}
		case 'P':
		{
			chk_no='23';			
			break;	}
		case 'Q':
		{
			chk_no='24';			
			break;	}
		case 'R':
		{
			chk_no='25';			
			break;	}
		case 'S':
		{
			chk_no='26';			
			break;	}
		case 'T':
		{
			chk_no='27';			
			break;	}
		case 'U':
		{
			chk_no='28';			
			break;	}
		case 'V':
		{
			chk_no='29';			
			break;	}
		case 'X':
		{
			chk_no='30';			
			break;	}
		case 'Y':
		{
			chk_no='31';			
			break;	}
		case 'W':
		{
			chk_no='32';			
			break;	}
		case 'Z':
		{
			chk_no='33';			
			break;	}
		case 'I':
		{
			chk_no='34';			
			break;	}
		case 'O':
		{
			chk_no='35';			
			break;	}
	}
	return chk_no;
}

//return true if the string is ID(合法的統編)
function isIDNumber2(str){
var I = 0;
	var v1 = 0;
	var v2 = 0;
	
	var d2 = 0;
	var d4 = 0;
	var d6 = 0;
	var d7 = 0;
	
	var d2H = 0;
	var d2L = 0;
	var d4H = 0;
	var d4L = 0;
	var d6H = 0;
	var d6L = 0;
	var d7H = 0;
	var d7L = 0;
	var dLast = 0;
	var d2str = '';
	var problem = false;
	var errMessage = "統一編號之長度須為8個字元";
	var errMessage1 = "請檢查輸入統一編號內容";
	var strCom = str;
	var a = "12";
  
	if (strCom.length != 8 ) {
		alert(errMessage);
		return false;
	}
		
	for ( i = 1; i <= 8; i++) {
		if ("0123456789".indexOf(strCom.charAt(i-1)) != -1) {
			continue;
		} else {   
			alert(errMessage1);
			return false;
		}
	}  
  
	v1 = parseInt(strCom.charAt(0)) + parseInt(strCom.charAt(2)) + parseInt(strCom.charAt(4)) + parseInt(strCom.charAt(7))
	d2 = 2 * parseInt(strCom.charAt(1));
	d2h = (d2 >= 10) ? 1 : 0;
	d2l = (d2 >= 10) ? (d2 - 10)  : d2;
	d4 = 2 * parseInt(strCom.charAt(3));
	d4h = (d4 >= 10) ? 1 : 0;
	d4l = (d4 >= 10) ? (d4 - 10)  : d4;
	d6 = 2 * parseInt(strCom.charAt(5));
	d6h = (d6 >= 10) ? 1 : 0;
	d6l = (d6 >= 10) ? (d6 - 10)  : d6;
	d7 = 4 * parseInt(strCom.charAt(6));
	d7h = (d7 >= 10) ? Math.floor((d7 / 10)) : 0;
	
	d7l = (d7 >= 10) ? (d7 - (10 * d7h))  : d7;
	
	v2 = v1 + d2h + d2l + d4h + d4l + d6h + d6l + d7h + d7l;
  
	if ((v2 % 10) == 0) {
		problem = false
	} else {
		if (parseInt(strCom.charAt(6)) == 7) {
			dLast = ((d7h + d7l) >= 10) ? 1: 0;    
			v2 = v2 - d7h - d7l + dLast;
			if ((v2 % 10) == 0) {
				problem = false;
			} else {
				problem = true
			}
		} else {
			problem = true;
		}
	}
  
	if (problem) {    
		//alert(errMessage1);
		return false;        
	}
	return true;
}


// validate the form
function validateForm(f, preCheck){
  var errors = '';
  if(preCheck != null) errors += preCheck;
  var i,e,t,n,v,s;
  for(i=0; i < f.elements.length; i++){
    e = f.elements[i];
    if(e.optional) continue;
    t = e.type;
    n = e.name;
    v = e.value;
    s = e.ShowName;
    if(t == 'text' || t == 'password' || t == 'textarea'){
    	if(!e.isEmpty){
      	if(isEmpty(v)){
        	errors += '欄位 "' + s + '" 不得為空白\n'; continue;
      	}
      }
      if(!e.isDefaultValue && e.value != ''){
     	 if(v == e.defaultValue){
      	  errors += '欄位 "' + s + '" 不得為預設值.\n'; continue;
      	}
    	}
      if(e.isAlpha && e.value != ''){
        if(!isAlpha(v)){
          errors += '欄位 "' + s + '" 只能輸入英文字大小寫(A-Z a-z).\n'; continue;
        }
      }
      if(e.isNumeric && e.value != ''){
        if(!isNumeric(v)){
          errors += '欄位 "' + s + '" 只能輸入數字(0-9).\n'; continue;
        }
      }
      if(e.isAlphaNumeric && e.value != ''){
        if(!isAlphaNumeric(v)){
          errors += '欄位 "' + s + '" 只能輸入英數字(A-Z a-z 0-9).\n'; continue;
        }
      }
      if(e.isEmail && e.value != ''){
        if(!isEmail(v)){
          errors += v+' 不是一個正確的電子郵件格式.\n'; continue;
        }
      }
      if(e.isLength != null && e.value != ''){
        var len = e.isLength;
        if(!isLength(v,len)){
          errors += '欄位 "'+ s + '" 資料長度須為 '+len+' 字元.\n'; continue;
        }
      }
      if(e.isLengthBetween != null && e.value != ''){
        var min = e.isLengthBetween[0];
        var max = e.isLengthBetween[1];
        if(!isLengthBetween(v,min,max)){
          errors += '欄位 "'+ s + '" 長度需界於 '+min+' 到 '+max+' 之間.\n'; continue;
        }
      }
      if(e.isPhoneNumber && e.value != ''){
        if(!isPhoneNumber(v)){
          errors += v+' 不是一個正確的電話格式.\n'; continue;
        }
      }
      if(e.isDate && e.value != ''){
        if(!isDate(v)){
          errors += v+' 不是一個正確的日期格式(YYYY-MM-DD).\n'; continue;
        }
      }
      if(e.isMatch != null && e.value != ''){
        if(!isMatch(v, e.isMatch)){
          errors += '欄位 "'+ s + '" 資料不一制.\n'; continue;
        }
      }
      if(e.isNegativeNumeric && e.value != ''){
        if(!isNegativeNumeric(v)){
          errors += '欄位 "' + s + '" 只能輸入負數.\n'; continue;
        }
      }
      if(e.isNegativePositiveNumeric && e.value != ''){
        if(!isNegativePositiveNumeric(v)){
          errors += '欄位 "' + s + '" 只能輸入正負數.\n'; continue;
        }
      }
      if(e.isFloatNumeric && e.value != ''){
        if(!isFloatNumeric(v)){
          errors += '欄位 "' + s + '" 只能輸入浮點數(123456.99).\n'; continue;
        }
      }
      if(e.isIPAddress && e.value != ''){
        if(!isIPAddress(v)){
          errors += '欄位 "' + s + '" 不是一個正確的IP Address格式.\n'; continue;
        }
      }
      if(e.isIDNumber1 && e.value != ''){
        if(!isIDNumber1(v)){
          errors += '欄位 "' + s + '" 不是一個正確的身分證格式.\n'; continue;
        }
      }
      if(e.isIDNumber2 && e.value != ''){
        if(!isIDNumber2(v)){
          errors += '欄位 "' + s + '" 不是一個正確的統編格式.\n'; continue;
        }
      }
      
    }
    if(t.indexOf('select') != -1){
      if(isEmpty(e.options[e.selectedIndex].value)){
        errors += '請選擇 "'+ s + '"\n'; continue;
      }
    }
    if(t == 'file'){
      if(isEmpty(v)){
        errors += '欄位 "'+ s + '" 必需輸入一個檔名.\n'; continue;
      }
    }
  }
  if(errors != '') alert(errors);
  return errors == '';
}

