// SingleViewConfiguration.js - Populate default Settings for the solution

function populateSingleViewSettings() { // Call data function async to populate tiles array, chain to displayTiles once we have data
    // alert("Considering " + ms.Data.Records.length + " records for " + ms.Data.odataSetName
    //    + " (Key is " + ms.Data.keyAttribute + ", preventDuplicates=" + ms.Data.preventDuplicates + ")");
    for (var i = 0, len = ms.Data.Records.length; i < len; i++) {
        var html = "<li>" + ms.Data.Records[i][ms.Data.keyAttribute] + ": <span id='settings" + i + "'></span>";
        $("#settingsList").append(html);
        var oContext = {
            "index": i,
            "keyAttribute": ms.Data.keyAttribute,
            "key": ms.Data.Records[i][ms.Data.keyAttribute],
            "id": "#settings" + i
        };
        $(oContext.id).addClass("Busy");
        if (!ms.Data.preventDuplicates) {
            $(oContext.id).text("Creating...");
            createConfig(oContext, ms.Data.Records[i]);
        } else {
            $(oContext.id).text("Checking for existing records...");
            createConfigIfUnique(oContext, ms.Data.Records[i]);
        }
    }
}

function createConfigIfUnique(oContext, configRecord) {
    // alert(oContext.key);
    retrieveMultiple("ms_singleviewsettingSet", oContext.keyAttribute + " eq '" + oContext.key + "'", oContext.keyAttribute, processConfig, oContext, false);
}

function processConfig(results, oContext) {
    // alert(oContext.key);
    if (results.length > 0) {
        $(oContext.id).text("Existing record (left intact).");
        $(oContext.id).removeClass("Busy");
        $(oContext.id).addClass("Ok");
    } else {
        createConfig(oContext, ms.Data.Records[oContext.index]);
    }
}

function createConfig(oContext, configRecord) {
    // alert("Creating Configuration Record for " + oContext.key);
    createRecord(configRecord, "ms_singleviewsettingSet", createCompleted, oContext, false);
}

function createCompleted(record, oContext) {
    $(oContext.id).text("Created.");
    $(oContext.id).removeClass("Busy");
    $(oContext.id).addClass("Ok");
}
function errorHandler(xmlHttpRequest, oContext, textStatus, errorThrow) {
    $(oContext.id).removeClass("Busy");
    $(oContext.id).addClass("Error");
    $(oContext.id).text("* Ajax Error (" + xmlHttpRequest.statusText + ")");
    // alert("ms.DataAccess - Ajax Error\n\n" + textStatus + ": " + xmlHttpRequest.statusText);
}