﻿function GetClientId(controlId, useOnlyStandardObject) {
    /// <summary>object GetClientId(controlId, useRadObject) to obtain control object.</summary>
    /// <param name="controlId">control ID of the </param>
    /// <param name="useOnlyStandardObject">true if use only standard object; otherwise false (default value is false)</param>
    /// <return>control object</param>
    var body = document.getElementsByTagName("body");
    var id = body[0].attributes["controlPrefix"];

    if (useOnlyStandardObject == undefined || useOnlyStandardObject == null) useOnlyStandardObject = false;

    var clientObject = null;
    var lastIndex = id.value.lastIndexOf("_");
    var postfix = ((lastIndex >= 0) ? postfix = id.value.substring(lastIndex, id.value.length) : "");
    var numOfMasters = (id.value.replace(new RegExp(postfix, "g"), "")).split("_");
    var prefix = id.value;

    for (index = 0; index <= numOfMasters.length; index++) {

        clientId = prefix + "_" + controlId;
        /*
        // telerik
        if (!useOnlyStandardObject) {
            if (clientObject == null) clientObject = find(clientId);
            if (clientObject != null) clientObject.id = clientId;
        }
        */
        // server control
        if (clientObject == null) clientObject = document.getElementById(clientId);

        // html control
        if (clientObject == null) clientObject = document.getElementById(controlId);

        if (clientObject != null) break;

        prefix = prefix.substring(0, prefix.lastIndexOf(postfix));
    }
    return clientObject;
}

// Namespace
var KT = window.KT || {};
// Singleton
KT.Validation = function () {
    //----------------------
    // Private Interface
    //----------------------
    // Message Template
    var MSG_001 = "Please enter {0}.";
    var MSG_002 = "Invalid {0}.";
    var MSG_003 = "Angle brackets (< >) are not allowed.";
    var MSG_004 = "Please select {0}.";
    var MSG_005 = "Please enter valid {0}. Use alphabets and (<span class='text_01'> -', space</span>) only.";
    var MSG_006 = "{0}";
    var MSG_007 = "{0} does not match";
    var MSG_008 = "{0} should contain at least {1} characters.";
    var MSG_009 = "{0} should contain alphabets and numbers only.";
    var MSG_010 = "File extension is invalid.";
    var MSG_011 = "{0} should contain at most {1} characters.";
    var focusedControlId = "";
    // Common validation
    function IsAlphaNumeric(value) { var pattern = /^([a-z]|[A-Z]|[0-9])+$/; return (value != "" && value.match(pattern) == null) ? false : true; }
    function IsAlphaSpecial(value) { /* accept [-] [,] [']*/var pattern = /^([a-z]|[A-Z])+([a-z]|[A-Z]|\-|\,|['']|\ )*$/; return (value != "" && value.match(pattern) == null) ? false : true; }
    function IsAngleBracket(value) { return (value.indexOf('<') > -1 || value.indexOf('>') > -1) ? true : false; }
    function IsAllowedFileExtensions(value1, value2) { var extensionfile = value1.split("."); var extensionAccepted = value2.split(":"); var i = 0; for (i = 0; i < extensionAccepted.length; i++) { if (("." + extensionfile[extensionfile.length - 1]).toLowerCase() == extensionAccepted[i].toLowerCase()) return true; } return false; }
    function IsEmail(value) { var pattern = /^([a-zA-Z0-9''_]+)([a-zA-Z0-9''_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/; return (value != "" && value.match(pattern) == null) ? false : true; }
    function IsEmpty(value) { return (value == ""); }
    function IsEqual(value1, value2) { return (value1 == value2); }
    function IsLengthMin(value, length) { return (value.length >= length); }
    function IsLengthMax(value, length) { return !(value.length <= length); }
    function IsGreater(value1, value2) { return (value1 > value2); }
    function IsNumeric(value) { var pattern = /^([0-9])+$/; return (value != "" && value.match(pattern) == null) ? false : true; }
    function IsPhone(value) { var pattern = /^\d{3}-\d{3}-\d{4}$/; return (value != "" && value.match(pattern) == null) ? false : true; }
    function IsSelected(value) { return (value > 0) ? true : false; }
    function IsSelectedRad(value) { return (value >= 0) ? true : false; } // this is used for only rad combobox
    function IsZipcode(value) { var pattern = /^(\d{5}|\d{5}-\d{4})$/; return (value != "" && value.match(pattern) == null) ? false : true; }
    function IsListChecked(value) { for (var j = 0; j < value.rows.length; j++) { for (var i = 0; i < value.rows[j].cells.length; i++) { if (value.rows[j].cells[i].firstChild != null && value.rows[j].cells[i].firstChild.checked) return true; } } return false; }

    // Utility Method
    function Trim(value) { return value.replace(/^\s*(\b.*\b|)\s*$/, "$1"); }
    function SetMessage(targetControl, focusedControl, errMsgControl, messageId, errMsgParam, errMsgAppend) {
        var errMsgControl = document.getElementById(errMsgControl.id);
        var parameters = errMsgParam.split(":");
        var message = messageId;
        for (i = 0; i < parameters.length; i++) message = message.replace("{" + i + "}", parameters[i]);
        var imgIcon = document.createElement("img");
        imgIcon.src = "/KidsTraining4.0/Media/Icon_Red_Cross.png";
        imgIcon.height = imgIcon.width = "14";
        imgIcon.alt = "";
        imgIcon.className = "vertical_bottom padding_02";
        try {
            // firebox needs this        
            imgIcon.outerHTML = "<img src='/KidsTraining4.0/Media/Icon_Red_Cross.png' height='14px' class='vertical_bottom padding_02' width='14px' alt='' scr='/KidsTraining4.0/Media/Icon_Red_Cross.png'/>";
        }
        catch (e) { }
        message = imgIcon.outerHTML + message;
        errMsgControl.className = "vertical_middle text_15 text_17";
        errMsgControl.innerHTML = (errMsgAppend != undefined || errMsgAppend) ? (errMsgControl.innerHTML + message + "<br/>") : message + "<br/>";
        SetTargetControlStyle(targetControl.id);
        if (focusedControlId == "") focusedControlId = focusedControl.id;
    }
    function InitControls(targetControlId, errMsgControlId, errMsgAppend) {
        var targetControl = GetClientId(targetControlId, true);
        var errMsgControl = GetClientId(errMsgControlId);
        if (!errMsgAppend) errMsgControl.innerHTML = "";
        targetControl.className = targetControl.className.replace(" border_06", "");
    }
    function SetTargetControlStyle(targetControlId) {
        var targetControl = GetClientId(targetControlId);
        targetControl.className = targetControl.className + " border_06";
    }
    //----------------------
    // Public Interface
    //----------------------
    return {
        RemoveError: function (targetControlId, errMsgControlId) {
            InitControls(targetControlId, errMsgControlId, false);
        },

        SetFocus: function () {
            /// <summary>boolean SetFocus() to set first error control.</summary>
            if (focusedControlId != "") {
                var control = GetClientId(focusedControlId, true);
                try {
                    SetScrollBar(focusedControlId, 0, -40);
                    control.focus();
                    control.select();
                } catch (e) { }
                focusedControlId = "";
            }
        },

        CheckDefault: function (targetControlId, mandatory, errMsgControlId, errMsgParam, errMsgAppend) {
            /// <summary>boolean CheckDefault(targetControlId, mandatory, errMsgControlId, errMsgParam, errMsgAppend) checks if field is entered (if mandatory is true) without any angle bracket.</summary>
            /// <param name="targetControlId">Id of target control to validate</param>
            /// <param name="mandatory">true if mandatory; otherwise false</param>
            /// <param name="errMsgControlId">Id of control to set error message</param>
            /// <param name="errMsgParam">parameterts for error message. (use separator [:] for multiple parameters) e.g., "Message", "Message1:Message2"</param>
            /// <param name="errMsgAppend">true if message is appended; otherwise false</param>
            InitControls(targetControlId, errMsgControlId, errMsgAppend);
            var targetControl = GetClientId(targetControlId);
            var errMsgControl = GetClientId(errMsgControlId);
            if (mandatory && IsEmpty(Trim(targetControl.value))) {
                SetMessage(targetControl, targetControl, errMsgControl, MSG_001, errMsgParam, errMsgAppend); return false;
            }
            if (IsAngleBracket(Trim(targetControl.value))) {
                SetMessage(targetControl, targetControl, errMsgControl, MSG_003, errMsgParam, errMsgAppend); return false;
            }
            return true;
        },

        CheckDefaultWithMaxLength: function (targetControlId, mandatory, maxlength, errMsgControlId, errMsgParam, errMsgAppend) {
            /// <summary>boolean CheckDefault(targetControlId, mandatory, errMsgControlId, errMsgParam, errMsgAppend) checks if field is entered (if mandatory is true) without any angle bracket.</summary>
            /// <param name="targetControlId">Id of target control to validate</param>
            /// <param name="mandatory">true if mandatory; otherwise false</param>
            /// <param name="errMsgControlId">Id of control to set error message</param>
            /// <param name="errMsgParam">parameterts for error message. (use separator [:] for multiple parameters) e.g., "Message", "Message1:Message2"</param>
            /// <param name="errMsgAppend">true if message is appended; otherwise false</param>
            InitControls(targetControlId, errMsgControlId, errMsgAppend);
            var targetControl = GetClientId(targetControlId);
            var errMsgControl = GetClientId(errMsgControlId);
            if (mandatory && IsEmpty(Trim(targetControl.value))) {
                SetMessage(targetControl, targetControl, errMsgControl, MSG_001, errMsgParam, errMsgAppend); return false;
            }
            if (IsAngleBracket(Trim(targetControl.value))) {
                SetMessage(targetControl, targetControl, errMsgControl, MSG_003, errMsgParam, errMsgAppend); return false;
            }
            if (IsLengthMax(Trim(targetControl.value), maxlength)) {
                errMsgParam = errMsgParam + ":" + maxlength;
                SetMessage(targetControl, targetControl, errMsgControl, MSG_011, errMsgParam, errMsgAppend); return false;
            }
            return true;
        },

        CheckEmail: function (targetControlId, mandatory, errMsgControlId, errMsgParam, errMsgAppend) {
            /// <summary>boolean CheckEmail(targetControlId, mandatory, errMsgControlId, errMsgParam, errMsgAppend) checks if field is entered (if mandatory is true) with a correct email format.</summary>
            /// <param name="targetControlId">Id of target control to validate</param>
            /// <param name="mandatory">true if mandatory; otherwise false</param>
            /// <param name="errMsgControlId">Id of control to set error message</param>
            /// <param name="errMsgParam">parameterts for error message. (use separator [:] for multiple parameters) e.g., "Message", "Message1:Message2"</param>
            /// <param name="errMsgAppend">true if message is appended; otherwise false</param>
            InitControls(targetControlId, errMsgControlId, errMsgAppend);
            var targetControl = GetClientId(targetControlId);
            var errMsgControl = GetClientId(errMsgControlId);
            if (mandatory && IsEmpty(Trim(targetControl.value))) {
                SetMessage(targetControl, targetControl, errMsgControl, MSG_001, errMsgParam, errMsgAppend); return false;
            }
            if (!IsEmail(Trim(targetControl.value))) {
                SetMessage(targetControl, targetControl, errMsgControl, MSG_002, errMsgParam, errMsgAppend); return false;
            }
            return true;
        },

        CheckName: function (targetControlId, mandatory, errMsgControlId, errMsgParam, errMsgAppend) {
            /// <summary>boolean CheckName(targetControlId, mandatory, errMsgControlId, errMsgParam, errMsgAppend) checks if field is entered (if mandatory is true) with alphabets and accecpted special chars ([-] [,] [']).</summary>
            /// <param name="targetControlId">Id of target control to validate</param>
            /// <param name="mandatory">true if mandatory; otherwise false</param>
            /// <param name="errMsgControlId">Id of control to set error message</param>
            /// <param name="errMsgParam">parameterts for error message. (use separator [:] for multiple parameters) e.g., "Message", "Message1:Message2"</param>
            /// <param name="errMsgAppend">true if message is appended; otherwise false</param>
            InitControls(targetControlId, errMsgControlId, errMsgAppend);
            var targetControl = GetClientId(targetControlId);
            var errMsgControl = GetClientId(errMsgControlId);
            if (mandatory && IsEmpty(Trim(targetControl.value))) {
                SetMessage(targetControl, targetControl, errMsgControl, MSG_001, errMsgParam, errMsgAppend); return false;
            }
            if (!IsAlphaSpecial(Trim(targetControl.value))) {
                SetMessage(targetControl, targetControl, errMsgControl, MSG_005, errMsgParam, errMsgAppend); return false;
            }
            return true;
        },

        CheckPhone: function (targetControl1Id, targetControl2Id, mandatory, errMsgControlId, errMsgParam, errMsgAppend) {
            /// <summary>boolean CheckPhone(targetControl1Id, targetControl2Id, mandatory, errMsgControlId, errMsgParam, errMsgAppend) checks if field is entered (if mandatory is true) with a correct phone format (optioanl extension number).</summary>
            /// <param name="targetControl1Id">Id of target control to validate</param>
            /// <param name="targetControl2Id">Id of target control (extension number) to validate</param>
            /// <param name="mandatory">true if mandatory; otherwise false</param>
            /// <param name="errMsgControlId">Id of control to set error message</param>
            /// <param name="errMsgParam">parameterts for error message. (use separator [:] for multiple parameters) e.g., "Message", "Message1:Message2"</param>
            /// <param name="errMsgAppend">true if message is appended; otherwise false</param>
            InitControls(targetControl1Id, errMsgControlId, errMsgAppend);
            InitControls(targetControl2Id, errMsgControlId, errMsgAppend);
            var targetControl1 = GetClientId(targetControl1Id);
            var targetControl2 = GetClientId(targetControl2Id);
            var errMsgControl = GetClientId(errMsgControlId);
            if (mandatory && IsEmpty(Trim(targetControl1.value))) {
                SetMessage(targetControl1, targetControl1, errMsgControl, MSG_001, errMsgParam, errMsgAppend); return false;
            }
            if (IsEmpty(Trim(targetControl1.value)) && !IsEmpty(Trim(targetControl2.value))) {
                SetMessage(targetControl1, targetControl1, errMsgControl, MSG_002, errMsgParam, errMsgAppend); return false;
            }
            if (!IsPhone(Trim(targetControl1.value))) {
                SetMessage(targetControl1, targetControl1, errMsgControl, MSG_002, errMsgParam, errMsgAppend); return false;
            }
            if (!IsEmpty(Trim(targetControl2.value)) && !IsNumeric(Trim(targetControl2.value))) {
                SetMessage(targetControl2, targetControl2, errMsgControl, MSG_002, errMsgParam, errMsgAppend); return false;
            }
            return true;
        }
    }
} ();

window.onerror = function (message, url, line) {

    var param = "";

    var errorAjax = false;

    try {
        var errorLog = message.split(":");

        if (errorLog != null && errorLog.length > 0) {

            for (i = 0; i < errorLog.length; i++) {

                if (errorLog[i].indexOf("errorLogId") >= 0) {

                    var parts = errorLog[i].split("=");

                    param = "?errorLogId=" + parts[1];
                }
                else if (errorLog[i].indexOf("errorAjax") >= 0) {

                    errorAjax = true;
                }
            }
        }
    }
    catch (e) { }

    // client script error
    if (!errorAjax) {
        param = "?errorClientScript=[" + message.replace("<", "#") + "]:url[" + url + "]:line[" + line + "]";
    }

    param = param + ((param == "") ? "?" : "&") + "master=" + GetClientId("uxInputImmediateMasterPage").value;

    window.location.href = "/KidsTraining4.0/Error.aspx" + param;

    return true;
}
