// skills_custom.js
var pattern;
var pattern1;
var pattern2;

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

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

    // Change new item link
    ChangeSkillsNewItemLink();

    // Exclude Non Audio Skills
    if ($("select[title*='AvailabilityEscapeSkill']").length || $("select[title*='CountdownEscapeSkill']").length) {
        ExecuteOrDelayUntilScriptLoaded(function () { retrieveExcludeSkills(); }, "sp.js");
    }

    // Validate ForwardToSip
    ValidateForwardToSip();
    $("input[title*='ForwardToSip']").bind("keyup", function () {
        ValidateForwardToSip();
    });
    $("input[title*='ForwardToSip']").bind("focusout", function () {
        ValidateForwardToSip();
    });
    $("input[title*='ForwardToSip']").bind("mousedown", function () {
        ValidateForwardToSip();
    });
});

function ValidateForwardToSip() {
    var testValue = $("input[title*='ForwardToSip']").val();
    if (testValue != null && testValue != "") {
        var matchIndex = testValue.indexOf(";");
        if (matchIndex != -1) {
            testValue = testValue.substring(0, matchIndex);
        }
        $("input[title*='ForwardToSip']").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 (testValue.indexOf("sip:") != -1) {
            pattern = pattern1;
        }
        else if (testValue.indexOf("tel:") != -1) {
            pattern = pattern2;
        }

        if (pattern != null) {
            if (pattern.test(testValue) == true) {
                $("input[id*='SaveItem']").prop("disabled", false);
                $("input[title*='ForwardToSip']").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);
        $("input[title*='ForwardToSip']").css("border", "1px solid #2a8dd4");
        $("a[id='Ribbon.ListForm.Edit.Commit.Publish-Large']").prop("class", "ms-cui-ctl-large");
    }
}

function ChangeSkillsNewItemLink() {
    // Determine if Skills list
    var requestUrl = document.URL;
    var pos0 = requestUrl.toLowerCase().indexOf("/lists/skills/");
    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 = "0x0100eaa9773c27c34c839546ffa73807bf37";
                        var tmpViewName = viewName.toLowerCase();
                        if (tmpViewName == "chatskillview") {
                            contentTypeId = "0x0100ea6b62e0be14412a809964b346565f45";
                        }
                        else if (tmpViewName == "countdownskillview") {
                            contentTypeId = "0x01003343ffba61094f7ab40092305f0ed699";
                        }
                        else if (tmpViewName == "forwardskillview") {
                            contentTypeId = "0x0100a5b746647f034c3e8fea942dee4c09c5";
                        }
                        else if (tmpViewName == "availabilityskillview") {
                            contentTypeId = "0x01007755ebc65e59614ea6031b7cd27bcb81";
                        }
                        else if (tmpViewName == "chatforwardskillview") {
                            contentTypeId = "0x010017c7b8112b4c40628aa21c88b6f9406f";
                        }
                        else if (tmpViewName == "countdownavailabilityskillview") {
                            contentTypeId = "0x0100c35cf7e695e54c3385add4b9223c8481";
                        }
                        else if (tmpViewName == "escapemaxqueuesizeskillview") {
                            contentTypeId = "0x0100d38d5473574c5547b83b7dcb8afdda6a";
                        }

                        // 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);
                    }
                }
            }
        }
    }
}

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

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

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

function onQueryRetrieveExcludeSkillsSucceeded(sender, args) {
    var listItemEnumerator = collListItem.getEnumerator();
    while (listItemEnumerator.moveNext()) {
        var oListItem = listItemEnumerator.get_current();
        var oListItemTitle = oListItem.get_item('Title');
        $("select[title*='AvailabilityEscapeSkill'] option").each(function () {
            if ($(this).text() == oListItemTitle) {
                $(this).remove();
            }
        });
        $("select[title*='CountdownEscapeSkill'] option").each(function () {
            if ($(this).text() == oListItemTitle) {
                $(this).remove();
            }
        });
    }
}

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