// idrquestions_custom.js
var currentContentType = "";
var currentTitle = "";
var usedChoice = [];
var pattern;
var spVersion = "";

$(document).ready(function () {
    if (customFormMode != "display" && customFormMode != "listview") {
        spVersion = SP.ClientSchemaVersions.currentVersion.substring(0, 2);
    }

    if (customFormMode == "add" || customFormMode == "edit") {
        pattern = new RegExp("^-?\\d*\\.{0,1}\\d+$");
        var titleElement = "input[id*='Title']";

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

        if (customFormMode == "edit") {
            // Hide title input
            currentTitle = $(titleElement).val();
            $(titleElement + ":first").after(currentTitle);
            $(titleElement + ":first").hide();
        }

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

        // Determine ContentType
        var parentCheck = $("select[title*='Parent']").val();
        if (typeof parentCheck != "undefined") {
            currentContentType = "IDRQuestion";
        }
        else {
            currentContentType = "IDRSystemItem";
        }

        if (currentContentType == "IDRQuestion") {
            // Exclude IDRQuestions
            retrieveExcludeIDRQuestions();

            // Validate Choice field
            var parentValue = $("select[title*='Parent'] option:selected").text();
            if (typeof parentValue != "undefined" && parentValue != "") {
                ExecuteOrDelayUntilScriptLoaded(function () { retrieveUsedChoice(parentValue); }, "sp.js");
            }

            // Validate Choice field
            ValidateChoice();
            $("input[title='Choice']").bind("keyup", function () {
                ValidateChoice();
            });
            $("input[title='Choice']").bind("focusout", function () {
                ValidateChoice();
            });
            $("input[title='Choice']").bind("mousedown", function () {
                ValidateChoice();
            });

            $("select[title*='Parent']").change(function () {
                var parentValue = $("select[title*='Parent'] option:selected").text();
                ExecuteOrDelayUntilScriptLoaded(function () { retrieveUsedChoice(parentValue); }, "sp.js");
            });

            // Exclude Skills
            ExecuteOrDelayUntilScriptLoaded(function () { retrieveExcludeSkills() }, "sp.js");

            // Pre-fill title field
            if (customFormMode == "add") {
                var tmpTitle = currentTitle = $(titleElement).val();
                if (tmpTitle == "") {
                    if (currentContentType == "IDRQuestion") {
                        $(titleElement).val("Question ");
                    }
                }
            }

            // Pre fill fields Office365
            if (customFormMode == "add") {
                $("select[title='Queue']").val("Question Queue");
                $("select[title='Workflow']").val("WelcomeFlow");
            }
            $("select[title='Queue']").prop("disabled", true);
            $("select[title='Workflow']").prop("disabled", true);
        }
    }
});

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

    var camlQuery = new SP.CamlQuery();
    camlQuery.set_viewXml("<View><OrderBy><FieldRef Name='Title' /></OrderBy></View>");

    this.collIDRItems = oList.getItems(camlQuery);
    clientContext.load(collIDRItems);
    this.listIDRContentTypes = oList.get_contentTypes();
    clientContext.load(listIDRContentTypes);

    clientContext.executeQueryAsync(Function.createDelegate(this, this.onQueryRetrieveExcludeIDRQuestionsSucceeded), Function.createDelegate(this, this.onQueryFailed));
}

function onQueryRetrieveExcludeIDRQuestionsSucceeded(sender, args) {
    var listItemEnumerator = collIDRItems.getEnumerator();
    while (listItemEnumerator.moveNext()) {
        var oListItem = listItemEnumerator.get_current();
        var oListItemTitle = oListItem.get_item('Title');
        var oListItemCT = oListItem.get_item('ContentTypeId');

        // Get ContentType
        var contentTypeName = "";
        var ct_enumerator = listIDRContentTypes.getEnumerator();
        while (ct_enumerator.moveNext()) {
            var ct = ct_enumerator.get_current();
            if (ct.get_id().toString() == oListItemCT) {
                contentTypeName = ct.get_name();
                break;
            }
        }

        $("select[title*='Parent'] option").each(function () {
            if (currentContentType == "IDRQuestion") {
                if (contentTypeName != currentContentType) {
                    if ($(this).text() == oListItemTitle || $(this).text() == currentTitle) {
                        $(this).remove();
                    }
                }
            }
        });
    }
}

// Used Choice Query
function retrieveUsedChoice(parentValue) {
    var clientContext = SP.ClientContext.get_current();
    var oList = clientContext.get_web().get_lists().getByTitle('IDRQuestions');

    var camlQuery = new SP.CamlQuery();
    camlQuery.set_viewXml("<View><Query><Where><Eq><FieldRef Name='wsp_ucc_idr_parent' /><Value Type='Lookup'>" + parentValue + "</Value></Eq></Where></Query><OrderBy><FieldRef Name='Title' /></OrderBy></View>");
    this.collListItemsChoice = oList.getItems(camlQuery);

    clientContext.load(collListItemsChoice);
    clientContext.executeQueryAsync(Function.createDelegate(this, this.onQueryRetrieveUsedChoiceSucceeded), Function.createDelegate(this, this.onQueryFailed));
}

function onQueryRetrieveUsedChoiceSucceeded(sender, args) {
    usedChoice = [];
    var listItemEnumerator = collListItemsChoice.getEnumerator();
    while (listItemEnumerator.moveNext()) {
        var oListItem = listItemEnumerator.get_current();
        var oListItemTitle = oListItem.get_item('Title');
        var oListItemChoice = oListItem.get_item('wsp_ucc_idr_choice');

        if (oListItemTitle != currentTitle) {
            usedChoice.push(oListItemChoice);
        }
    }
    ValidateChoice();
}

// Skills 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><OrderBy><FieldRef Name='Title' /></OrderBy></View>");

    this.collListItemsSkills = oList.getItems(camlQuery);
    clientContext.load(collListItemsSkills);
    this.listContentTypes = oList.get_contentTypes();
    clientContext.load(listContentTypes);

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

function onQueryRetrieveExcludeSkillsSucceeded(sender, args) {
    var listItemEnumerator = collListItemsSkills.getEnumerator();
    while (listItemEnumerator.moveNext()) {
        var oListItem = listItemEnumerator.get_current();
        var oListItemTitle = oListItem.get_item("Title");
        var oListItemCT = oListItem.get_item("ContentTypeId");

        // Get ContentType
        var contentTypeName = "";
        var ct_enumerator = listContentTypes.getEnumerator();
        while (ct_enumerator.moveNext()) {
            var ct = ct_enumerator.get_current();
            if (ct.get_id().toString() == oListItemCT) {
                contentTypeName = ct.get_name();
                break;
            }
        }

        $("select[title*='Skill'] option").each(function () {
            if (contentTypeName != "ChatSkill" && contentTypeName != "ChatForwardSkill") {
                if ($(this).text() == oListItemTitle) {
                    $(this).remove();
                }
            }
        });
    }
}

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

function ValidateChoice() {
    var testValue = $("input[title='Choice']").val();
    $("input[title='Choice']").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");
    $("span#errorMsg").remove();
    if (pattern.test(testValue) == true) {
        var testInt = parseInt(testValue);
        if (testInt > 0 && testInt < 10) {
            if ($.inArray(testInt, usedChoice) == -1) {
                $("input[id*='SaveItem']").prop("disabled", false);
                $("a[id='Ribbon.ListForm.Edit.Commit.Publish-Large']").prop("class", "ms-cui-ctl-large");
                $("input[title='Choice']").css("border", "1px solid green");
                $("input[title='Choice']").after("<span id='errorMsg' style='color:green;'>&nbsp;&nbsp;&nbsp;OK</span>");
            }
            else {
                var inUseMsg = resource_ivrquestions_errormsg_inuse;
                $("input[title='Choice']").after("<span id='errorMsg' style='color:red;'>&nbsp;&nbsp;&nbsp;" + inUseMsg + "</span>");
            }
        }
        else {
            var notInRangeMsg = resource_ivrquestions_errormsg_notinrange;
            $("input[title='Choice']").after("<span id='errorMsg' style='color:red;'>&nbsp;&nbsp;&nbsp;" + notInRangeMsg + "</span>");
        }
    }
    else {
        var errorMsg = resource_ivrquestions_errormsg_empty;
        if (testValue != null && testValue != "") {
            var errorMsg = resource_ivrquestions_errormsg_nonumber;
        }
        $("input[title='Choice']").after("<span id='errorMsg' style='color:red;'>&nbsp;&nbsp;&nbsp;" + errorMsg + "</span>");
    }
}