$(function() {
	setValidation();
});

//Set Validation
function setValidation(id){
	if(typeof(id)=='undefined'){id=""}
	//Set Date time Mask
    setDateObject(id);
	//Set Phone Mask
	setTelNumberObject(id);
	//Set Input validation
	$(id+".validate-integer:text").change(function(){
		if(!checkValidateNumeral($(this).val())){
			$(this).val("");
		}
    });
    $(id+".validate-numeric:text").change(function(){
        if(!checkValidateDouble($(this).val())){
			$(this).val("");
		}
    });
	$(id+".validate-email:text").change(function(){
		if(!checkValidateEmail($(this).val())){
			$(this).val("");
		}
    });
	$(id+".validate-englishOnly:text").change(function(){
		if(checkChineseInput($(this).val())){
			setErrorMsg(this.id,"此欄位只可輸入英文")
			$(this).val("");
		}else{
			setErrorMsg(this.id,"")
		}
    });
	$(id+".validate-password").change(function(){
		if(!checkValidatePassword($(this).val())){
			setErrorMsg(this.id,"密碼必須為8位的英文字母或數字.")
			$(this).val("");
		}else{
			setErrorMsg(this.id,"")
		}
    });

	$(id+".validate-password").change(function(){
		if(!checkValidatePassword($(this).val())){
			setErrorMsg(this.id,"密碼必須為8位的英文字母或數字.")
			$(this).val("");
		}else{
			setErrorMsg(this.id,"")
		}
    });

	/*
	$(id+".inputInteger:text").bind('keypress', function(e){
		var keyCode=getKeyCode(e);
        return keyCode==0 || checkValidateNumeral(String.fromCharCode(keyCode));
    });
    $(id+".inputNumeric:text").bind('keypress', function(e){
		var keyCode=getKeyCode(e);
        return keyCode==0 || keyCode==46 || keyCode==8 || checkValidateDouble(String.fromCharCode(keyCode));
    });
	$(id+".inputEmail:text").bind('keypress', function(e){
		var keyCode=getKeyCode(e);
        return keyCode==0 || checkValidateEmail(String.fromCharCode(keyCode));
    });
*/
}

/* Date Object*/
function setDateObject(id){
	$.datepicker.setDefaults({dateFormat:'yy-mm-dd'});
	if(typeof(id)=='undefined'){id=""}
    setDatePickerObject(id);
    setDateMask(id);
    setTimeMask(id);
}

/* DatePicker*/
function setDatePickerObject(id){
    if(typeof(id)=='undefined'){id=""}
	if(id!=""){id="#"+id+" ";}
    $(id+" input.validate-date").datepicker({showOn: 'button',buttonImage: 'images/calendar.png',buttonImageOnly: true});
}

//Date Mask
function setDateMask(id){
	if(typeof(id)=='undefined'){id=""}
	if(id!=""){id="#"+id+" ";}
    $(id+" input.validate-date").mask("9999-99-99",{placeholder:" "});
}

function setTimeMask(id){
	if(typeof(id)=='undefined'){id=""}
	if(id!=""){id="#"+id+" ";}
    $(id+" input.validate-time").mask("99:99",{placeholder:" "});
}

//Tel Mask
function setTelNumberObject(id){
	if(typeof(id)=='undefined'){id=""}
    setTelNumberMask(id);
}

function setTelNumberMask(id){
	if(typeof(id)=='undefined'){id=""}
	if(id!=""){id="#"+id+" ";}
    $(id+" input.validate-tel").mask("99999999",{placeholder:" "});
}

function addTelNumberMask(id){
   $("#"+id).mask("99999999",{placeholder:" "});
}

//Check Double
function checkValidateDouble( strValue ) {
    var objRegExp  =  /(^-?\d{1,7}\.\d$)|(^-?\d{1,7}$)/;
    return objRegExp.test(strValue);
}
//Check Integer
function checkValidateInteger(strValue) {
    var objRegExp  = /(^-?\d\d*$)/;
    return objRegExp.test(strValue);
}
//Check Numeric
function checkValidateNumeric(strValue){
    var objRegExp  = /[0-9]/;
    return objRegExp.test(strValue);
}
//Check Alphabet
function checkAlphabet(strValue){
    var objRegExp  = /([a-z]|[A-Z])/;
    return objRegExp.test(strValue);
}

function checkAlphabetUpper(strValue){
    var objRegExp  = /([A-Z])/;
    return objRegExp.test(strValue);
}

//Check Password
function checkValidatePassword(strValue){
    var objRegExp  = /^([a-z]|[A-Z]|[0-9]){8}$/;
    return objRegExp.test(strValue);
}

//Check Email
function checkValidateEmail(strValue){
    var objRegExp  = /^(\w+)@([\w.]+)(\.{1})([\w.]+)/;
    return objRegExp.test(strValue);
}
//Check Full HK ID
function checkHKID(strValue){
    var objRegExp  = /^([a-z]|[A-Z]){1}([0-9]{6}([0-9]|[a]|[A]){1})|([a-z]|[A-Z]){2}([0-9]{6}([0-9]|[a]|[A]){1})$/;
    return objRegExp.test(strValue);
}
//Check HK ID
function checkHKID_1(strValue){
    var objRegExp  = /^([a-z]|[A-Z]){1,2}$/;
    return objRegExp.test(strValue);
}

function checkHKID_2(strValue){
    var objRegExp  = /^\d{6}$/;
    return objRegExp.test(strValue);
}

function checkHKID_3(strValue){
    var objRegExp  = /^(\d|([a])|[A]){1}$/;
    return objRegExp.test(strValue);
}
//Check HK Phone Number
function checkValidateHKPhoneNumber(strValue){
    strValue=strValue.replace(" ","");
    var objRegExp  = /^\d{8}$/;
    return objRegExp.test(strValue);
}
//Check Chinese
function checkChineseInput(strValue){
    var objRegExp1 = new RegExp("^[\u4E00-\uFA29]*$"); //Chinese character range
    var objRegExp2 = new RegExp("^[\uE7C7-\uE7F3]*$"); //Chinese character range

    return objRegExp1.test(strValue) || objRegExp2.test(strValue);
}
//Check Time
function checkValidateTimeValue(strValue){
    var objRegExp  = /^([0-2])([0-9]):([0-5])([0-9])$/;
    return objRegExp.test(strValue);
}
//Check Date
function checkValidateDateValue(strValue,strDateFormat) {
    var objRegExp = /(\d{4})-(\d{2})-(\d{2})/
    if(!objRegExp.test(strValue))
        return false; //doesn't match pattern, bad date
    else{
        var strSeparator="-";

        var arrayDate = strValue.split(strSeparator);
        var arrayFormat=strDateFormat.split(strSeparator);

        var dtmDate;
        var dtmMonth;
        var dtmYear;
        for(var i=0;i<arrayFormat.length;i++){
            switch(arrayFormat[i].substr(0,1)){
                case "d":
                    dtmDate=arrayDate[i];
                    break;
                case "M":
                    dtmMonth=arrayDate[i];
                    break;
                case "y":
                    dtmYear=arrayDate[i];
                    break
            }
        }

        if(!checkValidateInteger(arrayDate[0]) || !checkValidateInteger(arrayDate[1]) || !checkValidateInteger(arrayDate[2])){
            return false;
        }else{
            //alert(arrayDate[0]+","+arrayDate[1]+","+arrayDate[2]);
            //create a lookup for months not equal to Feb.
            var arrayLookup = {
                '01' : 31,
                '03' : 31,
                '04' : 30,
                '05' : 31,
                '06' : 30,
                '07' : 31,
                '08' : 31,
                '09' : 30,
                '10' : 31,
                '11' : 30,
                '12' : 31
            }
            var intDay = parseInt(dtmDate,10);

            //check if month value and day value agree
            if(arrayLookup[dtmMonth] != null) {
                if(intDay <= arrayLookup[dtmMonth] && intDay != 0)
                    return true; //found in lookup table, good date
            }

            //check for February (bugfix 20050322)
            //bugfix  for parseInt kevin
            //bugfix  biss year  O.Jp Voutat
            var intMonth = parseInt(dtmMonth,10);
            if (intMonth == 2) {
                var intYear = parseInt(dtmYear,10);
                if (intDay > 0 && intDay < 29) {
                    return true;
                }
                else if (intDay == 29) {
                    if ((intYear % 4 == 0) && (intYear % 100 != 0) ||
                        (intYear % 400 == 0)) {
                        // year div by 4 and ((not div by 100) or div by 400) ->ok
                        return true;
                    }
                }
            }
        }
        return false; //any other values, bad date
    }
}

//Error Message
function setErrorMsg(id,msg){
	//$("#"+id+"_errorMsg").html("<br>"+msg);
	$("#"+id+"_errorMsg").html(msg);
	$("#"+id+"_errorMsgBox").css("display",msg==""?"none":"");
}

function setHighlightMsg(id,msg){
	$("#"+id+"_highlightMsg").html(msg);
	$("#"+id+"_highlightMsgBox").css("display",msg==""?"none":"");
}

//Auto Check Valiation
var _validateObjFocusId="";
function resetValiateFocus(){
	_validateObjFocusId="";
}

function _setValiateFocus(id){
	if(_validateObjFocusId==""){
		$("#"+id).focus();
		_validateObjFocusId=id;
	}
}

function checkEmptyTextBox(id,errorMsg){
	if($("#"+id).val()!=""){
		setErrorMsg(id,"");
		return true;
	}else{
		setErrorMsg(id,errorMsg);
		_setValiateFocus(id);
		return false;
	}
}

function checkIntegerTextBox(id,errorMsg){
	if(checkValidateInteger($("#"+id).val())){
		setErrorMsg(id,"");
		return true;
	}else{
		setErrorMsg(id,errorMsg);
		_setValiateFocus(id);
		return false;
	}
}

function checkNumericTextBox(id,errorMsg){
	if(checkValidateDouble($("#"+id).val())){
		setErrorMsg(id,"");
		return true;
	}else{
		setErrorMsg(id,errorMsg);
		_setValiateFocus(id);
		return false;
	}
}

function checkHKIDTextBox(id1,id2,id3,errorMsg){
	var pass=true;
	if(checkHKID_1($("#"+id1).val())){
		setErrorMsg(id1,"");
	}else{
		_setValiateFocus(id1);
		pass=false;
	}
	if(checkHKID_2($("#"+id2).val())){
		setErrorMsg(id1,"");
	}else{
		_setValiateFocus(id2);
		pass=false;
	}
	if(checkHKID_3($("#"+id3).val())){
		setErrorMsg(id1,"");
	}else{
		_setValiateFocus(id3);
		pass=false;
	}
	return pass;
}

