;
(function ($, window, document, undefined) {
    "use strict";

    var $win = $(window),
        $doc = $(document),
        $body = $(document.body);

    var debug = false;

    $.mysouthwarkYourArea = function () {
        var self = this;
        return self;
    };

    $.mysouthwarkYourArea.prototype.name = 'mysouthwarkYourArea';

    $.mysouthwarkYourArea = {
        registerPanel: registerPanel,
        enableDebug: enableDebug
    };

    function registerPanel(options) {
        var fullOptions = $.extend({}, $.mysouthwarkYourArea.defaultOptions, options);

        log(fullOptions.panelId, "Registered");

        $.ajax({
            contentType: "application/json; charset=utf-8",
            url: fullOptions.getDataUri,
            dataType: "json",
            success: function (data) {
                if (data === null || data === undefined || data.length === 0) {
                    log(fullOptions.panelId, "Ajax completed - No Data");

                    if (fullOptions.noDataTemplate !== null) {
                        $("#" + fullOptions.panelId + fullOptions.loaderIdSuffix).replaceWith('<div class="row clearfix noBottomPadding" data-equalizer><div class="card columns small-12 large-4 large-push-4"><div class="cardWrap panel withShadow noBottomMargin" data-equalizer-watch>' + fullOptions.noDataTemplate + "</div></div></div>");
                    }
                } else {
                    log(fullOptions.panelId, "Ajax completed - Data received");
                    processResponse(fullOptions, data);
                }
            },
            error: function (jqXHR, textStatus, errorThrown) {
                log(fullOptions.panelId, "Ajax failed: " + textStatus + " - " + errorThrown);

                if (fullOptions.errorTemplate !== null) {
                    $("#" + fullOptions.panelId + fullOptions.loaderIdSuffix).replaceWith('<div class="row clearfix noBottomPadding" data-equalizer><div class="card columns small-12 large-4 large-push-4"><div class="cardWrap panel withShadow noBottomMargin" data-equalizer-watch>' + fullOptions.errorTemplate + "</div></div></div>");
                }
            }
        });
    }

    function getTemplateId(options, templateId, type) {
        return "template-" + options.panelId + "-" + templateId + "-" + type;
    }

    function hasNoDataTemplate(data, widgetId) {
        for (var i in data.templates) {
            if (data.templates[i].id === widgetId) {
                return data.templates[i].noDataTemplate !== null && data.templates[i].noDataTemplate.length > 0;
            }
        }

        return false;
    }

    function processResponse(options, data) {
        for (var t in data.templates) {
            log(options.panelId, "Templates for widget " + data.templates[t].id + " added");

            $('<script type="text/x-jsrender" id="' + getTemplateId(options, data.templates[t].id, "content") + '">' + data.templates[t].contentTemplate + '</script>').appendTo("body");
            $('<script type="text/x-jsrender" id="' + getTemplateId(options, data.templates[t].id, "error") + '">' + data.templates[t].errorTemplate + '</script>').appendTo("body");
            $('<script type="text/x-jsrender" id="' + getTemplateId(options, data.templates[t].id, "noData") + '">' + data.templates[t].noDataTemplate + '</script>').appendTo("body");
        }

        var widgetAreaId = options.panelId + "-widgets";
        $("#" + options.panelId + options.loaderIdSuffix).replaceWith('<div id="' + widgetAreaId + '"></div>');

        var column = 0;
        var currentRow = null;
        var firstRow = true;

        var widgets = data.results.length;

        for (var i in data.results) {
            var result = data.results[i];
            log(options.panelId, "Processing result for widget " + result.widgetId + " (" + result.name + ")");

            var noData = result.data === null || typeof result.data === "undefined" || result.length === 0;

            if (noData) {
                if (hasNoDataTemplate(data, result.widgetId)) {
                    log(options.panelId, "No data, will show the no data template");
                } else {
                    log(options.panelId, "No data and no template to defined, ignoring render");
                    continue;
                }
            }

            if (column === 0) {
                if (firstRow) {
                    currentRow = $('<div class="row clearfix noBottomPadding" data-equalizer></div>');
                    firstRow = false;
                } else {
                    currentRow = $('<div class="row clearfix noPadding" data-equalizer></div>');
                }
            }

            var outerCss = "card columns small-12 large-4";

            if (widgets === 1) {
                outerCss = "card columns small-12";
            }

            var cardLabelId = "cardLabel-" + widgetAreaId + "-" + result.widgetId + "-" + i;
            var outer = $('<div class="' + outerCss + '" aria-labelledby="' + cardLabelId + '"></div>').appendTo(currentRow);
            var container = $('<div class="cardWrap panel withShadow noBottomMargin" data-equalizer-watch></div>').appendTo(outer);
            var template = $.templates("#" + getTemplateId(options, result.widgetId, noData ? "noData" : "content"));

            var systemData = {
                index: i,
                panelId: options.panelId,
                widgetId: result.widgetId,
                widgetAreaId: widgetAreaId,
                cardLabelId: cardLabelId,
                widgetName: result.name
            };

            var templateData = $.extend({}, {
                widget: systemData
            }, result.data);
            var html = template.render(templateData);
            $(html).appendTo(container);

            column++;

            if (column === 3) {
                column = 0;
                currentRow.appendTo("#" + widgetAreaId);
            }
        }

        if (column > 0) {
            currentRow.appendTo("#" + widgetAreaId);
        }
    }

    function log(panelId, message) {
        if (debug)
            console.log("Panel ID " + panelId + ": " + message);
    }


    function enableDebug() {
        debug = true;
    }

    $.mysouthwarkYourArea.defaultOptions = {
        panelId: null,
        loaderIdSuffix: "-cards-loader",
        getDataUri: null,
        errorTemplate: null,
        noDataTemplate: null,
        debug: false
    };

})(jQuery, window, document);