﻿// JScript File
/*Methods to validate data in client
 Author : Le Duy Tung Phuong
 Data modify: 11 Dec 2007
 */

function validator(){
};
validator.prototype.setting = function(controltovalidate, currentValue, allowBlank, maxlength, isEmail, isInteger, isDecimal, isDate, isPassword){
    var setting = new Object();
    setting.controltovalidate = controltovalidate;
    setting.allowBlank = allowBlank;
    setting.Maxlength = maxlength;
    setting.CheckInteger = isInteger;
    setting.CheckDecimal = isDecimal;
    setting.CheckEmail = isEmail;
    setting.CheckDate = isDate;
    setting.Password = isPassword;
    
    setting.allowBlankErrMsg = g_LangText["ERROR_FIELD_EMPTY"];
    setting.MaxlengthErrMsg = g_LangText["ERROR_MAX_LENGTH"];
    setting.CheckIntegerErrMsg = g_LangText["ERROR_INTEGER"];
    setting.CheckDecimalErrMsg = g_LangText["ERROR_DECIMAL"];
    setting.CheckEmailErrMsg = g_LangText["ERROR_EMAIL"];
    setting.CheckDateErrMsg = g_LangText["ERROR_DATE"];
    setting.CheckPassErrMsg = g_LangText["ERROR_PASS"];    
    $get(controltovalidate).settingValidate = setting;
}

validator.prototype.CtrNeedFocus = "";
validator.prototype.enableFocus = true;
validator.prototype.ControlErr = "";
validator.prototype.ClientValidateData = function(ctr){
    var oSrc = typeof(ctr.settingValidate) == "undefined" ? ctr.srcElement.settingValidate : ctr.settingValidate;
    var valid = true;
    var errorMsg = "";
    var intRegEx = "";
    var stringDauNganCach = ";"
    var emailRegEx = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
//    if ($get(oSrc.controltovalidate).style.display == "none") {
//        return;
//    }
    if (!oSrc.allowBlank && $get(oSrc.controltovalidate).value.trim().length == 0) {
        valid = false;
        errorMsg += oSrc.allowBlankErrMsg;
    }
    if (oSrc.Maxlength != -1 && $get(oSrc.controltovalidate).value.trim().length > oSrc.Maxlength) {
        valid = false;
        errorMsg += errorMsg.length > 0 ? "\r\n" : "";
        errorMsg += oSrc.MaxlengthErrMsg;
        errorMsg = String.prototype.format1(errorMsg, oSrc.Maxlength);
    }
    if (oSrc.CheckInteger && $get(oSrc.controltovalidate).value.trim().length > 0 && !(/^[0-9]+$/.test($get(oSrc.controltovalidate).value))) {
        valid = false;
        errorMsg += errorMsg.length > 0 ? "\r\n" : "";
        errorMsg += oSrc.CheckIntegerErrMsg;
    }
    if (oSrc.CheckDecimal && $get(oSrc.controltovalidate).value.trim().length > 0 && !(/^-?\d+(\.\d+)?$/.test($get(oSrc.controltovalidate).value))) {
        valid = false;
        errorMsg += errorMsg.length > 0 ? "\r\n" : "";
        errorMsg += oSrc.CheckDecimalErrMsg;
    }
    if (oSrc.CheckEmail && $get(oSrc.controltovalidate).value.trim().length > 0) {
        var strmail = $get(oSrc.controltovalidate).value.trim().split(stringDauNganCach)
        if (strmail.length > 0) {
            for (i = 0; i < strmail.length; i++) {
                mail = strmail[i].trim()
                if (!mail.match(emailRegEx)) {
                    valid = false;
                    errorMsg += errorMsg.length > 0 ? "\r\n" : "";
                    errorMsg += oSrc.CheckEmailErrMsg;
                }
            }
        }
    }
    if (oSrc.CheckDate && $get(oSrc.controltovalidate).value.trim().length > 0 && validator.prototype.ValidateDate($get(oSrc.controltovalidate)) == null) {
        valid = false;
        errorMsg += errorMsg.length > 0 ? "\r\n" : "";
        errorMsg += oSrc.CheckDateErrMsg;
    }
    if (oSrc.Password && $get(oSrc.controltovalidate).value.trim().length > 0) {
        var mediumRegex = new RegExp("^(?=.{6,})(((?=.*[A-Z])(?=.*[a-z]))|((?=.*[A-Z])(?=.*[0-9]))|((?=.*[a-z])(?=.*[0-9]))).*$", "g");
        if (mediumRegex.test($get(oSrc.controltovalidate).value) == false) {
            valid = false;
            errorMsg += errorMsg.length > 0 ? "\r\n" : "";
            errorMsg += oSrc.CheckPassErrMsg;
        }
    }
    
    if (!valid) {
    
        if ($get(validator.prototype.CtrNeedFocus) == null) {
            validator.prototype.CtrNeedFocus = oSrc.controltovalidate;
            if (validator.prototype.ControlErr == "") 
                validator.prototype.ControlErr = validator.prototype.CtrNeedFocus;
            if (validator.prototype.enableFocus) {
                $get(validator.prototype.CtrNeedFocus).focus();
                validator.prototype.enableFocus = false
            }
        }
        else {
            validator.prototype.ResetFormatControl(oSrc.controltovalidate);
            validator.prototype.CtrNeedFocus = "";
            validator.prototype.ControlErr = "";
        }
        validator.prototype.FormatControlWhenError(oSrc.controltovalidate, errorMsg);
    }
    else {
        validator.prototype.ResetFormatControl(oSrc.controltovalidate);
        validator.prototype.CtrNeedFocus = "";
        validator.prototype.ControlErr = "";
    }
    return valid;
}

validator.prototype.FormatControlWhenError = function(controlName, errorMsg){
    var control;
    control = $get(controlName);
    if (control.tagName == "SELECT") 
        control.style.backgroundColor = '#ffe4e1'
    else {
        control.style.backgroundImage = "url('ClientUtil/Image/invalid_line.gif')";
        control.style.backgroundRepeat = "repeat-x";
        control.style.backgroundPosition = "bottom";
    }
    //control.style.borderColor = "#dd7870"
    if (document.all) {
        control.onmouseover = function(){
            Tip(errorMsg, FADEIN, 200, FADEOUT, 400, ABOVE, true, JUMPHORZ, true);
        }
        control.onmouseout = function(){
            UnTip();
        }
    }
    else {
        control.title = errorMsg
    }
}
validator.prototype.FormatTEXTAREAWhenError = function(EdtcontrolName,DivcontrolName, errorMsg){
    var controltext =FCKeditorAPI.GetInstance(EdtcontrolName).EditorWindow.document.body //document.getElementById(controlName);
   var control  = document.getElementById(DivcontrolName);
   var strtext=""
       if(controltext.textContent!='undefined')
         strtext= controltext.textContent ;
       else
         strtext=controltext.innerText ;
      

    if (strtext == "") {
        control.style.backgroundImage = "url('ClientUtil/Image/invalid_line.gif')";
        control.style.backgroundPosition = "bottom";
        control.style.borderColor = "#dd7870"
        control.style.backgroundRepeat = "repeat-x";
        
        control.onmouseover = function(){
            Tip(errorMsg, FADEIN, 200, FADEOUT, 400, ABOVE, true, JUMPHORZ, true);
        }
        control.onmouseout = function(){
       
            UnTip();
        }
        
        return false;
    }
    else {
        control.style.backgroundImage = "";
        control.style.backgroundPosition = "bottom";
        control.style.borderColor = "#cccccc"
        return true;
    }
}

validator.prototype.ResetFormatControl = function(controlName){
    control = document.getElementById(controlName);
    if (control.tagName == "SELECT") 
        control.style.backgroundColor = ''
    else 
        control.style.backgroundImage = "url()";
    //control.style.borderColor = "#cccccc";
    if (document.all) {
        UnTip();
        control.onmouseover = function(){
        }
        control.onmouseout = function(){
            UnTip()
        }
    }
    else {
        control.title = ''
    }
}

validator.prototype.LoadErrorFromServer = function(errList){
    if (errList == null) 
        return;
    var errorMsg = "";
    for (var i = 0; i < errList.length; i++) {
        var control = $get(errList[i].ControlToValidate);
        if (control.tagName == "SELECT") 
            control.style.backgroundColor = '#dd7870'
        else {
            control.style.backgroundImage = "url('ClientUtil/Image/invalid_line.gif')";
            control.style.backgroundPosition = "bottom";
        }
       // control.style.borderColor = "#dd7870";
        errorMsg += errorMsg.length > 0 ? "\r\n" : "";
        errorMsg += errList[i].ErrorMsg;
        control.onmouseover = function(){
            eval(Tip(errorMsg, FADEIN, 200, FADEOUT, 400, ABOVE, true, JUMPHORZ, true));
        }
        control.onmouseout = function(){
            eval(UnTip());
        }
    }
}
//Method validate date(format: mm/dd/yyyy)
validator.prototype.ValidateDate = function(oSrc){
    var formatChar = " ";
    var aFormat = g_DateFormatPattern.split(formatChar);
    if (aFormat.length < 3) {
        formatChar = "/"
        aFormat = g_DateFormatPattern.split(formatChar)
        if (aFormat.length < 3) {
            formatChar = "."
            aFormat = g_DateFormatPattern.split(formatChar)
            if (aFormat.length < 3) {
                formatChar = "-"
                aFormat = g_DateFormatPattern.split(formatChar)
                if (aFormat.length < 3) {
                    // invalid date	format
                    formatChar = ""
                }
            }
        }
    }
    if (formatChar == "") 
        return null;
    else {
        var aData = oSrc.value.split(formatChar)
        var dateSelected;
        var monthSelected;
        var yearSelected;
        var monthName = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December")
        var monthName2 = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")
        var tokensChanged = 0;
        for (i = 0; i < 3; i++) {
            if ((aFormat[i] == "d") || (aFormat[i] == "dd")) {
                dateSelected = parseInt(aData[i], 10);
                tokensChanged++;
            }
            else 
                if ((aFormat[i] == "m") || (aFormat[i] == "mm") || (aFormat[i] == "M") || (aFormat[i] == "MM")) {
                    monthSelected = parseInt(aData[i], 10) - 1
                    tokensChanged++
                }
                else 
                    if (aFormat[i] == "yyyy") {
                        yearSelected = parseInt(aData[i], 10);
                        tokensChanged++
                    }
                    else 
                        if (aFormat[i] == "yy") {
                            yearSelected = 2000 + parseInt(aData[i], 10);
                            tokensChanged++
                        }
                        else 
                            if (aFormat[i] == "mmm") {
                                for (j = 0; j < 12; j++) {
                                    if (aData[i] == monthName[j]) {
                                        monthSelected = j;
                                        tokensChanged++
                                    }
                                }
                            }
                            else 
                                if (aFormat[i] == "MMM") {
                                    for (j = 0; j < 12; j++) {
                                        if (aData[i] == monthName2[j]) {
                                            monthSelected = j;
                                            tokensChanged++
                                        }
                                    }
                                }
        }
        if ((tokensChanged != 3) || isNaN(dateSelected) || isNaN(monthSelected) || isNaN(yearSelected)) 
            return null;
        else {
            var RegExPattern = /^(?=\d)(?:(?!(?:(?:0?[5-9]|1[0-4])(?:\.|-|\/)10(?:\.|-|\/)(?:1582))|(?:(?:0?[3-9]|1[0-3])(?:\.|-|\/)0?9(?:\.|-|\/)(?:1752)))(31(?!(?:\.|-|\/)(?:0?[2469]|11))|30(?!(?:\.|-|\/)0?2)|(?:29(?:(?!(?:\.|-|\/)0?2(?:\.|-|\/))|(?=\D0?2\D(?:(?!000[04]|(?:(?:1[^0-6]|[2468][^048]|[3579][^26])00))(?:(?:(?:\d\d)(?:[02468][048]|[13579][26])(?!\x20BC))|(?:00(?:42|3[0369]|2[147]|1[258]|09)\x20BC))))))|2[0-8]|1\d|0?[1-9])([-.\/])(1[012]|(?:0?[1-9]))\2((?=(?:00(?:4[0-5]|[0-3]?\d)\x20BC)|(?:\d{4}(?:$|(?=\x20\d)\x20)))\d{4}(?:\x20BC)?)(?:$|(?=\x20\d)\x20))?((?:(?:0?[1-9]|1[012])(?::[0-5]\d){0,2}(?:\x20[aApP][mM]))|(?:[01]\d|2[0-3])(?::[0-5]\d){1,2})?$/;
            if ((oSrc.value.match(RegExPattern)) && (oSrc.value != '')) {
                return new Date(Date.UTC(yearSelected, monthSelected, dateSelected));
            }
            else {
                return null;
            }
        }
    }
}



/* End methods to format control when error*/
/*methods work with string
 Author : Le Duy Tung Phuong
 */
String.prototype.trim = function(){
    return this.replace(/^\s+|\s+$/g, "");
}
String.prototype.ltrim = function(){
    return this.replace(/^\s+/, "");
}
String.prototype.rtrim = function(){
    return this.replace(/\s+$/, "");
}

//Need change 
String.prototype.format1 = function(){
    if (arguments.length == 0) 
        return null;
    var str = arguments[0];
    for (var i = 1; i < arguments.length; i++) {
        var re = new RegExp('\\{' + (i - 1) + '\\}', 'gm');
        str = str.replace(re, arguments[i]);
    }
    return str;
}

/*Caledar*/
function DatetimePicker(){
};

DatetimePicker.prototype.selected = function(cal, date){
    cal.sel.value = date; // just update the date in the input field.
    if (cal.dateClicked) 
        cal.callCloseHandler();
}

DatetimePicker.prototype.closeHandler = function(cal){
    cal.hide();
    _dynarch_popupCalendar = null;
}

DatetimePicker.prototype.showCalendar = function(id, format, showsTime, showsOtherMonths){
    var el = $get(id);
    if (_dynarch_popupCalendar != null) 
        _dynarch_popupCalendar.hide();
    else {
        // first-time call, create the calendar.
        var cal = new Calendar(1, null, DatetimePicker.prototype.selected, DatetimePicker.prototype.closeHandler);
        if (showsTime) {
            cal.showsTime = true;
            cal.time24 = true;
        }
        if (showsOtherMonths) 
            cal.showsOtherMonths = true;
        _dynarch_popupCalendar = cal; // remember it in the global var
        cal.setRange(1900, 2070); // min/max year allowed.
        cal.create();
    }
    _dynarch_popupCalendar.setDateFormat(g_DateFormatPatternForCalendar); // set the specified date format
    _dynarch_popupCalendar.parseDate(el.value); // try to parse the text in field
    _dynarch_popupCalendar.sel = el; // inform it what input field we use    
    _dynarch_popupCalendar.showAtElement(el, "Br");
    return false;
}

/* Date*/
function isDate(dateStr){
    var datePat = /^(\d{4})(\/|-)(\d{1,2})(\/|-)(\d{1,2})$/;
    var matchArray = dateStr.match(datePat); // is the format ok?
    if (matchArray == null) {
        return false;
    }
    
    day = matchArray[5]; // p@rse date into variables
    month = matchArray[3];
    year = matchArray[1];
    
    if (month < 1 || month > 12) { // check month range     
        return false;
    }
    
    if (day < 1 || day > 31) {
        return false;
    }
    
    if ((month == 4 || month == 6 || month == 9 || month == 11) && day == 31) {
        return false;
    }
    
    if (month == 2) { // check for february 29th
        var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
        if (day > 29 || (day == 29 && !isleap)) {
            return false;
        }
    }
    return true; // date is valid
}

validator.prototype.FocusControl = function(strcontrol){
    if ($get(validator.prototype.CtrNeedFocus) == null) {
        validator.prototype.CtrNeedFocus = strcontrol;
        if (validator.prototype.ControlErr == "") 
            validator.prototype.ControlErr = validator.prototype.CtrNeedFocus;
        if (validator.prototype.enableFocus) {
            $get(validator.prototype.CtrNeedFocus).focus();
            validator.prototype.enableFocus = false
        }
    }
}

