// ivrquestions_custom.js
var currentContentType = "";
var currentTitle = "";
var currentAction = "";
var usedChoice = [];
var ivrData = [];
var ivrProcessedData = [];
var skillsData = [];
var pattern;
var validateCheck1 = false;
var validateCheck2 = false;
var validateCheck3 = false;
var validateCheck4 = false;
var validateCheck5 = false;
var validateCheck6 = false;
var spVersion = "";

$(document).ready(function () {
    spVersion = SP.ClientSchemaVersions.currentVersion.substring(0, 2);

    if (customFormMode == "listview") {
        // Change new item link
        ChangeIVRQuestionsNewItemLink();

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

        if (viewName != "CallbackItemView" && viewName != "SystemItemView") {
            ExecuteOrDelayUntilScriptLoaded(function () { retrieveIVRQuestions() }, "sp.js");
        }

        // Collapse 'Callback Queue' by default
        $(".ms-gb").each(function () {
            if ($(this).text().indexOf("Callback Queue") != -1) {
                $(this).find("a").click();
            }
        });
    }
    else {
        pattern = new RegExp("^-?\\d*\\.{0,1}\\d+$");

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

        // Determine ContentType
        var ctId = getUrlParameter('contenttypeid');
        var parentCheck = $("select[title*='Parent']").val();
        var actionCheck = $("select[title='Action']").val();

        if (typeof parentCheck != "undefined") {
            if (ctId.substring(0, 38).toLowerCase() == "0x010088bb6df099ea443394741878314a8d55") {
                currentContentType = "IVRHolidayQuestionItem";
            }
            else {
                currentContentType = "IVRQuestionItem";
            }
        }
        else {
            if (typeof actionCheck != "undefined") {
                currentContentType = "IVRCustomSystemItem";
            }
            else {
                if (ctId.substring(0, 38).toLowerCase() == "0x010070c809f405344d9eb874fd06f35d8be8") {
                    currentContentType = "IVRCallbackItem";
                }
                else {
                    currentContentType = "IVRSystemItem";
                }
            }
        }

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

        if (currentContentType == "IVRQuestionItem" || currentContentType == "IVRHolidayQuestionItem" || currentContentType == "IVRCustomSystemItem") {
            // Hide title
            if (customFormMode == "edit") {
                currentTitle = $(titleElement).val();
                $(titleElement + ":first").after(currentTitle);
                $(titleElement + ":first").hide();
            }

            // Exclude parent values
            ExecuteOrDelayUntilScriptLoaded(function () { retrieveExcludeIVRQuestions(); }, "sp.js");

            // Exclude PromptsConfig values
            ExecuteOrDelayUntilScriptLoaded(function () { retrieveExcludePromptsConfig(); }, "sp.js");

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

            // Action
            ActionHandler();
            $("select[title*='Action']").change(function () {
                ActionHandler();
                ChoiceTimeoutHandler();
                if (typeof parentValue != "undefined" && parentValue != "") {
                    ExecuteOrDelayUntilScriptLoaded(function () { retrieveUsedChoice(parentValue); }, "sp.js");
                }
            });

            // Validate Choice field
            ValidateChoice();
            $("select[title*='Choice']").bind("keyup", function () {
                ValidateChoice();
            });
            $("select[title*='Choice']").bind("focusout", function () {
                ValidateChoice();
            });
            $("select[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");
            });

            // Choice Timeout
            ChoiceTimeoutHandler();
            $("input[title='Choice Timeout']").bind("keyup", function () {
                ValidateChoiceTimeout();
                ChoiceTimeoutHandler();
            });
            $("input[title='Choice Timeout']").bind("focusout", function () {
                ValidateChoiceTimeout();
                ChoiceTimeoutHandler();
            });
            $("input[title='Choice Timeout']").bind("mousedown", function () {
                ValidateChoiceTimeout();
                ChoiceTimeoutHandler();
            });

            $("select[title='Skill']").change(function () {
                ChoiceTimeoutHandler();
                ValidateSkill();
            });

            $("select[title='Name']").change(function () {
                ValidateName();
            });

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

            // Skill Dependencies
            if (currentContentType == "IVRCustomSystemItem" && currentTitle.toLowerCase() == "message busy") {
                ExecuteOrDelayUntilScriptLoaded(function () { retrieveAudioSkills(); }, "sp.js");

                if (!$("input[title='Enable Skill Dependency']").prop('checked')) {
                    $("textarea[title='Skill Dependencies']").closest("tr").hide();
                }

                $("input[title='Enable Skill Dependency']").click(function () {
                    if ($(this).prop('checked')) {
                        initSkillDependency();
                        $("textarea[title='Skill Dependencies']").closest("tr").show();
                    }
                    else {
                        $(".addSkillDependency").remove();
                        $(".skillDependency").remove();
                        $("textarea[title='Skill Dependencies']").closest("tr").hide();
                    }
                });
            }
            else {
                $("input[title='Enable Skill Dependency']").closest("tr").hide();
                $("textarea[title='Skill Dependencies']").closest("tr").hide();
            }

            // Pre fill fields Office365
            if (currentContentType == "IVRQuestionItem") {
                $("select[title='Queue']").val("2 - Question Queue");
                $("textarea[title='Description']").prop("disabled", true);
                $("input[title='Order']").prop("disabled", true);
                $("select[title='Queue']").prop("disabled", true);
                $("select[title='Workflow']").prop("disabled", true);
            }
            else if (currentContentType == "IVRHolidayQuestionItem") {
                if (customFormMode == "add") {
                    $("textarea[title='Description']").val(resource_ivrquestions_description_holidayquestion);
                    $("input[title='Order']").val("100");
                    $("select[title='Queue']").val("1 - Entering Queue");
                    $("select[title='Workflow']").val("Holiday");
                    $("textarea[title='Description']").prop("disabled", true);
                    $("input[title='Order']").prop("disabled", true);
                    $("select[title='Queue']").prop("disabled", true);
                    $("select[title='Workflow']").prop("disabled", true);
                }
                else {
                    $("textarea[title='Description']").closest("tr").hide();
                    $("input[title='Order']").closest("tr").hide();
                    $("select[title='Queue']").closest("tr").hide();
                    $("select[title='Workflow']").closest("tr").hide();
                }
            }
        }
        else if (currentContentType == "IVRCallbackItem") {
            // Pre fill fields Office365
            if (customFormMode == "add") {
                $("input[title='Order']").val("470");
                $("select[title='Queue']").val("3 - Callback Queue");
                $("select[title='Workflow']").val("Callback");
                $("input[title='Order']").prop("disabled", true);
                $("select[title='Queue']").prop("disabled", true);
                $("select[title='Workflow']").prop("disabled", true);
            }
            else {
                // Hide title
                if (customFormMode == "edit") {
                    currentTitle = $(titleElement).val();
                    $(titleElement + ":first").after(currentTitle);
                    $(titleElement + ":first").hide();
                }

                $("input[title='Order']").closest("tr").hide();
                $("select[title='Queue']").closest("tr").hide();
                $("select[title='Workflow']").closest("tr").hide();
            }
        }
        else {
            // Hide title input with system items
            if (customFormMode == "edit") {
                currentTitle = $(titleElement).val();
                $(titleElement + ":first").after(currentTitle);
                $(titleElement + ":first").hide();
                if (currentTitle === "Welcome Recording") {
                    // Validate Question / AudioQuestion fields
                    ValidateQuestion();
                    ValidateAudioQuestion();
                    $("textarea[title='Question']").bind("keyup", function () {
                        ValidateQuestion();
                    });
                    $("textarea[title='Question']").bind("focusout", function () {
                        ValidateQuestion();
                    });
                    $("textarea[title='Question']").bind("mousedown", function () {
                        ValidateQuestion();
                    });
                    $("select[title='AudioQuestion']").bind("keyup", function () {
                        ValidateAudioQuestion();
                    });
                    $("select[title='AudioQuestion']").bind("focusout", function () {
                        ValidateAudioQuestion();
                    });
                    $("select[title='AudioQuestion']").bind("mousedown", function () {
                        ValidateAudioQuestion();
                    });
                }
            }
        }
    }
});

function ChangeIVRQuestionsNewItemLink() {
    // Determine if IVRQuestions list
    var requestUrl = document.URL;
    var pos0 = requestUrl.toLowerCase().indexOf("/lists/ivrquestions/");
    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 = "0x0100ce5ce9e97fe341ad831fd767f21deafe";
                        var tmpViewName = viewName.toLowerCase();
                        if (tmpViewName == "questionitemview") {
                            contentTypeId = "0x0100ce5ce9e97fe341ad831fd767f21deafe";
                        }
                        else if (tmpViewName == "holidayquestionitemview") {
                            contentTypeId = "0x010088bb6df099ea443394741878314a8d55";
                        }

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

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

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

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

function onQueryRetrieveExcludeIVRQuestionsSucceeded(sender, args) {
    var listItemEnumerator = collListItems1.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*='Parent'] option").each(function () {
            if (currentContentType == "IVRQuestionItem") {
                if (contentTypeName != currentContentType && $(this).text().toLowerCase() != "welcome message") {
                    if ($(this).text() == oListItemTitle || $(this).text() == currentTitle) {
                        $(this).remove();
                    }
                }
            }
        });
    }
}

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

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

    clientContext.load(collListItemsPromptsConfig);
    clientContext.executeQueryAsync(Function.createDelegate(this, this.onQueryRetrieveExcludePromptsConfigSucceeded), Function.createDelegate(this, this.onQueryFailed));
}

function onQueryRetrieveExcludePromptsConfigSucceeded(sender, args) {
    var listItemEnumerator = collListItemsPromptsConfig.getEnumerator();
    while (listItemEnumerator.moveNext()) {
        var oListItem = listItemEnumerator.get_current();
        var oListItemPromptId = oListItem.get_item('PromptId');
        //var oListItemPromptType = oListItem.get_item('wsp_ucc_pc_prompttype');

        // $("select[title*='Name'] option").each(function () {
        //if (oListItemPromptType != "Prompt") {
        //if ($(this).text() == oListItemPromptId) {
        // $(this).remove();
        //}
        //}
        // });
    }
}

// Used Keys Query
function retrieveUsedChoice(parentValue) {
    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><And><Eq><FieldRef Name='wsp_ucc_ivr_Parent' /><Value Type='Lookup'>" + parentValue + "</Value></Eq><Eq><FieldRef Name='ContentType' /><Value Type='Text'>" + currentContentType + "</Value></Eq></And></Where></Query><OrderBy><FieldRef Name='Title' /></OrderBy></View>");
    this.collListItems2 = oList.getItems(camlQuery);

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

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

        var addLock = true;
        if (currentAction != "Prompt" && oListItemAction != "Prompt") {
            addLock = false;
        }
        else if (currentAction == "Prompt" && oListItemAction == "Prompt") {
            addLock = false;
        }

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

// IVRQuestions data Query
function retrieveIVRQuestions() {
    ivrData = [];
    var clientContext = SP.ClientContext.get_current();
    var oList = clientContext.get_web().get_lists().getByTitle('IVRQuestions');
    this.oListSkills = clientContext.get_web().get_lists().getByTitle('Skills');
    this.oListPromptsConfig = clientContext.get_web().get_lists().getByTitle('PromptsConfig');

    var camlQuery = new SP.CamlQuery();
    camlQuery.set_viewXml("<View><OrderBy><FieldRef Name='Title' /></OrderBy></View>");
    this.collListItems3 = oList.getItems(camlQuery);
    this.collListContentTypes = oList.get_contentTypes();

    clientContext.load(collListItems3);
    clientContext.load(collListContentTypes);
    clientContext.load(oListSkills);
    clientContext.load(oListPromptsConfig);
    clientContext.executeQueryAsync(Function.createDelegate(this, this.onQueryRetrieveIVRQuestionsSucceeded), Function.createDelegate(this, this.onQueryFailed));
}

function onQueryRetrieveIVRQuestionsSucceeded(sender, args) {
    var listItemEnumerator = collListItems3.getEnumerator();
    while (listItemEnumerator.moveNext()) {
        var oListItem = listItemEnumerator.get_current();
        var oListItemId = oListItem.get_item('ID');
        var oListItemTitle = oListItem.get_item('Title');
        var oListItemCT = oListItem.get_item('ContentTypeId').toString();
        var oListItemCTName = "";
        var ct_enumerator = collListContentTypes.getEnumerator();
        while (ct_enumerator.moveNext()) {
            var ct = ct_enumerator.get_current();
            if (ct.get_id().toString() == oListItemCT) {
                oListItemCTName = ct.get_name();
            }
        }
        var oListItemAction = oListItem.get_item('wsp_ucc_ivr_action');
        if (oListItemAction == null) {
            oListItemAction = "";
        }
        var oListItemParent = oListItem.get_item('wsp_ucc_ivr_Parent');
        var oListItemChoiceTimeout = oListItem.get_item('wsp_ucc_ivr_choicetimeout');
        if (oListItemChoiceTimeout == null) {
            oListItemChoiceTimeout = "";
        }
        var oListItemSkill = oListItem.get_item('wsp_ucc_ivr_Skill');
        var oListItemName = oListItem.get_item('wsp_ucc_ivr_name');

        var keyExists = $.inArray(oListItemTitle, ivrData);
        if (keyExists == -1) {
            ivrData[oListItemTitle] = [];
        }
        ivrData[oListItemTitle]["Id"] = oListItemId;
        ivrData[oListItemTitle]["ContentTypeId"] = oListItemCT;
        ivrData[oListItemTitle]["ContentType"] = oListItemCTName;
        ivrData[oListItemTitle]["Action"] = oListItemAction;
        ivrData[oListItemTitle]["Parent"] = oListItemParent;
        ivrData[oListItemTitle]["ChoiceTimeout"] = oListItemChoiceTimeout;
        ivrData[oListItemTitle]["Skill"] = oListItemSkill;
        ivrData[oListItemTitle]["Name"] = oListItemName;
    }
    ProcessIVRData();
}

function retrieveAudioSkills() {
    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><And><Neq><FieldRef Name='ContentType' /><Value Type='Text'>ChatSkill</Value></Neq><Neq><FieldRef Name='ContentType' /><Value Type='Text'>ChatForwardSkill</Value></Neq></And></Where></Query><OrderBy><FieldRef Name='Title' /></OrderBy></View>");
    this.collAudioSkills = oList.getItems(camlQuery);

    clientContext.load(collAudioSkills);
    clientContext.executeQueryAsync(Function.createDelegate(this, this.onQueryRetrieveAudioSkillsSucceeded), Function.createDelegate(this, this.onQueryFailed));
}

function onQueryRetrieveAudioSkillsSucceeded(sender, args) {
    var listItemEnumerator = collAudioSkills.getEnumerator();
    while (listItemEnumerator.moveNext()) {
        var oListItem = listItemEnumerator.get_current();
        var oListItemId = oListItem.get_item('ID');
        var oListItemTitle = oListItem.get_item('Title');

        var obj = { Id: oListItemId, Title: oListItemTitle };
        skillsData.push(obj);
    }
    skillsData.sort(function (a, b) {
        return a.Title.localeCompare(b.Title);
    });
    initSkillDependency();
}

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

function ProcessIVRData() {
    ivrProcessedData = [];

    for (key in ivrData) {
        if (!ivrData.hasOwnProperty(key)) {
            continue;
        }

        var contentType = ivrData[key]["ContentType"];
        var action = ivrData[key]["Action"];
        var parentItem = ivrData[key]["Parent"];
        var parentValue = null;
        if (parentItem != null) {
            parentValue = parentItem.get_lookupValue();
        }
        var choicetimeout = ivrData[key]["ChoiceTimeout"];
        var skill = ivrData[key]["Skill"];
        var skillId = null;
        var skillValue = null;
        if (skill != null) {
            skillId = skill.get_lookupId();
            skillValue = skill.get_lookupValue();
        }
        var name = ivrData[key]["Name"];
        var nameId = null;
        var nameValue = null;
        if (name != null) {
            nameId = name.get_lookupId();
            nameValue = name.get_lookupValue();
        }

        ivrProcessedData[key] = [];
        ivrProcessedData[key]["contenttype"] = contentType;
        ivrProcessedData[key]["action"] = action;
        ivrProcessedData[key]["parent"] = parentValue;
        ivrProcessedData[key]["choicetimeout"] = choicetimeout;
        ivrProcessedData[key]["skillid"] = skillId;
        ivrProcessedData[key]["skill"] = skillValue;
        ivrProcessedData[key]["nameid"] = nameId;
        ivrProcessedData[key]["name"] = nameValue;
        ivrProcessedData[key]["childs"] = [];
    }

    for (key in ivrProcessedData) {
        if (!ivrProcessedData.hasOwnProperty(key)) {
            continue;
        }

        var parentValue = ivrProcessedData[key]["parent"];
        if (parentValue != null) {
            ivrProcessedData[parentValue]["childs"].push(key);
        }
    }

    // Get listform url:
    var listformUrl = "";
    var requestUrl = document.URL;
    var pos1 = requestUrl.toLowerCase().indexOf("/lists/ivrquestions/");
    if (pos1 != -1) {
        var listformUrl = requestUrl.substring(0, pos1);
        var layoutsLocation = "/_layouts/15/";
        if (spVersion == 14) {
            layoutsLocation = "/_layouts/";
        }
        listformUrl += layoutsLocation + "listform.aspx?PageType=4&RootFolder=*";
    }

    $(".ms-vb2").closest("tr").find("td:eq(1)").each(function () {
        var key = $(this).find("div a").html();
        var keyExists = key in ivrProcessedData;
        if (keyExists) {
            var contentType = ivrProcessedData[key]["contenttype"];
            var action = ivrProcessedData[key]["action"];
            var choicetimeout = ivrProcessedData[key]["choicetimeout"];
            var skillId = ivrProcessedData[key]["skillid"];
            var skill = ivrProcessedData[key]["skill"];
            var nameId = ivrProcessedData[key]["nameid"];
            var name = ivrProcessedData[key]["name"];
            var childs = ivrProcessedData[key]["childs"];

            if (contentType == "IVRQuestionItem") {
                var childsCount = childs.length;
                var showNotice = false;
                if (action == "" && childsCount == 0) {
                    showNotice = true;
                }
                else if (action == "Skill" && skill != "" && choicetimeout != "" && childsCount == 0) {
                    showNotice = true;
                }
                else if (action == "Voicemail" && choicetimeout != "" && childsCount == 0) {
                    showNotice = true;
                }

                if (showNotice) {
                    $(this).css("width", "150px");
                    var changeElement = $(this).find("div a:first");
                    var noChildMsg = resource_ivrquestions_errormsg_nochild;
                    var outputHtml = "<span class='noticeIVR' title='" + noChildMsg + "'>&nbsp;</span>";
                    $(changeElement).after(outputHtml);

                    // Fix SP 2010 notice
                    if (spVersion == 14) {
                        var linkElement = $(this).find("div:eq(1) a");
                        var parentElement = $(this).find("div:eq(1)");
                        $(linkElement).removeAttr("onclick");

                        $(linkElement).click("click", function (e) {
                            PopMenuFromChevron(e);
                            FixNoticeElement(this);
                            return false;
                        });

                        $(parentElement).click("click", function () {
                            FixNoticeElement(linkElement);
                            return false;
                        });
                    }
                }
            }

            var elementIndex = 3;
            if (spVersion == 14) {
                elementIndex = 2;
            }
            var actionElement = $(this).closest("tr").find("td:eq(" + elementIndex + ")");
            var actionValue = $(actionElement).html();
            var actionSubValue = "";
            if ((action == "Skill" || action == "Callback") && skill != null) {
                var listformUrlSkill = listformUrl + "&ListId={" + oListSkills.get_id().toString() + "}&ID=" + skillId;
                var skillHyperlink = "<a onclick=\"OpenPopUpPage('" + listformUrlSkill + "', RefreshPage); return false;\" href=\"" + listformUrlSkill + "\">" + skill + "</a>";
                actionSubValue = "<br>" + skillHyperlink;
            }
            if (action == "Prompt" && name != null) {
                var listformUrlName = listformUrl + "&ListId={" + oListPromptsConfig.get_id().toString() + "}&ID=" + nameId;
                var nameHyperlink = "<a onclick=\"OpenPopUpPage('" + listformUrlName + "', RefreshPage); return false;\" href=\"" + listformUrlName + "\">" + name + "</a>";
                actionSubValue = "<br>" + nameHyperlink;
            }
            $(actionElement).html("<b>" + actionValue + "</b>" + actionSubValue);
        }
    });
}

function FixNoticeElement(linkElement) {
    var targetElement = $(linkElement).closest("td");
    var removeElement = $(targetElement).find("div .noticeIVR");
    $(removeElement).remove();
    var changeElement = $(targetElement).find("div a:first");
    var noChildMsg = resource_ivrquestions_errormsg_nochild;
    var outputHtml = "<span class='noticeIVR' title='" + noChildMsg + "'>&nbsp;</span>";
    $(changeElement).after(outputHtml);
}

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

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

function ValidateSkill() {
    validateCheck3 = false;
    $("span#errorMsgSkill").remove();
    var action = $("select[title='Action']").find(":selected").val();
    if (action != null && action != "" && (action == "Skill" || action == "Callback" || (action == "Voicemail" && currentTitle != "Message Busy"))) {
        var testValue = $("select[title='Skill']").val();
        $("input[id*='SaveItem']").prop("disabled", true);
        $("a[id='Ribbon.ListForm.Edit.Commit.Publish-Large']").prop("class", "ms-cui-ctl-large ms-cui-disabled");
        $("select[title='Skill']").css("border", "1px solid red");
        if (testValue != null && testValue != "" && testValue != 0) {
            validateCheck3 = true;
            if (validateCheck1 && validateCheck2 && validateCheck3 && validateCheck4) {
                $("input[id*='SaveItem']").prop("disabled", false);
                $("a[id='Ribbon.ListForm.Edit.Commit.Publish-Large']").prop("class", "ms-cui-ctl-large");
            }
            $("select[title='Skill']").css("border", "1px solid green");
            $("select[title='Skill']").after("<span id='errorMsgSkill' style='color:green;'>&nbsp;&nbsp;&nbsp;OK</span>");
        }
        else {
            var noSelectMsg = resource_ivrquestions_errormsg_noselect;
            $("select[title='Skill']").after("<span id='errorMsgSkill' style='color:red;'>&nbsp;&nbsp;&nbsp;" + noSelectMsg + "</span>");
        }
    }
    else {
        validateCheck3 = true;
        if (validateCheck1 && validateCheck2 && validateCheck3 && validateCheck4) {
            $("input[id*='SaveItem']").prop("disabled", false);
            $("a[id='Ribbon.ListForm.Edit.Commit.Publish-Large']").prop("class", "ms-cui-ctl-large");
        }
        $("select[title='Skill']").css("border", "");
    }
}

function ValidateName() {
    validateCheck4 = false;
    var action = $("select[title='Action']").find(":selected").val();
    if (action != null && action != "" && action == "Prompt") {
        var testValue = $("select[title='Name']").val();
        $("input[id*='SaveItem']").prop("disabled", true);
        $("a[id='Ribbon.ListForm.Edit.Commit.Publish-Large']").prop("class", "ms-cui-ctl-large ms-cui-disabled");
        $("select[title='Name']").css("border", "1px solid red");
        $("span#errorMsgName").remove();
        if (testValue != null && testValue != "" && testValue != 0) {
            validateCheck4 = true;
            if (validateCheck1 && validateCheck2 && validateCheck3 && validateCheck4) {
                $("input[id*='SaveItem']").prop("disabled", false);
                $("a[id='Ribbon.ListForm.Edit.Commit.Publish-Large']").prop("class", "ms-cui-ctl-large");
            }
            $("select[title='Name']").css("border", "1px solid green");
            $("select[title='Name']").after("<span id='errorMsgName' style='color:green;'>&nbsp;&nbsp;&nbsp;OK</span>");
        }
        else {
            var noSelectMsg = resource_ivrquestions_errormsg_noselect;
            $("select[title='Name']").after("<span id='errorMsgName' style='color:red;'>&nbsp;&nbsp;&nbsp;" + noSelectMsg + "</span>");
        }
    }
    else {
        validateCheck4 = true;
        if (validateCheck1 && validateCheck2 && validateCheck3 && validateCheck4) {
            $("input[id*='SaveItem']").prop("disabled", false);
            $("a[id='Ribbon.ListForm.Edit.Commit.Publish-Large']").prop("class", "ms-cui-ctl-large");
        }
        $("select[title='Name']").css("border", "");
    }
}

function ValidateQuestion() {
    validateCheck5 = false;
    var testValue = $("textarea[title='Question']").val();
    $("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 != null && testValue != "") {
        validateCheck5 = true;
        if (validateCheck5 || validateCheck6) {
            $("input[id*='SaveItem']").prop("disabled", false);
            $("a[id='Ribbon.ListForm.Edit.Commit.Publish-Large']").prop("class", "ms-cui-ctl-large");
        }
    }
    else {
        if (validateCheck5 || validateCheck6) {
            $("input[id*='SaveItem']").prop("disabled", false);
            $("a[id='Ribbon.ListForm.Edit.Commit.Publish-Large']").prop("class", "ms-cui-ctl-large");
        }
    }
}

function ValidateAudioQuestion() {
    validateCheck6 = false;
    var testValue = $("select[title='AudioQuestion']").val();
    $("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 != null && testValue != "" && testValue != 0) {
        validateCheck6 = true;
        if (validateCheck5 || validateCheck6) {
            $("input[id*='SaveItem']").prop("disabled", false);
            $("a[id='Ribbon.ListForm.Edit.Commit.Publish-Large']").prop("class", "ms-cui-ctl-large");
        }
    }
    else {
        if (validateCheck5 || validateCheck6) {
            $("input[id*='SaveItem']").prop("disabled", false);
            $("a[id='Ribbon.ListForm.Edit.Commit.Publish-Large']").prop("class", "ms-cui-ctl-large");
        }
    }
}

function ActionHandler() {
    $("select[title*='Choice']").closest("tr").show();
    $("input[title='Choice Timeout']").closest("tr").hide();
    $("input[title='Answer']").closest("tr").hide();
    $("select[title='AudioAnswer']").closest("tr").hide();
    $("select[title='Skill']").closest("tr").hide();
    $("select[title='Name']").closest("tr").hide();

    // Hide Choice
    if ((currentContentType == "IVRQuestionItem" || currentContentType == "IVRHolidayQuestionItem" || currentContentType == "IVRCustomSystemItem") && currentTitle.toLowerCase() == "welcome message") {
        $("select[title*='Choice']").closest("tr").hide();
    }

    var description = resource_ivrquestions_description_question;
    var order = 200;
    var workflow = "WelcomeFlow";

    currentAction = $("select[title='Action']").find(":selected").val();
    if (currentAction == "Callback" || currentAction == "QueuedCallback") {
        if (currentAction == "Callback") {
            $("select[title='Skill']").closest("tr").show();
        }

        $("input[title='Choice Timeout']").val("");
        $("select[title='Name']").val("");

        if ((currentContentType == "IVRCustomSystemItem" && (currentTitle == "Welcome Message" || currentTitle == "Message Closed")) || currentContentType != "IVRCustomSystemItem") {
            $("input[title='Answer']").closest("tr").show();
            $("select[title='AudioAnswer']").closest("tr").show();
        }
        else {
            $("input[title='Answer']").val("");
            $("select[title='AudioAnswer']").val("");
        }
    }
    else if (currentAction == "Prompt") {
        $("select[title='Name']").closest("tr").show();

        $("input[title='Choice Timeout']").val("");
        $("select[title='Skill']").val("");

        if ((currentContentType == "IVRCustomSystemItem" && (currentTitle == "Welcome Message" || currentTitle == "Message Closed")) || currentContentType != "IVRCustomSystemItem") {
            $("input[title='Answer']").closest("tr").show();
            $("select[title='AudioAnswer']").closest("tr").show();
        }
        else {
            $("input[title='Answer']").val("");
            $("select[title='AudioAnswer']").val("");
        }

        description = resource_ivrquestions_description_prompt;
        order = 300;
        workflow = "PromptFlow";
    }
    else if (currentAction == "Skill") {
        if ((currentContentType == "IVRCustomSystemItem" && currentTitle != "Message Busy") || currentContentType != "IVRCustomSystemItem") {
            $("input[title='Choice Timeout']").closest("tr").show();
        }

        $("select[title='Skill']").closest("tr").show();

        if ((currentContentType == "IVRCustomSystemItem" && (currentTitle == "Welcome Message" || currentTitle == "Message Closed")) || currentContentType != "IVRCustomSystemItem") {
            $("input[title='Answer']").closest("tr").show();
            $("select[title='AudioAnswer']").closest("tr").show();
        }
        else {
            $("input[title='Answer']").val("");
            $("select[title='AudioAnswer']").val("");
        }

        $("select[title='Name']").val("");
    }
    else if (currentAction == "Voicemail") {
        if ((currentContentType == "IVRCustomSystemItem" && currentTitle != "Message Busy") || currentContentType != "IVRCustomSystemItem") {
            $("input[title='Choice Timeout']").closest("tr").show();
        }

        $("select[title='Skill']").closest("tr").show();
        $("select[title='Name']").val("");

        if ((currentContentType == "IVRCustomSystemItem" && (currentTitle == "Welcome Message" || currentTitle == "Message Closed")) || currentContentType != "IVRCustomSystemItem") {
            $("input[title='Answer']").closest("tr").show();
            $("select[title='AudioAnswer']").closest("tr").show();
        }
        else {
            $("input[title='Answer']").val("");
            $("select[title='AudioAnswer']").val("");
        }
    }
    else if (currentAction == "Disconnect") {
        if ((currentContentType == "IVRCustomSystemItem" && (currentTitle == "Welcome Message" || currentTitle == "Message Closed")) || currentContentType != "IVRCustomSystemItem") {
            $("input[title='Answer']").closest("tr").show();
            $("select[title='AudioAnswer']").closest("tr").show();
        }
        else {
            $("input[title='Answer']").val("");
            $("select[title='AudioAnswer']").val("");
        }
    }
    else if (currentAction == "Previous") {
        if ((currentContentType == "IVRCustomSystemItem" && (currentTitle == "Welcome Message" || currentTitle == "Message Closed")) || currentContentType != "IVRCustomSystemItem") {
            $("input[title='Answer']").closest("tr").show();
            $("select[title='AudioAnswer']").closest("tr").show();
        }
        else {
            $("input[title='Answer']").val("");
            $("select[title='AudioAnswer']").val("");
        }
    }
    else if (currentAction == "") {
        $("select[title='Skill']").val("");
        $("select[title='Name']").val("");
        /*  $("select[title*='Choice']").closest("tr").hide(); */
        if (currentContentType == "IVRQuestionItem") {
            $("select[title*='Choice']").closest("tr").show();
        }
        else {
            $("select[title*='Choice']").closest("tr").hide();
        }
    }
    else {
        $("select[title='Skill']").val("");
        $("select[title='Name']").val("");
        /* $("select[title*='Choice']").closest("tr").hide(); */
        if (currentContentType == "IVRQuestionItem") {
            $("select[title*='Choice']").closest("tr").show();
        }
        else {
            $("select[title*='Choice']").closest("tr").hide();
        }
    }

    if (currentContentType == "IVRQuestionItem") {
        $("textarea[title='Description']").val(description);
        $("input[title='Order']").val(order);
        $("select[title='Workflow']").val(workflow);
    }

    ValidateSkill();
    ValidateName();
}

function ChoiceTimeoutHandler() {
    var checkSkill = $("select[title='Skill']").find(":selected").val();
    var checkAction = $("select[title='Action']").find(":selected").val();
    if (checkSkill != 0 || checkAction == "Voicemail") {
        $("input[title='Choice Timeout']").prop("disabled", false);
    }
    else {
        $("input[title='Choice Timeout']").val("");
        $("input[title='Choice Timeout']").prop("disabled", true);
    }
    ValidateChoiceTimeout();
}

function initSkillDependency() {
    var initValue = $("textarea[title='Skill Dependencies']").val();
    if (initValue != "") {
        initValue = SortSkillDependency(initValue, true);
        var dependencySplit = initValue.split(";");
        for (j = 0; j < dependencySplit.length; j++) {
            var tmpSplit = dependencySplit[j].split(",");
            var skillId1 = tmpSplit[0];
            var skillId2 = tmpSplit[1];
            $("input[title='Enable Skill Dependency']").closest('tr').after("<tr class='skillDependency'><td class='ms-formlabel' noWrap='' vAlign='top'>&nbsp;</td><td class='ms-formbody' vAlign='top'>" + GenerateFormElements(skillId1, skillId2) + "</td></tr>");
        }
        $('.BtnUpdateSkillDependency').click(function (e) {
            e.preventDefault();
            UpdateSkillDependency();
        });
        $('.BtnRemoveSkillDependency').click(function (e) {
            e.preventDefault();
            RemoveSkillDependency($(this));
        });
    }

    if ($("input[title='Enable Skill Dependency']").prop('checked')) {
        var btnAdd = "<a href='#' id='BtnAddSkillDependency'>Add</a>";
        $("input[title='Enable Skill Dependency']").closest('tr').after("<tr class='addSkillDependency'><td class='ms-formlabel' noWrap='' vAlign='top'>&nbsp;</td><td class='ms-formbody' vAlign='top'>" + btnAdd + "</td></tr>");
        $('#BtnAddSkillDependency').click(function (e) {
            e.preventDefault();
            AddSkillDependency();
        });
    }
}

function SortSkillDependency(initValue, reverse) {
    if (initValue != "") {

        var dependencySplit = initValue.split(";");
        for (j = 0; j < dependencySplit.length; j++) {
            var tmpSplit = dependencySplit[j].split(",");
            var skillId1 = tmpSplit[0];
            var skillId2 = tmpSplit[1];
            var skillObj1 = $.grep(skillsData, function (s) { return s.Id == skillId1; });
            var skillObj2 = $.grep(skillsData, function (s) { return s.Id == skillId2; });
            tmpSplit[0] = skillObj1[0].Title;
            tmpSplit[1] = skillObj2[0].Title;
            dependencySplit[j] = tmpSplit.join(",");
        }

        dependencySplit.sort();
        if (reverse == true) {
            dependencySplit.reverse();
        }

        var returnValue = "";
        for (k = 0; k < dependencySplit.length; k++) {
            var tmpSplit = dependencySplit[k].split(",");
            var skillValue1 = tmpSplit[0];
            var skillValue2 = tmpSplit[1];
            var skillObj1 = $.grep(skillsData, function (s) { return s.Title == skillValue1; });
            var skillObj2 = $.grep(skillsData, function (s) { return s.Title == skillValue2; });
            tmpSplit[0] = skillObj1[0].Id
            tmpSplit[1] = skillObj2[0].Id
            dependencySplit[k] = tmpSplit.join(",");
            returnValue += dependencySplit[k] + ";";
        }

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

        return returnValue;
    }
}

function GenerateFormElements(skillId1, skillId2) {
    // Skill1
    var skills1 = "<select name='dependencySkill1'>";
    skills1 += "<option value=''>Select skill...</option>";
    for (key in skillsData) {
        var selected = "";
        if (skillId1 != "" && skillId1 == skillsData[key].Id) {
            selected = "selected";
        }
        skills1 += "<option value='" + skillsData[key].Id + "' " + selected + ">" + skillsData[key].Title + "</option>";
    }
    skills1 += "</select>";

    // Skill2
    var skills2 = "<select name='dependencySkill2'>";
    skills2 += "<option value=''>Select skill...</option>";
    for (key in skillsData) {
        var selected = "";
        if (skillId2 != "" && skillId2 == skillsData[key].Id) {
            selected = "selected";
        }
        skills2 += "<option value='" + skillsData[key].Id + "' " + selected + ">" + skillsData[key].Title + "</option>";
    }
    skills2 += "</select>";

    var btnUpdate = "<a href='#' class='BtnUpdateSkillDependency'>Update</a>";
    var btnRemove = "<a href='#' class='BtnRemoveSkillDependency'>Remove</a>";

    return skills1 + "&#160;" + skills2 + " " + btnUpdate + " " + btnRemove;
}

function AddSkillDependency() {
    $("tr#errorMsgContainer").remove();
    $(".addSkillDependency").after("<tr class='skillDependency'><td class='ms-formlabel' noWrap='' vAlign='top'>&nbsp;</td><td class='ms-formbody' vAlign='top'>" + GenerateFormElements("", "") + "</td></tr>");
    $('.BtnUpdateSkillDependency').click(function (e) {
        e.preventDefault();
        UpdateSkillDependency();
    });
    $('.BtnRemoveSkillDependency').click(function (e) {
        e.preventDefault();
        RemoveSkillDependency($(this));
    });
}

function UpdateSkillDependency() {
    $("tr#errorMsgContainer").remove();
    var insertValue = "";
    var validValue = true;
    var emptyValue = false;
    $(".skillDependency").each(function (index) {
        var skill1Value = $(this).find("select[name=dependencySkill1]").val();
        var skill2Value = $(this).find("select[name=dependencySkill2]").val();
        if (skill1Value == "" || skill2Value == "") {
            validValue = false;
            emptyValue = true;
        }
        else {
            insertValue += skill1Value + "," + skill2Value + ";";
        }
    });
    if (insertValue != "") {
        insertValue = insertValue.substring(0, insertValue.length - 1);
        insertValue = SortSkillDependency(insertValue, false);
    }

    if (validValue == true) {
        $("textarea[title='Skill Dependencies']").val(insertValue);
    }
    else {
        if (emptyValue == true) {
            $(".addSkillDependency").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;'>Empty skill</span></td></tr>");
        }
    }
}

function RemoveSkillDependency(element) {
    $(element).closest("tr").remove();
    UpdateSkillDependency();
}

// Ribbon enable check
function EnableRibbonCommands(command) {
    var result = false;
    if (command != "") {
        if (command == "Callback") {
            if (typeof this.callbackEnableCheck == "undefined" || this.callbackEnableCheck == false) {
                retrieveCallbackUsed();
                this.callbackEnableCheck = true;
            }
            if (typeof this.callbackEnable != "undefined" && this.callbackEnable) {
                result = true;
            }
        }
    }

    return result;
}

// Ribbon callback used
function retrieveCallbackUsed() {
    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><Eq><FieldRef Name='wsp_ucc_ivr_Workflow' /><Value Type='Text'>Callback</Value></Eq></Where></Query><RowLimit>7</RowLimit></View>");

    this.collListItemsCallback = oList.getItems(camlQuery);
    clientContext.load(collListItemsCallback);
    clientContext.executeQueryAsync(Function.createDelegate(this, this.onQueryRetrieveCallbackUsedSucceeded), Function.createDelegate(this, this.onQueryFailed));
}

function onQueryRetrieveCallbackUsedSucceeded(sender, args) {
    var itemCount = collListItemsCallback.get_count();
    if (itemCount < 7) {
        this.callbackEnable = true;
        RefreshCommandUI();
    }
}

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];
        }
    }
}