// endpoints_custom.js
var pattern;
var titleElement;
var currentContentType = "";

$(document).ready(function () {
    pattern = new RegExp("^(sip:)[A-Za-z0-9\\-_\\.!~*'()]+@([\\w-]+\\.)+[\\w-]{2,}$");

    // Exclude IVRQuestions
    if (customFormMode == "add" || customFormMode == "edit") {
        ExecuteOrDelayUntilScriptLoaded(function () { retrieveExcludeIVRQuestions(); }, "sp.js");

        // SP 2010 title select workarround
        titleElement = "input[id*='Title']";
        var titleTest = $(titleElement).val();
        if (typeof titleTest == "undefined") {
            titleElement = "input[id*='ctl00_ctl05_ctl00']";
        }

        // Hide contenttype change
        $("select[id*='ContentTypeChoice']").closest('tr').hide();

        // Determine content type
        var ctId = getUrlParameter('contenttypeid');
        if (typeof ctId != "undefined" && ctId.substring(0, 38).toLowerCase() == "0x0100ecf4300da77a4171a49134a3ca3ae4a7") {
            currentContentType = "ModalityEndpoint";
        }
        else if (typeof ctId != "undefined" && ctId.substring(0, 38).toLowerCase() == "0x010092195a9dd14d4b4cb3c2536417d416ec") {
            currentContentType = "SystemEndpoint";
        }
        else if (typeof ctId != "undefined" && ctId.substring(0, 38).toLowerCase() == "0x0100c10abfa06cbb436cad0313ff9e01a086") {
            currentContentType = "MainEndpoint";
        }
        else if (typeof ctId != "undefined" && ctId.substring(0, 38).toLowerCase() == "0x0100b8e2df1ab06f4478a6aa26ada1ea53e5") {
            currentContentType = "DefaultRoutingEndpoint";
        }
        else {
            currentContentType = "ModalityEndpoint";
        }

        // Fill type field
        if (customFormMode == "add") {
            $("input[title*='Type']").val(currentContentType);
            $("input[title*='Type']").prop("disabled", true);
        }
        else {
            $("input[title*='Type']").closest('tr').hide();
        }
    }
    else if (customFormMode == "listview") {
        // Change new item link
        ChangeEndpointNewItemLink();
    }

    // Validate Endpoint Sip
    ValidateEndpointSip();
    $(titleElement).bind("keyup", function () {
        ValidateEndpointSip();
    });
    $(titleElement).bind("focusout", function () {
        ValidateEndpointSip();
    });
    $(titleElement).bind("mousedown", function () {
        ValidateEndpointSip();
    });

    // Modality dropdown
    CreateOptionalDropdown($("input[title*='Modality']").val());
    // Skill / ParentQuestion choice
    initBooleanValue();
});

function ChangeEndpointNewItemLink() {
    // Determine if Endpoint list
    var requestUrl = document.URL;
    var pos0 = requestUrl.toLowerCase().indexOf("/lists/endpoints/");
    if (pos0 != -1) {
        // Determine view name
        var pos1 = requestUrl.lastIndexOf("/");
        var pos2 = requestUrl.lastIndexOf(".");
        if (pos1 != -1 && pos2 != -1) {
            var viewName = (requestUrl.substring(pos1 + 1, pos2));

            // Get target link string
            var target = $("td.ms-list-addnew a:first").attr("onclick");
            if (target == null) {
                target = $("td.ms-addnew a:first").attr("onclick");
            }
            if (target != null && target != "") {
                var pos3 = target.indexOf('"');
                if (pos3 != -1) {
                    var pos4 = target.indexOf('"', pos3 + 1);
                    if (pos4 != -1) {
                        var oldLink = target.substring(pos3 + 1, pos4);

                        // Determine content type id
                        var contentTypeId = "0x0100ecf4300da77a4171a49134a3ca3ae4a7";
                        var tmpViewName = viewName.toLowerCase();
                        if (tmpViewName == "systemendpointview") {
                            contentTypeId = "0x010092195a9dd14d4b4cb3c2536417d416ec";
                        }
                        else if (tmpViewName == "mainendpointview") {
                            contentTypeId = "0x0100c10abfa06cbb436cad0313ff9e01a086";
                        }
                        else if (tmpViewName == "defaultroutingendpointview") {
                            contentTypeId = "0x0100b8e2df1ab06f4478a6aa26ada1ea53e5";
                        }

                        // Determine new link
                        var newLink = requestUrl;
                        var pos5 = newLink.indexOf("?");
                        if (pos5 != -1) {
                            newLink = newLink.substring(0, pos5);
                        }
                        newLink = newLink.replace(viewName, "NewForm");
                        newLink += "?Source=" + encodeURIComponent(requestUrl) + "&RootFolder=&ContentTypeId=" + contentTypeId;

                        // Change new link
                        target = target.replace(oldLink, newLink);
                        $("td.ms-list-addnew a:first").attr("onclick", target);
                        $("td.ms-list-addnew a:first").attr("href", newLink);
                        $("td.ms-addnew a:first").attr("onclick", target);
                        $("td.ms-addnew a:first").attr("href", newLink);
                    }
                }
            }
        }
    }
}

function ValidateEndpointSip() {
    var testValue = $(titleElement).val();
    if (testValue != null && testValue != "") {
        $(titleElement).css("border", "1px solid red");
        $("input[id*='SaveItem']").prop("disabled", true);
        $("a[id='Ribbon.ListForm.Edit.Commit.Publish-Large']").prop("class", "ms-cui-ctl-large ms-cui-disabled");
        if (pattern.test(testValue) == true) {
            $("input[id*='SaveItem']").prop("disabled", false);
            $(titleElement).css("border", "1px solid green");
            $("a[id='Ribbon.ListForm.Edit.Commit.Publish-Large']").prop("class", "ms-cui-ctl-large");
        }
    }
    else {
        $("input[id*='SaveItem']").prop("disabled", false);
        $(titleElement).css("border", "1px solid #2a8dd4")
        $("a[id='Ribbon.ListForm.Edit.Commit.Publish-Large']").prop("class", "ms-cui-ctl-large");
    }
}

// IVRQuestions Exclude Values Query
function retrieveExcludeIVRQuestions() {
    var clientContext = SP.ClientContext.get_current();
    var oList = clientContext.get_web().get_lists().getByTitle('IVRQuestions');

    var camlQuery = new SP.CamlQuery();
    camlQuery.set_viewXml("<View><Query><Where><Or><Eq><FieldRef Name='Title' /><Value Type='Text'>Welcome Message</Value></Eq><And><Neq><FieldRef Name='ContentType' /><Value Type='Text'>IVRQuestionItem</Value></Neq><Neq><FieldRef Name='ContentType' /><Value Type='Text'>IVRPromptItem</Value></Neq></And></Or></Where></Query><OrderBy><FieldRef Name='Title' /></OrderBy></View>");
    this.collListItem = oList.getItems(camlQuery);

    clientContext.load(collListItem);
    clientContext.executeQueryAsync(Function.createDelegate(this, this.onQueryRetrieveExcludeIVRQuestionsSucceeded), Function.createDelegate(this, this.onQueryFailed));
}

function onQueryRetrieveExcludeIVRQuestionsSucceeded(sender, args) {
    var listItemEnumerator = collListItem.getEnumerator();
    while (listItemEnumerator.moveNext()) {
        var oListItem = listItemEnumerator.get_current();
        var oListItemTitle = oListItem.get_item('Title');
        $("select[title='ParentQuestion'] option").each(function () {
            if ($(this).text() == oListItemTitle && oListItemTitle != "Welcome Message") {
                $(this).remove();
            }
        });
    }
}

function onQueryFailed(sender, args) {
    console.log('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}

function CreateOptionalDropdown(selectedValue) {
    var outputHtml = "";
    var textValue = "Chat;Audio;CallMe;Voicemail;ChatAudio;ChatHunt;OutboundDialer";

    if (textValue != null && textValue != "") {
        var counter = 0;
        var selected = false;
        outputHtml = '<select id="valueDD" class="ms-long ms-spellcheck-true" style="width: 100px;">';
        if (textValue.indexOf(';') != -1) {
            var textValueSplit = textValue.split(";");
            textValueSplit.sort();
            for (j = 0; j < textValueSplit.length; j++) {
                counter++;
                var tmpValue = textValueSplit[j];
                if (selectedValue != "" && selectedValue == tmpValue) {
                    selected = true;
                    outputHtml += '<option value="' + tmpValue + '" selected>' + tmpValue + '</option>';
                }
                else {
                    outputHtml += '<option value="' + tmpValue + '">' + tmpValue + '</option>';
                }
            }
        }
        else {
            counter++;
            outputHtml += '<option value="' + textValue + '" selected>' + textValue + '</option>';
        }

        $("input[title*='Modality']").css("width", "360px");
        if (selected == false && selectedValue != "") {
            outputHtml += '<input type="checkbox" id="customValue" name="customValue" value="1" checked style="margin-left:5px;">';
        }
        else {
            outputHtml += '<input type="checkbox" id="customValue" name="customValue" value="1" style="margin-left:5px;">';
        }

        if (counter > 0) {
            $("input[title*='Modality']").after(outputHtml);

            if (selectedValue == "" || (selectedValue != "" && selected == true)) {
                $("input[title*='Modality']").hide();
                $("input[title*='Modality']").val($("#valueDD").val());
            }
            else if (selectedValue != "" && selected == false) {
                $("#valueDD").hide();
            }

            $("#valueDD").change(function () {
                $("input[title*='Modality']").val($(this).val());
            });

            $('#customValue').change(function () {
                if ($(this).is(":checked")) {
                    $("#valueDD").hide();
                    $("input[title*='Modality']").show();
                }
                else {
                    $("input[title*='Modality']").hide();
                    $("#valueDD").show();
                }
            });
        }
    }
}

function initBooleanValue() {
    var initValue1 = $("select[title='Skill']").val();
    var initValue2 = $("select[title='ParentQuestion']").val();

    $("input[title*='Modality']").closest('tr').after("<tr class='textValue'><td class='ms-formlabel' noWrap='' vAlign='top'>Step into</td><td class='ms-formbody' vAlign='top'>" + GenerateFormBooleanElements(initValue1, initValue2) + "</td></tr>");
    $(".booleanValue").click(function () {
        SetBooleanValue($(this));
    });
}

function GenerateFormBooleanElements(initValue1, initValue2) {
    $("select[title='Skill']").closest('tr').hide();
    $("select[title='ParentQuestion']").closest('tr').hide();
    var checked1 = "";
    var checked2 = "";
    var disabled1 = "";
    var disabled2 = "";
    if (initValue1 != "0") {
        checked1 = " checked='checked'";
        $("select[title='ParentQuestion']").closest("tr").hide();
        $("select[title='Skill']").closest("tr").show();
    }
    else if (initValue2 != "0") {
        checked2 = " checked='checked'";
        $("select[title='Skill']").closest("tr").hide();
        $("select[title='ParentQuestion']").closest("tr").show();
    }

    var booleanElement1 = "<input type='radio' name='booleanValue' class='booleanValue' value='skill'" + checked1 + " " + disabled1 + ">Skill";
    var booleanElement2 = "<input type='radio' name='booleanValue' class='booleanValue' value='parentquestion'" + checked2 + " " + disabled2 + ">ParentQuestion";

    return booleanElement1 + " " + booleanElement2;
}

function SetBooleanValue(element) {
    var booleanValue = $(element).val();
    if (booleanValue == "skill") {
        $("select[title='ParentQuestion']").val("0");
        $("select[title='ParentQuestion']").closest("tr").hide();
        $("select[title='Skill']").closest("tr").show();
    }
    else if (booleanValue == "parentquestion") {
        $("select[title='Skill']").val("0");
        $("select[title='Skill']").closest("tr").hide();
        $("select[title='ParentQuestion']").closest("tr").show();
    }
}

function getUrlParameter(sParam) {
    var sPageURL = decodeURIComponent(window.location.search.substring(1).toLowerCase()),
        sURLVariables = sPageURL.split('&'),
        sParameterName,
        i;

    for (i = 0; i < sURLVariables.length; i++) {
        sParameterName = sURLVariables[i].split('=');

        if (sParameterName[0] === sParam) {
            return sParameterName[1] === undefined ? true : sParameterName[1];
        }
    }
}