/*
#############################################
########## Data Validation Library ##########
#############################################
*/


//Check about the input that is fufill the length requirement
function f_checkLength(input, lengthReq) {
    if (input.length == lengthReq)
        return true;
    else
        return false;

}

//Check about the date that is a valid format
function f_checkIsValidDate(input, formatStyle) {

    var re = "";
    var result = false;

    switch (formatStyle) {
        case 'dd':
        case 'mm':

            re = /^\d{1,2}$/
            if (re.test(input))
                result = true;
            else
                result = false;

            break;

        case 'dd/mm':

            re = /^\d{1,2}\/\d{1,2}$/
            if (re.test(input))
                result = true;
            else
                result = false;

            break;

        case 'mm/yyyy':

            re = /^\d{1,2}\/\d{4}$/
            if (re.test(input))
                result = true;
            else
                result = false;

            break;

        case 'dd/mm/yyyy':
            //Advanced Reference Link: http://www.rodsdot.com/ee/dateValidate.asp; http://www.the-art-of-web.com/javascript/validate-date/
            re = /^\d{1,2}\/\d{1,2}\/\d{4}$/
            if (re.test(input))
                result = true;
            else
                result = false;

            break;
    }

    return result;
}

//Check about the time that is a valid format
function f_checkIsValidTime(input, formatStyle) {

    var re = "";
    var result = false;

    switch (formatStyle) {
        case 'mm':
        case 'hh':

            re = /^\d{1,2}$/
            if (re.test(input))
                result = true;
            else
                result = false;

            break;

        case 'hh:mm':

            re = /^\d{1,2}\:\d{1,2}$/
            if (re.test(input))
                result = true;
            else
                result = false;

            break;

        case 'hh:mm:ss':

            re = /^\d{1,2}\:\d{1,2}\:\d{1,2}$/
            if (re.test(input))
                result = true;
            else
                result = false;

            break;
    }

    return result;
}

//Check about the email that is a valid format
function f_checkIsValidEmail(input) {

    //    apos = input.indexOf("@");
    //    dotpos = input.lastIndexOf(".");
    //    if (apos < 1 || dotpos - apos < 2)
    //        return false;
    //    else
    //        return true;
    var pattern = /^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+\.([a-zA-Z0-9])+([a-zA-Z0-9])+$/;
    if (!pattern.test(input)) {
        return false;
    }

    // check index of  (consecutive ..)
    if (input.indexOf("..") >= 0) {
        return false;
    }

    if (f_checkWithSpace(input)) {
        return false;
    }
    return true;

}

//Check about the number that has a valid digits after point
function f_checkIsValidFloatNumber(input, maxDigitsAfterPoint) {

    input = input.toString();

    if (input.lastIndexOf('.') > 0) {

        var diff = input.length - input.lastIndexOf('.') - 1;

        if (diff <= maxDigitsAfterPoint)
            return true;
        else
            return false;

    } return true;

}

//Check about the number that has a negative number
function f_checkIsNegativeNumber(input) {

    if (input >= Number.NEGATIVE_INFINITY && input < 0)
        return true;
    else
        return false;

}

//Check about the number that has a positive number
function f_checkIsPositiveNumber(input) {

    if (input <= Number.POSITIVE_INFINITY && input >= 0)
        return true;
    else
        return false;

}

//Check about the input that is equal another value
function f_checkIsEqual(input1, input2) {

    if (input1.toString() == input2.toString())
        return true;
    else
        return false;

}

//Check about the input that is NOT equal another value
function f_checkIsNotEqual(input1, input2) {

    if (input1.toString() != input2.toString())
        return true;
    else
        return false;

}

//Check about the input that is greater than another value
function f_checkIsGreaterThan(input1, input2) {

    if (input1 > input2)
        return true;
    else
        return false;

}

//Check about the input that is greater and equal another value
function f_checkIsGreaterThanOrEqual(input1, input2) {

    if (input1 >= input2)
        return true;
    else
        return false;

}

//Check about the input that is lower than another value
function f_checkIsLessThan(input1, input2) {

    if (input1 < input2)
        return true;
    else
        return false;

}

//Check about the input that is lower and equal another value
function f_checkIsLessThanOrEqual(input1, input2) {

    if (input1 <= input2)
        return true;
    else
        return false;

}

//Check about the input that is between valueA and ValueB
function CheckIsBetween(input1, input2, input3) {

    if ((input1 >= input2) && (input1 <= input3))
        return true;
    else
        return false;

}

//Check about the input that is contained selected values
function f_checkIsContain(input1, input2Array) {

    var isFound = false;

    var i = 0;
    for (i = 0; i < input2Array.length; i++) {
        if (input1 == input2Array[i])
            isFound = true;
    }

    return isFound;

}

//Check about the input that is not contained selected values
function f_checkIsNotContain(input1, input2Array) {

    var isFound = false;

    var i = 0;
    for (i = 0; i < input2Array.length; i++) {
        if (input1 == input2Array[i])
            isFound = true;
    }

    return !isFound;

}


//Get the value length from target textbox
function f_getTextBoxValueLength(controlID) {

    return document.getElementById(controlID).value.length;

}

//Get the value from target textbox
function f_getTextBoxValue(controlID) {

    return document.getElementById(controlID).value;

}

//Get the selected value from target drop down list
function f_getDropDownListSelectedValue(controlID) {

    var dlist = document.getElementById(controlID);
    return dlist.options[dlist.selectedIndex].value;

}

//Get the selected values from target radio button list
function f_getRadioButtonListSelectedValue(controlID) {

    var rbtn = document.getElementById(controlID).getElementsByTagName('input');

    var result = "";

    for (var i = 0; i < rbtn.length; i++) {
        if (rbtn[i].checked) {
            result = rbtn[i].value;
        }
    }

    return result;

}

//Get the selected index from target checkbox list
function f_getCheckBoxListSelectedIndex(controlID) {

    var clist = document.getElementById(controlID).getElementsByTagName('input');

    var result = new Array();
    var resultIndex = 0;

    for (var i = 0; i < clist.length; i++) {
        if (clist[i].checked) {
            result[resultIndex] = i;
            resultIndex++;
        }
    }

    return result;

}

//Get the selected value from target checkbox
function f_getCheckBoxSelectedValue(controlID) {

    var c = document.getElementById(controlID);
    var result = false;

    if (c.checked)
        result = true;

    return result;

}

//Set the selected value from target drop down list
function f_setDropDownListSelectedIndex(controlID, selectedIndex) {

    var dlist = document.getElementById(controlID);
    dlist.selectedIndex = selectedIndex;

}

//Set the selected values from target radio button list
function f_setRadioButtonListSelectedIndex(controlID, selectedIndex) {

    var rbtn = document.getElementById(controlID).getElementsByTagName('input');
    rbtn[selectedIndex].checked = true;

}

//Set the selected index from target checkbox list
function f_setCheckBoxListSelectedIndex(controlID, selectedIndex, isChecked) {

    var clist = document.getElementById(controlID).getElementsByTagName('input');
    clist[selectedIndex].checked = isChecked;

}

//Set the selected value from target checkbox
function f_setCheckBoxSelectedValue(controlID, isChecked) {

    var c = document.getElementById(controlID);
    c.checked = isChecked;

}

//Set the target control as enabled or disabled
function f_setEnable(controlID, isEnabled, tabIndex) {

    if (document.getElementById(controlID).type == "text" || document.getElementById(controlID).type == "textarea") {
        document.getElementById(controlID).readOnly = !isEnabled;
        if (!isEnabled) {
            document.getElementById(controlID).tabIndex = -1;
        } else {
            document.getElementById(controlID).tabIndex = tabIndex;
        }
    }else{
        document.getElementById(controlID).disabled = !isEnabled;
        document.getElementById(controlID).readOnly = !isEnabled;
        if (!isEnabled) {
            document.getElementById(controlID).tabIndex = -1;
        } else {
            document.getElementById(controlID).tabIndex = tabIndex;
        }
    }
    if (document.getElementById(controlID).type != "submit" && document.getElementById(controlID).type != "checkbox") {
        if (isEnabled) {
            document.getElementById(controlID).style.backgroundColor = "White";
        }
        else {
            document.getElementById(controlID).style.backgroundColor = "#E6E6E6";
        }
    }
}

//Not test
//Set the target control as visibled or invisibled
function f_setVisible(controlID, isVisibled) {

    if (isVisibled)
        document.getElementById(controlID).style.display = "block";
    else
        document.getElementById(controlID).style.display = "none";

}

//Set the target control value
function f_setValue(controlID, input) {

    document.getElementById(controlID).value = input;

}

//Set the focus at target control
function f_setFocus(controlID) {
    if (document.getElementById(controlID) != null) {
        document.getElementById(controlID).focus();
    }
    else {
        controlID.focus();
    }
}

//Set the selection highlight at target control
function f_setSelect(controlID) {

    document.getElementById(controlID).select();

}



//f_checkIsEqual + customized error messange + f_setFocus
function f_checkRequiredField(controlID, ifErrorShowAlert, errorMessage) {

    var c = document.getElementById(controlID);

    if (f_checkIsEqual(c.value, '')) {

        if (ifErrorShowAlert)
            alert(errorMessage);

        return false;
    } else return true;

}
//-------------------------------------------------------------------
// f_isBlank(value)
//   Returns true if value only contains spaces
//-------------------------------------------------------------------
function f_isBlank(val) {
    if (val == null) { return true; }
    for (var i = 0; i < val.length; i++) {
        if ((val.charAt(i) != ' ') && (val.charAt(i) != "\t") && (val.charAt(i) != "\n") && (val.charAt(i) != "\r")) { return false; }
    }
    return true;
}


//Check about the date that is a valid format
function f_checkIsDigits(input) {
    var string = "1234567890";
    if (f_isBlank(input)) {
        return false;
    }
    for (var i = 0; i < input.length; i++) {
        if (string.indexOf(input.charAt(i)) == -1) {
            return false;
        }
    }

    return true;
}
//Check string contain alphanumerical characters only
function f_checkIsLetterOrDigits(input) {
    var string = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    if (f_isBlank(input)) {
        return false;
    }
    for (var i = 0; i < input.length; i++) {
        if (string.indexOf(input.charAt(i)) == -1) {
            return false;
        }
    }

    return true;
}

function f_setRadioButtonListEnable(controlID, selectedIndex, enable) {
    var rbtn = document.getElementById(controlID + "_" + selectedIndex);
    rbtn.disabled = !enable;
    var result = "";
}

//DeSelect the selected values from target radio button list
function f_setRadioButtonListToDeselect(controlID, selectedIndex) {

    var rbtn = document.getElementById(controlID).getElementsByTagName('input');
    rbtn[selectedIndex].checked = false;

}
//Get the target control maxlength
function f_getMaxLength(controlID) {

    return document.getElementById(controlID).getAttribute("maxLength");

}
// rtrim
function rtrim(stringToTrim) {
    return stringToTrim.replace(/\s+$/, "");
}

// ltrim
function ltrim(str, chars) {
    chars = chars || "\\s";
    return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}


// trim
function trim(str, chars) {
    return ltrim(rtrim(str, chars), chars);
}

function f_checkWithSpace(input) {
    var string = " ";
    if (f_isBlank(input)) {
        return false;
    }
    if (input.indexOf(string) != -1) {
        return true;
    }
    return false;
}

//function f_checkMaxLength(Object, MaxLen) {
//    var value = Object.value;
//    var totalLength = 0;
//    for (var i = 0; i < value.length; i++) {
//        if (value.charCodeAt(i) > 126){
//            totalLength += 2;
//        }else{
//            totalLength += 1;
//        }
//        if (totalLength > MaxLen) {
//            Object.value = Object.value.substring(0, i);           
//            break;
//        }
//    }
//}
function f_checkMaxLength_onkeypress(p_object, p_event) {
    //return false;
    var v_event = (window.event) ? window.event : p_event;
    var v_keyCode = (v_event.keyCode) ? v_event.keyCode : v_event.charCode;
    var lastValue = f_getTextBoxValue(p_object.id);
    if ((v_keyCode >= 48 && v_keyCode <= 59) // 1-9
        || (v_keyCode >= 65 && v_keyCode <= 90) // A-Z
        || (v_keyCode >= 96 && v_keyCode <= 111) // 1-9
        || (v_keyCode >= 187 && v_keyCode <= 192)
        || (v_keyCode >= 219 && v_keyCode <= 222)
        || (v_keyCode == 229)) {
        var lSize = f_getMaxLength(p_object.id);
        var newValue = f_getTextBoxValue(p_object.id);
        var totalLength = 0;
        for (var i = 0; i < newValue.length; i++) {
            if (newValue.charCodeAt(i) > 126 || newValue.charCodeAt(i) == 10) {
                 totalLength += 2;
            } else {
                totalLength += 1;
            }
            if (totalLength > lSize) {
                return false;
            }
        }

    }
   return true;
}

function f_checkMaxLength_onblur(p_object) {
    var v_fields = new Array();
    var lSize = f_getMaxLength(p_object.id);
    var newValue = f_getTextBoxValue(p_object.id);
    if (!g_isClosed) return false;
    var totalLength = 0;
    for (var i = 0; i < newValue.length; i++) {
        if (newValue.charCodeAt(i) > 126 || newValue.charCodeAt(i) ==10) {
            totalLength += 2;
        } else {
            totalLength += 1;
        }
    }
    if (totalLength > lSize) {
        v_fields = new Array();
        v_fields[0] = 'The length of input is over the limitation.';
        f_errorMessageShow('99997', p_object.id, v_fields);
    }
}

function f_checkMaxLength(p_object) {
    var lastValue = f_getTextBoxValue(p_object.id);
    lastValue = lastValue.replace(/\'/g, '\\\'');
    lastValue = lastValue.replace(/\"/g, '\\"');
    lastValue = lastValue.replace(/\n/g, '\\n');
    lastValue = lastValue.replace(/\r/g, '')
    setTimeout("f_checkNextMaxLength('" + p_object.id + "', '" + lastValue + "');", 1);

}

function f_checkNextMaxLength(p_objectID, p_lastValue) {
    var lSize = f_getMaxLength(p_objectID);
    var newValue = f_getTextBoxValue(p_objectID);
    var totalLength = 0;
    for (var i = 0; i < newValue.length; i++) {
        if (newValue.charCodeAt(i) > 126 || newValue.charCodeAt(i) == 10) {
            totalLength += 2;
        } else {
            totalLength += 1;
        }
        if (totalLength > lSize) {
           
            f_setValue(p_objectID, p_lastValue);
            f_setValue(p_objectID, p_lastValue.substring(0, i));
            break;
        }
    }
}

