// customhours.js
var dayarray;
var dayarray_labels;
var pattern;
var pattern1;
var pattern2;
var validateCheck1 = false;
var validateCheck2 = false;

$(document).ready(function () {
    dayarray = [{ key: 0, value: "MON" }, { key: 1, value: "TUE" }, { key: 2, value: "WED" }, { key: 3, value: "THU" }, { key: 4, value: "FRI" }, { key: 5, value: "SAT" }, { key: 6, value: "SUN" }];
    dayarray_labels = new Array(resource_uccmanager_workday_mon, resource_uccmanager_workday_tue, resource_uccmanager_workday_wed, resource_uccmanager_workday_thu, resource_uccmanager_workday_fri, resource_uccmanager_workday_sat, resource_uccmanager_workday_sun);

    pattern1 = new RegExp(/^(sip:)[A-Za-z0-9\-_\.!~*'()]+@([\w-]+\.)+[\w-]{2,}$/);
    pattern2 = new RegExp(/^(tel:)\+(?:[0-9] ?){6,14}[0-9]$/);

    $("textarea[title='" + resource_uccmanager_field_customhours_title + "']").focus(function () {
        $("textarea[title='" + resource_uccmanager_field_customhours_title + "']").blur();
    });

    if ($("input[title='" + resource_uccmanager_field_customhoursenable_title + "']").prop('checked')) {
        initCustomHours();
    }
    else {
        $("textarea[title='" + resource_uccmanager_field_customhours_title + "']").closest("tr").hide();
    }

    $("input[title='" + resource_uccmanager_field_customhoursenable_title + "']").click(function () {
        if ($(this).prop('checked')) {
            initCustomHours();
            $("textarea[title='" + resource_uccmanager_field_customhours_title + "']").closest("tr").show();
        }
        else {
            $(".addCustomHours").remove();
            $(".customHours").remove();
            $("textarea[title='" + resource_uccmanager_field_customhours_title + "']").closest("tr").hide();
        }
    });

    // Validate agent sip
    ValidateAgentSip();
    $("input[title*='Agent']").bind("keyup", function () {
        ValidateAgentSip();
    });
    $("input[title*='Agent']").bind("focusout", function () {
        ValidateAgentSip();
    });
    $("input[title*='Agent']").bind("mousedown", function () {
        ValidateAgentSip();
    });

    // Validate alternative valler id
    ValidateAlternativeCallerId();
    $("input[title*='Alternative Caller Id']").bind("keyup", function () {
        ValidateAlternativeCallerId();
    });
    $("input[title*='Alternative Caller Id']").bind("focusout", function () {
        ValidateAlternativeCallerId();
    });
    $("input[title*='Alternative Caller Id']").bind("mousedown", function () {
        ValidateAlternativeCallerId();
    });
});

function GenerateFormElements(workdayValue, startHourValue, startMinuteValue, endHourValue, endMinuteValue) {

    // Workdays
    var workdays = "<select name='workday'>";
    workdays += "<option value=''>" + resource_uccmanager_dayselect_text + "</option>";
    for (i = 0; i < dayarray.length; i++) {
        var selected = "";
        if (workdayValue != "") {
            if (workdayValue == dayarray[i].value)
                selected = "selected";
        }
        workdays += "<option value='" + dayarray[i].value + "' " + selected + ">" + dayarray_labels[i] + "</option>";
    }
    workdays += "</select>";

    // StartHours
    var startHour = "<select name='startHour'>";
    for (i = 0; i <= 23; i++) {
        var tmp = i;
        if (i < 10)
            tmp = "0" + tmp;

        var selected = "";
        if (startHourValue != "") {
            if (startHourValue == tmp)
                selected = "selected";
        }
        startHour += "<option value='" + tmp + "' " + selected + ">" + tmp + "</option>";
    }
    startHour += "</select>";

    // EndHours
    var endHour = "<select name='endHour'>";
    for (i = 0; i <= 23; i++) {
        var tmp = i;
        if (i < 10)
            tmp = "0" + tmp;

        var selected = "";
        if (endHourValue != "") {
            if (endHourValue == tmp)
                selected = "selected";
        }
        endHour += "<option value='" + tmp + "' " + selected + ">" + tmp + "</option>";
    }
    endHour += "</select>";

    // StartMinutes
    var startMinute = "<select name='startMinute'>";
    for (i = 0; i <= 59; i++) {
        var tmp = i;
        if (i < 10)
            tmp = "0" + tmp;

        var selected = "";
        if (startMinuteValue != "") {
            if (startMinuteValue == tmp)
                selected = "selected";
        }
        startMinute += "<option value='" + tmp + "' " + selected + ">" + tmp + "</option>";
    }
    startMinute += "</select>";

    // EndMinutes
    var endMinute = "<select name='endMinute'>";
    for (i = 0; i <= 59; i++) {
        var tmp = i;
        if (i < 10)
            tmp = "0" + tmp;

        var selected = "";
        if (endMinuteValue != "") {
            if (endMinuteValue == tmp)
                selected = "selected";
        }
        endMinute += "<option value='" + tmp + "' " + selected + ">" + tmp + "</option>";
    }
    endMinute += "</select>";

    var btnUpdate = "<a href='#' class='BtnUpdateCustomHours'>" + resource_uccmanager_btn_update + "</a>";
    var btnRemove = "<a href='#' class='BtnRemoveCustomHours'>" + resource_uccmanager_btn_remove + "</a>";

    return workdays + "&#160;" + startHour + "&#160;" + startMinute + "&#160;-&#160;" + endHour + "&#160;" + endMinute + " " + btnUpdate + " " + btnRemove;
}

function SortCustomHours(initValue, reverse) {
    if (initValue != "") {
        var daySplit = initValue.split(";");
        for (j = 0; j < daySplit.length; j++) {
            daySplit[j] = daySplit[j].replace(dayarray[0].value, "0T");
            daySplit[j] = daySplit[j].replace(dayarray[1].value, "1T");
            daySplit[j] = daySplit[j].replace(dayarray[2].value, "2T");
            daySplit[j] = daySplit[j].replace(dayarray[3].value, "3T");
            daySplit[j] = daySplit[j].replace(dayarray[4].value, "4T");
        }
        daySplit.sort();
        if (reverse == true)
            daySplit.reverse();

        var returnValue = "";
        for (k = 0; k < daySplit.length; k++) {
            daySplit[k] = daySplit[k].replace("0T", dayarray[0].value);
            daySplit[k] = daySplit[k].replace("1T", dayarray[1].value);
            daySplit[k] = daySplit[k].replace("2T", dayarray[2].value);
            daySplit[k] = daySplit[k].replace("3T", dayarray[3].value);
            daySplit[k] = daySplit[k].replace("4T", dayarray[4].value);
            returnValue += daySplit[k] + ";";
        }

        if (returnValue != "")
            returnValue = returnValue.substring(0, returnValue.length - 1);

        return returnValue;
    }
}

function initCustomHours() {
    var initValue = $("textarea[title='" + resource_uccmanager_field_customhours_title + "']").val();
    if (initValue != "") {
        initValue = SortCustomHours(initValue, true);
        var daySplit = initValue.split(";");
        for (j = 0; j < daySplit.length; j++) {
            var tmpSplit = daySplit[j].split(",");
            var workdayValue = tmpSplit[0];
            var startHourValue = tmpSplit[1].substring(0, tmpSplit[1].indexOf(":"));
            var startMinuteValue = tmpSplit[1].substring(tmpSplit[1].indexOf(":") + 1);
            var endHourValue = tmpSplit[2].substring(0, tmpSplit[2].indexOf(":"));
            var endMinuteValue = tmpSplit[2].substring(tmpSplit[2].indexOf(":") + 1);
            $("input[title='" + resource_uccmanager_field_customhoursenable_title + "']").closest('tr').after("<tr class='customHours'><td class='ms-formlabel' noWrap='' vAlign='top'>&nbsp;</td><td class='ms-formbody' vAlign='top'>" + GenerateFormElements(workdayValue, startHourValue, startMinuteValue, endHourValue, endMinuteValue) + "</td></tr>");
        }
        $('.BtnUpdateCustomHours').click(function (e) {
            e.preventDefault();
            UpdateCustomHours();
        });
        $('.BtnRemoveCustomHours').click(function (e) {
            e.preventDefault();
            RemoveCustomHours($(this));
        });
    }
    var btnAdd = "<a href='#' id='BtnAddCustomHours'>" + resource_uccmanager_btn_add + "</a>";
    $("input[title='" + resource_uccmanager_field_customhoursenable_title + "']").closest('tr').after("<tr class='addCustomHours'><td class='ms-formlabel' noWrap='' vAlign='top'>&nbsp;</td><td class='ms-formbody' vAlign='top'>" + btnAdd + "</td></tr>");
    $('#BtnAddCustomHours').click(function (e) {
        e.preventDefault();
        AddCustomHours();
    });
}

function AddCustomHours() {
    // Current hour
    var date = new Date();
    var hour1 = 9;
    var hour2 = 17;
    $("tr#errorMsgContainer").remove();
    $(".addCustomHours").after("<tr class='customHours'><td class='ms-formlabel' noWrap='' vAlign='top'>&nbsp;</td><td class='ms-formbody' vAlign='top'>" + GenerateFormElements("", hour1, "", hour2, "") + "</td></tr>");
    $('.BtnUpdateCustomHours').click(function (e) {
        e.preventDefault();
        UpdateCustomHours();
    });
    $('.BtnRemoveCustomHours').click(function (e) {
        e.preventDefault();
        RemoveCustomHours($(this));
    });
}

function UpdateCustomHours() {
    $("tr#errorMsgContainer").remove();
    var insertValue = "";
    var validValue = true;
    var emptyValue = false;
    $(".customHours").each(function (index) {
        var workdayValue = $(this).find("select[name=workday]").val();
        var startHourValue = $(this).find("select[name=startHour]").val();
        var startMinuteValue = $(this).find("select[name=startMinute]").val();
        var endHourValue = $(this).find("select[name=endHour]").val();
        var endMinuteValue = $(this).find("select[name=endMinute]").val();

        var compare1 = startHourValue + "" + startMinuteValue;
        var compare2 = endHourValue + "" + endMinuteValue;
        if (compare1 >= compare2)
            validValue = false;
        if (workdayValue == "") {
            validValue = false;
            emptyValue = true;
        }

        insertValue += workdayValue + "," + startHourValue + ":" + startMinuteValue + "," + endHourValue + ":" + endMinuteValue + ";";
    });
    if (insertValue != "") {
        insertValue = insertValue.substring(0, insertValue.length - 1);
        insertValue = SortCustomHours(insertValue, false);
    }

    if (validValue == true)
        $("textarea[title='" + resource_uccmanager_field_customhours_title + "']").val(insertValue);
    else {
        if (emptyValue == true) {
            $(".addCustomHours").after("<tr id='errorMsgContainer'><td class='ms-formlabel' noWrap='' vAlign='top'>&nbsp;</td><td class='ms-formbody' vAlign='top'><span id='errorMsg' style='color:red;'>" + resource_uccmanager_errormessage2 + "</span></td></tr>");
        }
        else {
            $(".addCustomHours").after("<tr id='errorMsgContainer'><td class='ms-formlabel' noWrap='' vAlign='top'>&nbsp;</td><td class='ms-formbody' vAlign='top'><span id='errorMsg' style='color:red;'>" + resource_uccmanager_errormessage1 + "</span></td></tr>");
        }
    }
}

function RemoveCustomHours(element) {
    $(element).closest("tr").remove();
    UpdateCustomHours();
}

function ValidateAgentSip() {
    validateCheck1 = false;
    var testValue = $("input[title*='Agent']").val();
    $("input[id*='SaveItem']").prop("disabled", true);
    $("a[id='Ribbon.ListForm.Edit.Commit.Publish-Large']").prop("class", "ms-cui-ctl-large ms-cui-disabled");
    $("input[title*='Agent']").css("border", "1px solid red");
    if (testValue !== null && testValue !== "") {
        var matchIndex = testValue.indexOf(";");
        if (matchIndex !== -1) {
            testValue = testValue.substring(0, matchIndex);
        }
        
        if (testValue.indexOf("sip:") !== -1) {
            pattern = pattern1;
        }
        else if (testValue.indexOf("tel:") !== -1) {
            pattern = pattern2;
        }

        if (pattern !== null) {
            if (pattern.test(testValue) === true) {
                validateCheck1 = true;
                if (validateCheck1 && validateCheck2) {
                    $("input[id*='SaveItem']").prop("disabled", false);
                    $("a[id='Ribbon.ListForm.Edit.Commit.Publish-Large']").prop("class", "ms-cui-ctl-large");
                }

                $("input[title*='Agent']").css("border", "1px solid green"); 
            }
        }
    }
    else {
        validateCheck1 = true;
        if (validateCheck1 && validateCheck2) {
            $("input[id*='SaveItem']").prop("disabled", false);
            $("a[id='Ribbon.ListForm.Edit.Commit.Publish-Large']").prop("class", "ms-cui-ctl-large");
        }

        $("input[title*='Agent']").css("border", "1px solid #2a8dd4");
    }
}

function ValidateAlternativeCallerId() {
    validateCheck2 = false;
    var testValue = $("input[title*='Alternative Caller Id']").val();
    $("input[id*='SaveItem']").prop("disabled", true);
    $("a[id='Ribbon.ListForm.Edit.Commit.Publish-Large']").prop("class", "ms-cui-ctl-large ms-cui-disabled");
    $("input[title*='Alternative Caller Id']").css("border", "1px solid red");
    if (testValue !== null && testValue !== "") {
        var matchIndex = testValue.indexOf(";");
        if (matchIndex !== -1) {
            testValue = testValue.substring(0, matchIndex);
        }
        
        if (testValue.indexOf("sip:") !== -1) {
            pattern = pattern1;
        }
        else if (testValue.indexOf("tel:") !== -1) {
            pattern = pattern2;
        }

        if (pattern !== null) {
            if (pattern.test(testValue) === true) {
                validateCheck2 = true;
                if (validateCheck1 && validateCheck2) {
                    $("input[id*='SaveItem']").prop("disabled", false);
                    $("a[id='Ribbon.ListForm.Edit.Commit.Publish-Large']").prop("class", "ms-cui-ctl-large");
                }

                $("input[title*='Alternative Caller Id']").css("border", "1px solid green");
            }
        }
    }
    else {
        validateCheck2 = true;
        if (validateCheck1 && validateCheck2) {
            $("input[id*='SaveItem']").prop("disabled", false);
            $("a[id='Ribbon.ListForm.Edit.Commit.Publish-Large']").prop("class", "ms-cui-ctl-large");
        }

        $("input[title*='Alternative Caller Id']").css("border", "1px solid #2a8dd4");
    }
}

RegExp.escape = function (s) {
    return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
};