// playlists_custom.js
var currentId = "";
var currentPlaylist = "";
var availablePlaylists = [];
var playlistsData = [];
var orderData = [];
var usedOrder = [];
var pattern;

$(document).ready(function () {
    pattern = new RegExp("^-?\\d*\\.{0,1}\\d+$");

    if (customFormMode == "add" || customFormMode == "listview") {
        ExecuteOrDelayUntilScriptLoaded(function () { retrieveAvailablePlaylists() }, "sp.js");
    }

    if (customFormMode == "add") {
        var tmpPlaylist = getParameterByName("playlist");
        if (tmpPlaylist != null && tmpPlaylist != "") {
            $("input[title*='Playlist']").val(tmpPlaylist);
            currentPlaylist = tmpPlaylist;
        }

        $("input[title*='Playlist']").bind("keyup", function () {
            currentPlaylist = $("input[title*='Playlist']").val();
            OrderHandler();
        });
        $("input[title*='Playlist']").bind("focusout", function () {
            currentPlaylist = $("input[title*='Playlist']").val();
            OrderHandler();
        });
        $("input[title*='Playlist']").bind("mousedown", function () {
            currentPlaylist = $("input[title*='Playlist']").val();
            OrderHandler();
        });
    }
    else if (customFormMode == "edit") {
        currentId = getParameterByName("ID");
        currentPlaylist = $("input[title*='Playlist']").val();
        var currentAudioFile = $("select[title*='Audio File']").find(":selected").text();
        var currentOrder = $("input[title*='Order']").val();
        $("input[title*='Playlist']").css("display", "none");
        $("input[title*='Playlist']").after(currentPlaylist);
        $("select[title*='Audio File']").css("display", "none");
        $("select[title*='Audio File']").after(currentAudioFile);
        $("input[title*='Order']").css("display", "none");
        $("input[title*='Order']").after(currentOrder);
    }

    $("input[title*='Order']").bind("keyup", function () {
        ValidateOrder();
    });
    $("input[title*='Order']").bind("focusout", function () {
        ValidateOrder();
    });
    $("input[title*='Order']").bind("mousedown", function () {
        ValidateOrder();
    });
});

// Available Playlists Query
function retrieveAvailablePlaylists() {
    try {
        var clientContext = SP.ClientContext.get_current();
        var oList = clientContext.get_web().get_lists().getByTitle('Playlists');

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

        clientContext.load(collAvailablePlaylistsItems);
        clientContext.executeQueryAsync(Function.createDelegate(this, this.onQueryRetrieveAvailablePlaylistsSucceeded), Function.createDelegate(this, this.onQueryFailed));
    }
    catch (exp) {
        console.log("retrieveAvailablePlaylists " + exp);
    }
}

function onQueryRetrieveAvailablePlaylistsSucceeded(sender, args) {
    try {
        var listItemEnumerator = collAvailablePlaylistsItems.getEnumerator();
        while (listItemEnumerator.moveNext()) {
            var oListItem = listItemEnumerator.get_current();
            var oListItemId = oListItem.get_item('ID');
            var oListItemTitle = oListItem.get_item('Title');
            var oListItemAudioFile = oListItem.get_item('wsp_ucc_pl_audiofile');
            var oListItemOrder = oListItem.get_item('wsp_ucc_pl_order');
            var oListItemActive = oListItem.get_item('wsp_ucc_pl_active');

            var keyExists = $.inArray(oListItemTitle, availablePlaylists);
            if (keyExists == -1) {
                availablePlaylists.push(oListItemTitle);
            }

            // Playlists data
            var dataKeyExists1 = oListItemId in playlistsData;
            if (dataKeyExists1 == false) {
                playlistsData[oListItemId] = [];
            }
            playlistsData[oListItemId].push(oListItemTitle);
            playlistsData[oListItemId].push(oListItemAudioFile);
            playlistsData[oListItemId].push(oListItemOrder);
            playlistsData[oListItemId].push(oListItemActive);

            // Order data
            var dataKeyExists2 = oListItemTitle in orderData;
            if (dataKeyExists2 == false) {
                orderData[oListItemTitle] = [];
                orderData[oListItemTitle].push(-1);
                orderData[oListItemTitle].push(-1);
                orderData[oListItemTitle].push(0);
            }

            if (oListItemOrder > orderData[oListItemTitle][1]) {
                orderData[oListItemTitle][1] = oListItemOrder;
            }

            if (orderData[oListItemTitle][0] == -1) {
                orderData[oListItemTitle][0] = oListItemOrder;
            }
            else if (orderData[oListItemTitle][0] != -1 && oListItemOrder < orderData[oListItemTitle][0]) {
                orderData[oListItemTitle][0] = oListItemOrder;
            }

            // Count
            orderData[oListItemTitle][2] = orderData[oListItemTitle][2] + 1;
        }

        if (customFormMode == "add") {
            $("input[title*='Playlist']").autocomplete({
                source: availablePlaylists
            });
            OrderHandler();
        }
    }
    catch (exp) {
        console.log("onQueryRetrieveAvailablePlaylistsSucceeded " + exp);
    }
}

// Used Order Query
function retrieveUsedOrder(playlist) {
    try {
        var clientContext = SP.ClientContext.get_current();
        var oList = clientContext.get_web().get_lists().getByTitle('Playlists');

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

        clientContext.load(collOrderItems);
        clientContext.executeQueryAsync(Function.createDelegate(this, this.onQueryRetrieveUsedOrderSucceeded), Function.createDelegate(this, this.onQueryFailed));
    }
    catch (exp) {
        console.log("retrieveUsedOrder " + exp);
    }
}

function onQueryRetrieveUsedOrderSucceeded(sender, args) {
    try {
        usedOrder = [];
        var listItemEnumerator = collOrderItems.getEnumerator();
        while (listItemEnumerator.moveNext()) {
            var oListItem = listItemEnumerator.get_current();
            var oListItemId = oListItem.get_item('ID');
            var oListItemTitle = oListItem.get_item('Title');
            var oListItemOrder = oListItem.get_item('wsp_ucc_pl_order');

            if (oListItemTitle == currentPlaylist && oListItemId != currentId) {
                usedOrder.push(oListItemOrder);
            }
        }

        ValidateOrder();
    }
    catch (exp) {
        console.log("onQueryRetrieveUsedOrderSucceeded " + exp);
    }
}

function ValidateOrder() {
    var testValue = $("input[title*='Order']").val();
    $("input[title*='Order']").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 >= 1) {
            if ($.inArray(testInt, usedOrder) == -1) {
                $("input[id*='SaveItem']").prop("disabled", false);
                $("input[title*='Order']").css("border", "1px solid green");
                $("a[id='Ribbon.ListForm.Edit.Commit.Publish-Large']").prop("class", "ms-cui-ctl-large");
                $("input[title*='Order']").after("<span id='errorMsg' style='color:green;'>&nbsp;&nbsp;&nbsp;OK</span>");
            }
            else {
                var inUseMsg = resource_playlists_errormsg_inuse;
                $("input[title*='Order']").after("<span id='errorMsg' style='color:red;'>&nbsp;&nbsp;&nbsp;" + inUseMsg + "</span>");
            }
        }
        else {
            var notInRangeMsg = resource_playlists_errormsg_notinrange;
            $("input[title*='Order']").after("<span id='errorMsg' style='color:red;'>&nbsp;&nbsp;&nbsp;" + notInRangeMsg + "</span>");
        }
    }
    else {
        var errorMsg = resource_playlists_errormsg_empty;
        if (testValue != null && testValue != "") {
            errorMsg = resource_playlists_errormsg_nonumber;
        }
        $("input[title*='Order']").after("<span id='errorMsg' style='color:red;'>&nbsp;&nbsp;&nbsp;" + errorMsg + "</span>");
    }
}

function OrderHandler() {
    if (currentPlaylist != "") {
        if (currentPlaylist in orderData) {
            $("input[title*='Order']").val(orderData[currentPlaylist][1] + 1);
            ExecuteOrDelayUntilScriptLoaded(function () { retrieveUsedOrder(currentPlaylist); }, "sp.js");
        }
        else {
            usedOrder = [];
        }
    }
}

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, " "));
}