/* Minification failed. Returning unminified contents.
(1,1): run-time error CSS1019: Unexpected token, found '$'
(1,2): run-time error CSS1019: Unexpected token, found '('
(1,12): run-time error CSS1031: Expected selector, found '('
(1,12): run-time error CSS1025: Expected comma or open brace, found '('
(34,2): run-time error CSS1019: Unexpected token, found ')'
(36,1): run-time error CSS1019: Unexpected token, found '$'
(36,2): run-time error CSS1019: Unexpected token, found '('
(36,3): run-time error CSS1019: Unexpected token, found '".dropdown-menu"'
(36,19): run-time error CSS1019: Unexpected token, found ')'
(36,21): run-time error CSS1030: Expected identifier, found 'on('
(36,21): run-time error CSS1019: Unexpected token, found 'on('
(36,24): run-time error CSS1019: Unexpected token, found ''click''
(36,31): run-time error CSS1019: Unexpected token, found ','
(36,33): run-time error CSS1019: Unexpected token, found ''li a''
(36,39): run-time error CSS1019: Unexpected token, found ','
(36,50): run-time error CSS1031: Expected selector, found '('
(36,50): run-time error CSS1025: Expected comma or open brace, found '('
(53,2): run-time error CSS1019: Unexpected token, found ')'
(55,9): run-time error CSS1031: Expected selector, found '='
(55,9): run-time error CSS1025: Expected comma or open brace, found '='
(85,10): run-time error CSS1031: Expected selector, found '='
(85,10): run-time error CSS1025: Expected comma or open brace, found '='
(142,11): run-time error CSS1031: Expected selector, found '='
(142,11): run-time error CSS1025: Expected comma or open brace, found '='
(244,12): run-time error CSS1031: Expected selector, found '='
(244,12): run-time error CSS1025: Expected comma or open brace, found '='
(290,12): run-time error CSS1031: Expected selector, found '='
(290,12): run-time error CSS1025: Expected comma or open brace, found '='
(372,12): run-time error CSS1031: Expected selector, found '='
(372,12): run-time error CSS1025: Expected comma or open brace, found '='
(382,9): run-time error CSS1031: Expected selector, found '='
(382,9): run-time error CSS1025: Expected comma or open brace, found '='
(397,10): run-time error CSS1031: Expected selector, found '='
(397,10): run-time error CSS1025: Expected comma or open brace, found '='
(402,18): run-time error CSS1031: Expected selector, found '='
(402,18): run-time error CSS1025: Expected comma or open brace, found '='
(404,13): run-time error CSS1031: Expected selector, found '='
(404,13): run-time error CSS1025: Expected comma or open brace, found '='
(430,11): run-time error CSS1031: Expected selector, found '='
(430,11): run-time error CSS1025: Expected comma or open brace, found '='
(443,16): run-time error CSS1031: Expected selector, found '='
(443,16): run-time error CSS1025: Expected comma or open brace, found '='
 */
$(function () {

    //
    // sätter färger enligt valt tema
    //
    var temaFarg = $('#FargKodLjus').val();
    var temaFargMork = $('#FargKodMork').val();
    var temaTextFarg = $('#FargKodText').val();

    if (temaFarg) {
        $('.SLV-bg-tema').css({ "background-color": temaFarg });
        $('.dropdown.SLV-border-tema').css({ "background-color": temaFarg });
        $('.SLV-border-tema').css({ "border-color": temaFarg });
        $('div.SLV-maltids-tillfalle:hover').css({ "background-color": temaFarg });
        $('.SLV-BEKRAFTA-radio-trigger:hover').css({ "border-color": temaFarg });
    }

    if (temaFargMork) {
        $('.SLV-bg-tema-mork').css({ "background-color": temaFargMork });
    }

    if (temaTextFarg) {
        $(".SLV-bg-tema > h4").css({ "color": temaTextFarg });
        $(".SLV-bg-tema > h5").css({ "color": temaTextFarg });
    }
    
    //Visa element efter att färgen är satt, de ska vara dolda innan
    $('.SLV-bg-tema').css("visibility", "visible");
    $('.SLV-bg-tema-mork').css("visibility", "visible");
    $('.dropdown.SLV-border-tema').css("visibility", "visible");
    $('.SLV-border-tema').css("visibility", "visible");
    $('div.SLV-maltids-tillfalle:hover').css("visibility", "visible");
    $('.SLV-BEKRAFTA-radio-trigger:hover').css("visibility", "visible");
});

$(".dropdown-menu").on('click', 'li a', function () {
    
    var item = $(this);

    if (item.hasClass("disabled")) {
        event.preventDefault();
        return false;
    }

    var itemVal = item.children('.SLV-hidden');
    var newHeading = item.text();
    var button = $(this).closest('.dropdown').children('.dropdown-toggle');
    button.find('.SLV-dropdown-button-text').html(newHeading);
    var hidden = button.find('.SLV-hidden');
    hidden.val(itemVal.val());
    hidden.trigger('change');
    
});

var slv = {
    loggaUt: function (id) {
        var urlAction = slv.mvc.getUrlAction("LoggaUt", "Home");

        var request = slv.ajax.doPostRequest(urlAction, null, false),
              chained = request.then(function (response) {
                  if (response.success) {
                      var urlAction = slv.mvc.getUrlAction("LoggaInVy", "LoggaIn", id);
                      window.location = urlAction;
                  }
                  else {
                      alert("Ett fel uppstod");
                  }
              });
    },

    runThis: function (input) {
        var url = input;
        window.location = url;
    },

    toBool: function (s) {
        if (s == 'true' || s == 'True' || s == 'TRUE') {
            return true
        }
        else
            return false;
    }
};

slv.ajax = {
    selectors: {
        ajaxLoadingIndicator: "#loading-indicator"
    },
    doGetRequest: function (urlAction, requestData, async, callBack) {
        return this.doRequest(urlAction, requestData, async, callBack, "GET");
    },
    doPostRequest: function (urlAction, requestData, async, callBack) {

        return this.doRequest(urlAction, requestData, async, callBack, "POST");
    },
    doRequest: function (urlAction, requestData, async, callBack, type) {
        var bAsync = typeof (async) == 'undefined' ? true : async;

        return $.ajax({
            url: urlAction,
            type: type,
            async: bAsync,
            cache: false,
            data: requestData,
            dataType: 'json',
            traditional: true,
            processData: true,
            error: function (xhr, r) {

                if (slv.debug.isEnabled) {
                    var debugMsg = { "urlAction": urlAction, "requestData": requestData, "async": async, "type": type, "readyState": xhr.readyState, "responseText": xhr.responseText };
                    slv.debug.output(debugMsg);
                }
                else {
                }


            },
            success: function (result) {
                if (callBack != null) {
                    callBack(result);
                }
            },
            complete: function () {
            }
        });
    },
    initAjaxEvents: function () {
        var that = this;
        var selectors = that.selectors;
        $(document).ajaxSend(function (event, request, settings) {
            $(selectors.ajaxLoadingIndicator).show();
        });

        $(document).ajaxComplete(function (event, request, settings) {
            $(selectors.ajaxLoadingIndicator).hide();
        });
    },
};


slv.debug = {
    isEnabled: false,
    arDebugBuild: false,
    _debugEl: null,
    _radBryt: "\n",
    enable: function (settings) {
        this.addDebugStyles();
        settings = $.extend({
            arHtmlRadBryt: true,
            startMs: new Date(),
            endMs: null
        }, settings);
        this._settings = settings;

        this._radBryt = settings.arHtmlRadBryt ? "<BR/>" : "\n";

        ///<summary>Sätt på debug läge om applikation är byggd i debug läge
        ///<para>Utseende kan anpassas genom att ha css klasser definierede för #debugContainer och #debugOutput</para>
        ///</summary>
        if (this.arDebugBuild) {
            if ($("#debugOutput").length == 0) {
                $("body").append("<br style=\"clear: both;\"/><div id=\"debugContainer\"><div id=\"debugOutput\"/></div>");
            }
            $("#debugContainer").show();

            this._debugEl = $("#debugOutput");
            this.output = this._output;
            this.clear = this._clear;
            this.isEnabled = true;
        }

    },
    addDebugStyles: function () {
        if ($("style:contains('#debugContainer')").length > 0) return;

        $('<style type="text/css">'
            + '#debugContainer { float:none; height: 300px; overflow: auto; background-color: white; margin-top: 30px; width: 100%; border: 2px dotted green; }\n'
            + '#debugOutput { padding-top: 20px; padding-left: 20px; }'
            + '</style>').appendTo("head");
    },
    disable: function () {
        ///<summary>Stäng av debug läge</summary>
        var tomFn = function () { };
        this.output = tomFn;
        this.clear = tomFn;
        $("#debugContainer").hide();
    },
    output: function () { },
    clear: function () { },
    resetBenchmark: function () {
        this._settings.startMs = new Date();
        this._settings.endMs = null;
    },
    _output: function (msg) {
        ///<summary>Visa meddelande i debug panelen</summary>
        ///<param name="msg" type="String">Meddelande</param>
        var ms = this._getBenchmark();
        var d = this._debugEl;
        d.append('<span>' + (ms) + '</span>: ');
        var debugMsg = this._getDebugMsg(msg);
        d.append(debugMsg);
        d.append(this._radBryt);
    },
    _getDebugMsg: function (msg) {
        if (typeof (msg) != "object") return msg;

        var responseText = "";
        if (typeof (msg.responseText) != 'undefined') {
            responseText = msg.responseText;
            delete (msg.responseText);
        }

        var items = [];
        items.push(JSON.stringify(msg));


        if (responseText.length > 0) {
            items.push('<span>AJAX responseText</span>:');
            items.push('<div id="debugResponseText">');
            items.push(responseText);
            items.push('</div');
        }

        var debugMsg = items.join("<br/>");

        return debugMsg;
    },

    _getBenchmark: function () {
        var s = this._settings;
        s.endMs = new Date();
        var n = s.endMs - s.startMs.getTime();
        s.startMs = s.endMs;
        return n;
    },
    _clear: function () {
        ///<summary>Rensa debug panelen</summary>
        this._debugEl.html('');
    }
};


slv.dialog = {
    bekrafta: function (urlEllerFunktion, meddelande) {
        var msg = '<p><span class="ui-icon ui-icon-alert" style="float: left; margin: 0 7px 20px 0;"></span>'
            + meddelande + '</p>';
        $("#confirmDialog").html(msg);
        $("#confirmDialog").dialog({
            //dialogClass: "no-close",
            resizable: false,
            //height: 220,
            //width: 440,
            modal: true,
            buttons: {
                "Ja": function () {
                    if (typeof (urlEllerFunktion) == "function") {
                        $(this).dialog("close");
                        urlEllerFunktion();
                    }
                    else {
                        document.location.href = urlEllerFunktion;
                    }
                },
                "Nej": function () {
                    $(this).dialog("close");
                }
            }
        });
    },
    visa: function (meddelande) {
        var msg = '<p><span class="ui-icon ui-icon-alert" style="float: left; margin: 0 7px 20px 0;"></span>'
            + meddelande + '</p>';
        $("#confirmDialog").html(msg);
        $("#confirmDialog").dialog({
            //dialogClass: "no-close",
            resizable: false,
            //height: 220,
            //width: 440,
            modal: true,
            buttons: {
                "OK": function () {
                    $(this).dialog("close");
                }
            }
        });
    }
};

slv.export = {
    options: {
        exportHeaderParent: "#exportArea",
        exportParentRow: "li"
    },
    exportTyper: {
        "excel": 1,
        "pdf": 2
    },
    postUsingIFrame: function (urlAction, request) {
        var params = typeof (request) == "object" ? JSON.stringify(request) : request;

        // Skapa exportformulär i en iframe för att kunna göra ajax anrop och returnera en fil. Spökar annars om man har flera formulär.
        $("#iframeExport").remove();

        var frmFrame = $('<iframe style="display:none;width:0;height:0" id="iframeExport"/>');
        var frmExport = $('<form method="post" name="frmExport" id="frmExport" action="' + urlAction + '"/>');
        if (typeof (params) != 'undefined') {
            var requestData = $('<input type="hidden" name="requestData" id="requestData" value="' + encodeURI(params) + '"/>');
            $(requestData).appendTo(frmExport);
        }
        $(frmExport).appendTo(frmFrame);
        $(frmFrame).appendTo("body");
        $(frmExport).submit();
    },
    spara: function (exportType, replaceHeaders) {
        var that = this;
        var options = that.options;
        var items = [];

        var headers = $(options.exportHeaderParent + " .exportHeader:visible");

        var columns = [];
        $.each(headers, function () {
            columns.push(decodeURI($(this).text()));
        });
        items.push(columns);

        if (replaceHeaders != null && replaceHeaders.length > 0) {
            for (var i = 0; i < replaceHeaders.length; i++) {
                columns[i] = replaceHeaders[i];
            }
        }

        var listItems = $("#exportArea content:visible, #exportArea div:visible").find(options.exportParentRow + ":visible");
        //var startIdx = that.options.exportParentRow == "tr" ? 1 : 0;

        $.each(listItems, function (i) {
            var firstCol = $(this).find(".exportInclude:eq(0):visible").text();
            columns = [];
            columns.push(decodeURI(firstCol));

            var values = $(this).find(".exportInclude:gt(0):visible");
            $.each(values, function () {
                var value = $(this).find(".exportExclude:visible").length > 0 ? "" : $(this).text();
                columns.push(value);
            });

            // Sometimes an empty array. Need to check why this is
            if (columns.length == headers.length) {
                items.push(columns);
            }

        })

        //TODO: kolla exportType när pdf finns

        var urlAction = slv.mvc.getUrlAction("HamtaExcelfil", "Spara");
        //var request = { "data": items };

        that.postUsingIFrame(urlAction, items);

    }
};



//slv.form = {

//};


slv.format = {
    toLocalDateTimeString: function (d) {
        d = new Date();

        var dStr = d.toJSON().substring(0, 10) + ' ' + d.toLocaleTimeString();
        return dStr;

    }
};

slv.mvc = {
    getUrlAction: function (methodName, controllerName, param) {
        var url = slv.page.appFolder;
        url += typeof (controllerName) != "undefined" && controllerName != null && controllerName.length > 0 ? controllerName + "/" : "";
        url += methodName;
        if (param != null) {
            url += "/" + param;
        }
        return url;
    },
    getUrlActionWithId: function (methodName, controllerName, id) {
        return slv.mvc.getUrlAction(methodName, controllerName) + "/" + (id);
    }
}

slv.page = {
    appFolder: "/"
    //cookieKeyMyFoodList: "minLivsmedelslista"
};

slv.page.context = {};

slv.plugins = {
    autoComplete: function (id, serviceUrl) {
        $.ajax({
            type: "POST",
            url: serviceUrl,
            data: param = "",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: successFunc,
            error: errorFunc
        });

        function successFunc(data, status) {
            $(id).autocomplete({
                source: data
            });
        }

        function errorFunc() {
            //alert('error');
        }

    }

};

slv.tools = {
    oppnaForUtskrift: function oppnaForUtskrift(url, windowName) {
        if (typeof (windowName) == 'undefined') windowName = "utskriftsfonster";
        var features = "location=no,menubar=no,status=no,titlebar=no,toolbar=no,scrollbars=yes";
        var w = window.open(url, windowName, features, false);

        w.focus();


    }
};


slv.validation = {
    disableRequiredFields: function () {
        ///<summary>Stäng av tvingande fält</summary>
        var sel = $("input[data-required]");
        sel.each(function (i) {
            $(this).data("required", null);
            $(this).on('focus', function () {
                $(this).data("required", true);
                $(this).off('focus');
            });
        });

    },
    enableRequiredFields: function () {
        ///<summary>Sätt på validering av tvingande fält</summary>
        var sel = $("input[data-required]");
        sel.each(function (i) {
            $(this).data("required", true);
        });

    }
};




