"use strict";

App.addInitializer(function(options){

    var $document = $(document);

    // A box that randomly changes colour when css assets become new
    if (window.location.href.indexOf("track_assets_version") > 0) {
        var cssHref = $("link[rel=stylesheet]").attr("href");
        var assetsVersion = cssHref.slice(cssHref.indexOf("?") + 1);
        var $cssUpdateIndicator = $.bem.generateElement("app", "assets-version-indicator");
        $cssUpdateIndicator.text("assets version: " + assetsVersion);
        $cssUpdateIndicator.appendTo($(".app"));
        $cssUpdateIndicator.click(function() {
            App.showNotification({id: "assets-version-indicator", content: "This element changes colour when the css file recomplies."});
        });
    }
    var codeVersion = "2015-03-12";
    var latestChange = "Comparison views and also three new views for collections were added (<b>tuning stats</b>, <b>tonic histogram</b> and <b>pitch class histogram</b>). All three demo states now have the same sets of rows."
    var previouslyOpenedCodeVersion = App.DataModule.Storage.getStrCache(null, "code-version");
    if (codeVersion != previouslyOpenedCodeVersion) {
        App.DataModule.Storage.setStrCache(null, "introductory-hint-was-read", undefined);
        App.DataModule.Storage.setStrCache(null, "code-version", codeVersion);
    }

    if (previouslyOpenedCodeVersion < "2015-03-12") {
        App.contextManager.restoreDefault(App.context, "empty");
    };

    // introductory hint
//    if (!App.DataModule.Storage.getStrCache(null, "introductory-hint-was-read")) {
//        setTimeout(function() {
//            App.showNotification({
//                content: Backbone.Marionette.TemplateCache.get("#notification-content_tmp-instructions")({
//                    codeVersion: codeVersion,
//                    latestChange: latestChange,
//                    ctrl:  App.keyboardMappings.ctrlTitle,
//                }),
//                onClose: function() {
//                    App.DataModule.Storage.setStrCache(null, "introductory-hint-was-read", "yes")
//                },
//                modifiers: ["ttl_ever"]
//            });
//        }, 3000);
//        //}, 0);
//    }

    // scrollable data in vis instances for Samer (if he adds ?scroll)
    if (window.location.href.indexOf("scroll") > 0) {
        $("body").addClass("scrollable-pres-in-vis-instances");
    }

    var latestVisit = App.DataModule.Storage.getStrCache(null, "latest-visit");

    // Flash help when a user sees the vis for the first time
    if (!latestVisit) {
        setTimeout(function() {
            if (!App.helpIsShowing()) {
                App.MainMenuModule.flashItem("help", 20);
                // Show help when a user sees the vis for the first time
//                App.MainMenuModule.flashItem("help", 20, function() {
//                    App.showHelp();
//                });
            }
        }, 5000);
    }


    App.DataModule.Storage.setStrCache(null, "latest-visit", (new Date().toString()));


    // A warning that a backup api is being used
    var defaultURIIdentifier = options.musicLibrary.defaultApiRootPaths[0];
    if (options.musicLibrary.apiRootPaths[0].indexOf(defaultURIIdentifier) == -1) {
        var currentURIIdentifier = options.musicLibrary.apiRootPaths[0].replace(/^[a-zA-Z]*:?\/\//, "").replace(/\/$/, "");
        setTimeout(function() {
            App.showNotification({
                content: Backbone.Marionette.TemplateCache.get("#notification-content_alternative-api")({
                    defaultURIIdentifier: defaultURIIdentifier,
                    currentURIIdentifier: currentURIIdentifier,
                    stuffToRemoveFromAddess: "api2",
                }),
                modifiers: ["ttl_30", "type_warning"]
            });
        }, 1000);
    }

    // Debug API on / off
    var debugAPIShortcut = App.keyboardMappings.ctrlShift + "+8";
    var debugAPIShortcutTitle = App.keyboardMappings.ctrlShiftTitle + "+8";
    var debugAPIMessageVersion = 1;
    var showDebugAPIModeNotificationIfNeeded = function() {
        if (App.options.debugAPI && App.DataModule.Storage.getStrCache(null, "debug-api-message-shown") != debugAPIMessageVersion) {
            App.showNotification({
                id: "debug-api",
                content: Backbone.Marionette.TemplateCache.get("#notification-content_debug-api")({
                    debugAPIShortcut: debugAPIShortcutTitle,
                }),
                onClose: function() {
                    App.DataModule.Storage.setStrCache(null, "debug-api-message-shown", debugAPIMessageVersion ? "1" : 0);
                },
                modifiers: ["ttl_ever", "type_warning"]
            });
        }
    };

    $document.bind("keydown", debugAPIShortcut, function(event) {
        App.options.debugAPI = !App.options.debugAPI;
        if (!App.options.debugAPI) {
            App.hideNotification("debug-api");
        }
        showDebugAPIModeNotificationIfNeeded();
        App.mainRegionView.render(true);
        App.DataModule.Storage.setStrCache(null, "debug-api", App.options.debugAPI ? "1" : "");
    });
    showDebugAPIModeNotificationIfNeeded();

    // Change entity width

    //var widths = [100, 200, 300, 500, 750, 1000, 1]
    var minWidth = 100;
    var step = 20;
    var maxWidth = 2000;
    var changeEntityWidth = function(direction) {
        var currentGrid = App.context.get("state").getConfigGridBeingShown();
        var currentEntityWidth = (currentGrid.get("entityWidth") || App.options.defaultEntityWidth) * 1;

        var diff = direction > 0 ? step : -step;
        var newEntityWidth = currentEntityWidth + diff;
        if (newEntityWidth > maxWidth) {
            newEntityWidth = maxWidth;
        }

        if (newEntityWidth < minWidth) {
            newEntityWidth = minWidth;
        }

        currentGrid.set("entityWidth", newEntityWidth);
    };

    $document.bind("keydown", "pageup", function(event) {
        changeEntityWidth(1);
        event.preventDefault();
    });
    $document.bind("keydown", "pagedown", function(event) {
        changeEntityWidth(-1);
        event.preventDefault();
    });
});
