// routing_custom.js
var currentId = "";
var usedMatchCombos = [];
var endpointList = [];
var routingData = [];
var skillsList = [];
var currentContentType = "";
var spVersion = "";
var viewName = "";

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

    if (customFormMode == "add" || customFormMode == "edit") {

        // Init fields
        $("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']").closest("tr").hide();
        $("select[title='ParentQuestion']").closest("tr").hide();
        $("select[title='Name']").closest("tr").hide();

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

        // Determine ContentType
        var matchEndpointCheck = $("input[title*='ExactMatch']").val();
        if (typeof matchEndpointCheck != "undefined") {
            currentContentType = "UCCRouting";
        }
        else {
            currentContentType = "InboundRouting";
        }

        if (currentContentType == "UCCRouting") {
            ExecuteOrDelayUntilScriptLoaded(function () { retrieveEndpoints(); }, "sp.js");
        }

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

        // Action
        ActionHandler();
        $("select[title*='Action']").change(function () {
            ActionHandler();
        });

        // Skill change
        $("select[title='Skill']").bind("change", function () {
            ValidateValue("Skill", $("select[title='Skill']").val());
        });

        // ParentQuestion change
        $("select[title='ParentQuestion']").bind("change", function () {
            ValidateValue("ParentQuestion", $("select[title='ParentQuestion']").val());
        });

        // Prompt change
        $("select[title='Name']").bind("change", function () {
            ValidateValue("Name", $("select[title='Name']").val());
        });

        // Match To change
        $("input[title*='Match To']").bind("keyup", function () {
            ValidateMatchCombo();
        });
        $("input[title*='Match To']").bind("focusout", function () {
            ValidateMatchCombo();
        });
        $("input[title*='Match To']").bind("mousedown", function () {
            ValidateMatchCombo();
        });

        // MatchCombo
        currentId = getParameterByName("ID");
        ExecuteOrDelayUntilScriptLoaded(function () { retrieveUsedMatchCombos(); }, "sp.js");
        ValidateMatchCombo();
        $("input[title*='Match From']").bind("keyup", function () {
            ValidateMatchCombo();
        });
        $("input[title*='Match From']").bind("focusout", function () {
            ValidateMatchCombo();
        });
        $("input[title*='Match From']").bind("mousedown", function () {
            ValidateMatchCombo();
        });
    }
    else if (customFormMode == "listview") {
        // Change new item link
        ChangeRoutingNewItemLink();

        // Action info
        var requestUrl = document.URL;
        var pos0 = requestUrl.toLowerCase().indexOf("/lists/routing/");
        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));
            }
        }
        ExecuteOrDelayUntilScriptLoaded(function () { retrieveRouting() }, "sp.js");
    }
});

function ChangeRoutingNewItemLink() {
    // Determine if Routing list
    var requestUrl = document.URL;
    var pos0 = requestUrl.toLowerCase().indexOf("/lists/routing/");
    if (pos0 != -1) {
        // Determine view name
        var pos1 = requestUrl.lastIndexOf("/");
        var pos2 = requestUrl.lastIndexOf(".");
        if (pos1 != -1 && pos2 != -1) {
            var pageViewName = (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 = "0x0100a9c88ce0264e43e987da092333b4307a";
                        var tmpViewName = pageViewName.toLowerCase();
                        if (tmpViewName == "inboundroutingview") {
                            contentTypeId = "0x010038f813f3f98443ee92841ad149cc28cb";
                        }

                        // Determine new link
                        var newLink = requestUrl;
                        var pos5 = newLink.indexOf("?");
                        if (pos5 != -1) {
                            newLink = newLink.substring(0, pos5);
                        }
                        newLink = newLink.replace(pageViewName, "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 initEndpointsSelect() {
    $("input[title*='MatchEndpoint']").hide();
    $("input[title*='MatchEndpoint']").after(GenerateFormCheckboxElements());

    $("div#epList + br").hide();

    $("input[name='epcheckbox']").click(function () {
        var checkboxValue = $(this).val();
        var checkboxChecked = $(this).is(':checked');

        if (checkboxValue == "All") {
            if (checkboxChecked) {
                $("#epList").css("display", "none");
            }
            else {
                $("#epList").css("display", "");
            }
            $("input[name='epcheckbox']").each(function () {
                if ($(this).val() != "All") {
                    $(this).prop("checked", "");
                }
            });
        }
        else if (checkboxValue == "SelectAll") {
            $("input[name='epcheckbox']").each(function () {
                if ($(this).val() != "All") {
                    $(this).prop("checked", checkboxChecked);
                }
            });
        }

        SaveCheckboxValue();
    });
}

function GenerateFormCheckboxElements() {
    var outputHtml = "";

    if (endpointList != null && endpointList.length > 0) {
        var checkCount = 0;
        var savedValues = $("input[title*='MatchEndpoint']").val();

        $.each(endpointList, function (index, value) {
            var checked = "";
            var valueExists = savedValues.indexOf(value.Id);
            if (valueExists != -1 || savedValues.indexOf("SelectAll") != -1) {
                checked = " checked";
                checkCount++;
            }
            outputHtml += "<input type='checkbox' name='epcheckbox' value='" + value.Id + "'" + checked + ">&#160;&#160;&#160;" + value.Title + "<br>";
        });

        var allChecked = "";
        var selectAllChecked = "";
        var display = "";
        if (savedValues == "All") {
            allChecked = " checked";
            display = "none";
        }
        else {
            if (checkCount == endpointList.length) {
                selectAllChecked = " checked";
            }
        }

        outputHtml = "<input type='checkbox' name='epcheckbox' value='All'" + allChecked + ">&#160;&#160;&#160;All (Routing Enabled Endpoints)<div id='epList' style='display:" + display + ";'><br><input type='checkbox' name='epcheckbox' value='SelectAll'" + selectAllChecked + "><br>" + outputHtml;
        outputHtml = outputHtml.substring(0, outputHtml.length - 4);
        outputHtml += "</div>";
    }
    else {
        $("input[title*='MatchEndpoint']").val("");
        outputHtml = "No endpoints found";
    }

    return outputHtml;
}

function SaveCheckboxValue() {
    var saveValue = "";
    var checkedCheck = true;

    $("input[name='epcheckbox']").each(function () {
        var checkboxValue = $(this).val();
        var checkboxChecked = $(this).is(':checked');
        if (checkboxChecked && checkboxValue != "All" && checkboxValue != "SelectAll") {
            saveValue += checkboxValue + ";";
        }
        else if (!checkboxChecked && checkboxValue != "All" && checkboxValue != "SelectAll") {
            checkedCheck = false;
        }
    });

    var allChecked = $("input[name='epcheckbox'][value=All]").is(':checked');
    if (allChecked) {
        saveValue = "All";
    }
    else {
        if (checkedCheck) {
            $("input[name='epcheckbox'][value=SelectAll]").prop("checked", true);
        }
        else {
            $("input[name='epcheckbox'][value=SelectAll]").prop("checked", false);
        }
    }

    if (saveValue != "All") {
        saveValue = saveValue.substring(0, saveValue.length - 1);
    }
    $("input[title*='MatchEndpoint']").val(saveValue);
}

function ValidateValue(checkElement, checkValue) {
    if (checkElement != null && checkValue != null && checkElement != "" && checkValue != "") {
        $("select[title='" + checkElement + "']").css("border", "1px solid red");
        $("span#errorMsg").remove();
        var noSelectMsg = resource_routing_errormsg_noselect;
        $("select[title='" + checkElement + "']").after("<span id='errorMsg' style='color:red;'>&nbsp;&nbsp;&nbsp;" + noSelectMsg + "</span>");
        $("input[id*='SaveItem']").prop("disabled", true);
        $("a[id='Ribbon.ListForm.Edit.Commit.Publish-Large']").prop("class", "ms-cui-ctl-large ms-cui-disabled");
        if (checkValue != "0") {
            $("input[id*='SaveItem']").prop("disabled", false);
            $("select[title='" + checkElement + "']").css("border", "1px solid green");
            $("a[id='Ribbon.ListForm.Edit.Commit.Publish-Large']").prop("class", "ms-cui-ctl-large");
            $("span#errorMsg").remove();
            $("select[title='" + checkElement + "']").after("<span id='errorMsg' style='color:green;'>&nbsp;&nbsp;&nbsp;OK</span>");
        }
    }
    else {
        $("input[id*='SaveItem']").prop("disabled", false);
        $("a[id='Ribbon.ListForm.Edit.Commit.Publish-Large']").prop("class", "ms-cui-ctl-large");
    }
}

function ValidateMatchCombo() {
    var testValue1 = $("input[title*='Match From']").val();
    if (testValue1 == "") {
        testValue1 = null;
    }
    var testValue2 = $("input[title*='Match To']").val();
    if (testValue2 == "") {
        testValue2 = null;
    }

    $("input[title*='Match From']").css("border", "1px solid red");
    $("input[title*='Match To']").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");
    $("tr#errorMsg").remove();
    var testValueCombo = testValue1 + ";" + testValue2;
    if (testValueCombo != null && testValueCombo != "") {
        if ($.inArray(testValueCombo, usedMatchCombos) == -1) {
            $("input[id*='SaveItem']").prop("disabled", false);
            $("input[title*='Match From']").css("border", "1px solid green");
            $("input[title*='Match To']").css("border", "1px solid green");
            $("a[id='Ribbon.ListForm.Edit.Commit.Publish-Large']").prop("class", "ms-cui-ctl-large");
        }
        else {
            var inUseMsg = resource_routing_errormsg_inuse;
            $("input[title*='Match From']").closest("tr").after("<tr id='errorMsg'><td nowrap='true' valign='top' width='113px' class='ms-formlabel'>&nbsp;</td><td valign='top' width='350px' class='ms-formbody'><span style='color:red;'>" + inUseMsg + "</span></td>");
        }
    }
    else {
        $("input[id*='SaveItem']").prop("disabled", false);
        $("a[id='Ribbon.ListForm.Edit.Commit.Publish-Large']").prop("class", "ms-cui-ctl-large");
    }
}

function ActionHandler() {
    $("select[title='Skill']").closest("tr").hide();
    $("select[title='ParentQuestion']").closest("tr").hide();
    $("select[title='Name']").closest("tr").hide();


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

        $("select[title='ParentQuestion']").val("");
        $("select[title='Name']").val("");
        ValidateValue("Skill", $("select[title='Skill']").val());
        SkillHandler();
    }
    else if (currentAction == "Forward") {
        $("select[title='Skill']").closest("tr").show();
        $("select[title='ParentQuestion']").val("");
        $("select[title='Name']").val("");
        ValidateValue("Skill", $("select[title='Skill']").val());
        SkillHandler();
    }
    else if (currentAction == "Prompt") {
        $("select[title='Name']").closest("tr").show();
        $("select[title='Skill']").val("");
        $("select[title='ParentQuestion']").val("");
        ValidateValue("Name", $("select[title='Name']").val())
    }
    else if (currentAction == "Question") {
        $("select[title='ParentQuestion']").closest("tr").show();
        $("select[title='Skill']").val("");
        $("select[title='Name']").val("");
        ValidateValue("ParentQuestion", $("select[title='ParentQuestion']").val());
    }
    else if (currentAction == "Skill") {
        $("select[title='Skill']").closest("tr").show();
        $("select[title='ParentQuestion']").val("");
        $("select[title='Name']").val("");
        ValidateValue("Skill", $("select[title='Skill']").val());
        SkillHandler();
    }
    else if (currentAction == "Voicemail" || currentAction == "Disconnect" || currentAction == "") {
        $("select[title='Skill']").val("");
        $("select[title='ParentQuestion']").val("");
        $("select[title='Name']").val("");
        ValidateValue(null, null);
    }
}

function SkillHandler() {

    // Reset Skill dropdown
    $("select[title='Skill'] span").each(function () {
        var replacement = $(this).find("option").show();
        $(this).replaceWith(replacement);
    });

    currentAction = $("select[title*='Action']").find(":selected").val();
    $("select[title='Skill'] option").each(function () {
        var skillName = $(this).text();
		var skillId = $(this).val(); // Retrieve the ID value of the skill list
        var result = null;
        if (currentAction != "Forward") {
            result = $.grep(skillsList, function (s) { return s.Title == skillName && s.ContentType != "ForwardSkill"; });
        }
        else {
            result = $.grep(skillsList, function (s) { return s.Title == skillName && s.ContentType == "ForwardSkill"; });
        }

        if (result != null && result.length == 0 && skillId != 0) { // Check if a skill was (not) selected by evaluating the ID. 0 means no selection
            $(this).wrap("<span>").hide();
        }
    });
}

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

    clientContext.load(collListItemsSkills);
    clientContext.load(collListContentTypesSkills);
    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 oListItemId = oListItem.get_item("ID");
        var oListItemTitle = oListItem.get_item('Title');
        var oListItemCT = oListItem.get_item("ContentTypeId").toString();
        var oListItemCTName = "";
        var ct_enumerator = collListContentTypesSkills.getEnumerator();
        while (ct_enumerator.moveNext()) {
            var ct = ct_enumerator.get_current();
            if (ct.get_id().toString() == oListItemCT) {
                oListItemCTName = ct.get_name();
            }
        }

        var obj = { Id: oListItemId, Title: oListItemTitle, ContentType: oListItemCTName };
        skillsList.push(obj);
    }

    SkillHandler();
}

// 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><Neq><FieldRef Name='wsp_ucc_ivr_Workflow' /><Value Type='Text'>WelcomeFlow</Value></Neq></Where><OrderBy><FieldRef Name='Title' /></OrderBy></Query></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) {
                $(this).remove();
            }
        });
    }
}

// Routing used match combos Query
function retrieveUsedMatchCombos() {
    var clientContext = SP.ClientContext.get_current();
    var oList = clientContext.get_web().get_lists().getByTitle('Routing');

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

    clientContext.load(collUsedMatchComboItems);
    clientContext.executeQueryAsync(Function.createDelegate(this, this.onQueryRetrieveUsedMatchCombosSucceeded), Function.createDelegate(this, this.onQueryFailed));
}

function onQueryRetrieveUsedMatchCombosSucceeded(sender, args) {
    var listItemEnumerator = collUsedMatchComboItems.getEnumerator();
    while (listItemEnumerator.moveNext()) {
        var oListItem = listItemEnumerator.get_current();
        var oListItemId = oListItem.get_item('ID');
        var oListItemTitle = oListItem.get_item('Title');
        var oListItemMatchFrom = oListItem.get_item('wsp_ucc_routing_match_from');
        var oListItemMatchTo = oListItem.get_item('wsp_ucc_routing_match_to');

        var matchCombo = oListItemMatchFrom + ";" + oListItemMatchTo;
        if (oListItemId != currentId) {
            usedMatchCombos.push(matchCombo);
        }
    }
    ValidateMatchCombo();
}

// Endpoints Values Query
function retrieveEndpoints() {
    var clientContext = SP.ClientContext.get_current();
    this.oListEndpoints = clientContext.get_web().get_lists().getByTitle('Endpoints');

    var camlQuery = new SP.CamlQuery();
    camlQuery.set_viewXml("<View><Query><Where><And><Or><Eq><FieldRef Name='ContentType' /><Value Type='Text'>ModalityEndpoint</Value></Eq><Eq><FieldRef Name='ContentType' /><Value Type='Text'>MainEndpoint</Value></Eq></Or><Eq><FieldRef Name='wsp_ucc_endpoints_enablerouting' /><Value Type='Integer'>1</Value></Eq></And></Where><OrderBy><FieldRef Name='Title' /></OrderBy></Query></View>");
    this.collListItemsEndpoints = oListEndpoints.getItems(camlQuery);

    clientContext.load(collListItemsEndpoints);
    clientContext.load(oListEndpoints);
    clientContext.executeQueryAsync(Function.createDelegate(this, this.onQueryRetrieveEndpointsSucceeded), Function.createDelegate(this, this.onQueryFailed));
}

function onQueryRetrieveEndpointsSucceeded(sender, args) {
    var listItemEnumerator = collListItemsEndpoints.getEnumerator();
    while (listItemEnumerator.moveNext()) {
        var oListItem = listItemEnumerator.get_current();
        var oListItemId = oListItem.get_item("ID");
        var oListItemTitle = oListItem.get_item("Title");
        var oListItemModality = oListItem.get_item("wsp_ucc_modality");

        var obj = { Id: oListItemId, Title: oListItemTitle, Modality: oListItemModality };
        endpointList.push(obj);
    }

    if (viewName.toLowerCase() == "uccroutingview") {
        DisplayRoutingData();
    }
    else {
        initEndpointsSelect();
    }
}

// Routing data Query
function retrieveRouting() {
    routingData = [];
    var clientContext = SP.ClientContext.get_current();
    var oList = clientContext.get_web().get_lists().getByTitle("Routing");
    this.oListSkills = clientContext.get_web().get_lists().getByTitle("Skills");
    this.oListIVRQuestions = clientContext.get_web().get_lists().getByTitle("IVRQuestions");
    this.oListPromptsConfig = clientContext.get_web().get_lists().getByTitle("PromptsConfig");

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

    clientContext.load(collListItemsRouting);
    clientContext.load(collListContentTypes);
    clientContext.load(oListSkills);
    clientContext.load(oListIVRQuestions);
    clientContext.load(oListPromptsConfig);
    clientContext.executeQueryAsync(Function.createDelegate(this, this.onQueryRetrieveRoutingSucceeded), Function.createDelegate(this, this.onQueryFailed));
}

function onQueryRetrieveRoutingSucceeded(sender, args) {
    var listItemEnumerator = collListItemsRouting.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_routing_action');
        if (oListItemAction == null) {
            oListItemAction = "";
        }
        var oListItemSkill = oListItem.get_item('wsp_ucc_routing_skill');
        var oListItemQuestion = oListItem.get_item('wsp_ucc_routing_parentquestion');
        var oListItemName = oListItem.get_item('wsp_ucc_routing_name');

        var keyExists = $.inArray(oListItemId, routingData);
        if (keyExists == -1) {
            routingData[oListItemId] = [];
        }
        routingData[oListItemId]["Id"] = oListItemId;
        routingData[oListItemId]["Title"] = oListItemTitle;
        routingData[oListItemId]["ContentTypeId"] = oListItemCT;
        routingData[oListItemId]["ContentType"] = oListItemCTName;
        routingData[oListItemId]["Action"] = oListItemAction;
        routingData[oListItemId]["Skill"] = null;
        if (oListItemSkill != null) {
            routingData[oListItemId]["SkillId"] = oListItemSkill.get_lookupId();
            routingData[oListItemId]["Skill"] = oListItemSkill.get_lookupValue();
        }
        routingData[oListItemId]["Question"] = null;
        if (oListItemQuestion != null) {
            routingData[oListItemId]["QuestionId"] = oListItemQuestion.get_lookupId();
            routingData[oListItemId]["Question"] = oListItemQuestion.get_lookupValue();
        }
        routingData[oListItemId]["Name"] = null;
        if (oListItemName != null) {
            routingData[oListItemId]["NameId"] = oListItemName.get_lookupId();
            routingData[oListItemId]["Name"] = oListItemName.get_lookupValue();
        }
    }

    if (viewName.toLowerCase() == "uccroutingview") {
        retrieveEndpoints();
    }
    else {
        DisplayRoutingData();
    }
}

function DisplayRoutingData() {

    // Get listform url:
    var listformUrl = "";
    var requestUrl = document.URL;
    var pos1 = requestUrl.toLowerCase().indexOf("/lists/routing/");
    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").attr("Id");
        var keyExists = key in routingData;
        if (keyExists) {
            var action = routingData[key]["Action"];
            var skillId = routingData[key]["SkillId"];
            var skill = routingData[key]["Skill"];
            var questionId = routingData[key]["QuestionId"];
            var question = routingData[key]["Question"];
            var nameId = routingData[key]["NameId"];
            var name = routingData[key]["Name"];

            var elementIndex = 5;
            if (spVersion == 14) {
                elementIndex = 4;
            }
            if (viewName.toLowerCase() == "allitems") {
                elementIndex++;
            }

            var actionElement = $(this).closest("tr").find("td:eq(" + elementIndex + ")");
            var actionValue = $(actionElement).html();
            var actionSubValue = "";
            if ((action == "Forward" || 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 == "Question" && question != null) {
                var listformUrlQuestion = listformUrl + "&ListId={" + oListIVRQuestions.get_id().toString() + "}&ID=" + questionId;
                var questionHyperlink = "<a onclick=\"OpenPopUpPage('" + listformUrlQuestion + "', RefreshPage); return false;\" href=\"" + listformUrlQuestion + "\">" + question + "</a>";
                actionSubValue = "<br>" + questionHyperlink;
            }

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

            if (viewName.toLowerCase() == "uccroutingview") {
                elementIndex++;
                var matchEndpointElement = $(this).closest("tr").find("td:eq(" + elementIndex + ")");
                var matchEndpointValue = $(matchEndpointElement).html();
                var matchEndpointSubValue = "";
                if (matchEndpointValue != "All") {
                    var matchEndpointValueSplit = [];
                    if (matchEndpointValue.indexOf(";") != -1) {
                        matchEndpointValueSplit = matchEndpointValue.split(";");
                    }
                    else {
                        matchEndpointValueSplit.push(matchEndpointValue);
                    }

                    $.each(matchEndpointValueSplit, function (index, value) {
                        var endpointTitle = value;
                        var result = $.grep(endpointList, function (e) { return e.Id == value; });
                        if (result != null && result.length == 1) {
                            endpointTitle = result[0].Title;
                        }
                        var listformUrlName = listformUrl + "&ListId={" + oListEndpoints.get_id().toString() + "}&ID=" + value;
                        var matchEndpointHyperlink = "<a onclick=\"OpenPopUpPage('" + listformUrlName + "', RefreshPage); return false;\" href=\"" + listformUrlName + "\">" + endpointTitle + "</a>";
                        matchEndpointSubValue += matchEndpointHyperlink + "<br>";
                    });
                    matchEndpointSubValue = matchEndpointSubValue.substring(0, matchEndpointSubValue.length - 4);
                    $(matchEndpointElement).html(matchEndpointSubValue);
                }
            }
        }
    });
}

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

function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
    return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}