/// <reference path="http://localhost/IndustrialDashboard/Scripts/IndustrialDashboard-debug.js" />
define([
  // Application.
  "app",

  //templates-loader
  "js/templates-loader", 

  "js/jquery.vticker"

],

function (app, T) {

    var NotificationBar = { Collection: {}, Model: {}, Views: {} }
    
    NotificationBar.Model = Backbone.Model.extend({
        defaults: {
            list: []
            , lastDateChecked: null
            , newElems: 0
        }

        , initialize: function () {
        }

        , fetch: function (args) {
            //overriding fetch method
            //according to our needs.

            //var jsonObj = {};
            //Core.Object.Extend(this.attributes, jsonObj);

            //jsonObj.newElems = 0; 

            //var QP = new Core.Database.QueryParameters();
            //QP.Add("lastDateChecked", "DATETIME", this.get("lastDateChecked"));

            //Core.Json.CallProcedure("dbo.GetNotifications", QP, {
            //    onSuccess: function (data) {
            //        if (Core.Object.Eval(data, "Table.0")) {
            //            var meta = data.Table[0]; 
            //            jsonObj.lastDateChecked = meta.ToTimestamp; 
            //        }

            //        if (Core.Object.Eval(data, "Table1")) {
            //            var notificationList = data.Table1;
            //            jsonObj.newElems = notificationList.length;
            //            var notificationsParams = (Core.Object.Eval(data, "Table2")) ? data.Table2 : null; 

            //            for (var i = 0; i < notificationList.length; i++) {
            //                var item = {};
            //                Core.Object.Extend(notificationList[i], item); 
            //                if (notificationsParams) {
            //                    var notUsed = [];
            //                    var p = null; 
            //                    while ((p = notificationsParams.pop()) != null) {
            //                        if (p.NotificationId == item.Id) {
            //                            if (!item.Parameters) item.Parameters = {};
            //                            item.Parameters[p.Name] = p.Value;
            //                        } else {
            //                            var h = p; 
            //                            notUsed.push(h); 
            //                        }
            //                    }
            //                    notificationsParams = notUsed; 
            //                }
            //                item.HREF = app.router.resolveURL(item.Route, (item.Parameters) ? item.Parameters : null);
            //                jsonObj.list.unshift(item);
            //            }
            //        }

            //    },
            //    Async: false
            //}, app.ConnectionStrings.app);

            ////change method is fired.
            //this.set(this.parse(jsonObj), {});
            //var that = this; 
            //setTimeout(function () { that.fetch() }, 1000);
            return this;

        }
    });

    NotificationBar.Views.Main = Backbone.View.extend({
        template: "notificationBar/notificationBar"
        , id: "notification-bar"
        , title: ""
        //default not cacheable, change this if you want the view to be cacheable
        // if the view is set as cacheable should also have a refresh method to reset the view without erasing the DOM.
        //refreshing only the data, maybe?
        , isCacheable: false
        , initialize: function () {
            //binding the correct (this) object to everymethod.
            _.bindAll(this);

            this.options.attributes = {};

            this.listenTo(this.model, 'change', this.refresh); 
        },

        events: {
            "click #nb_button_next": "next"
            , "click #nb_button_prev": "prev"
            , "click #nb_button_top": "top"
        }, 
        // global view variable (seen in this scope, public to the view, and SHARED BETWEEN OTHER INSTANCES OF THE SAME VIEW)
        // containing all the variables for this view

        //properties that you wanna scope as private variables for each instance of a view should not be placed here
        //the only way i found to maintain the variables between instances of the same view, is either using models,
        // (each view will have its own model so data is not shared between them), or in case you don't want to use a model
        // you can use the Backbone.View.options object, and doing something like
        // this.options.attributes = {}
        // and storing every single variable inside attributes.

        render: function (container) {
            var that = this;
            var thatContainer = container;
            T.render.call(this, this.template, function (tmp) {
                //getInternationalizationData
                if (!that.options.i18n) that.options.i18n = {};
                app.getI18NJed(that, that.template, function (i18nJED) {
                    //storing internationalization data
                    that.options.i18n[that.template] = i18nJED;

                    //start: before the view is visible, but the template was already loaded (not instanced nor appended)

                    //end:

                    //loading the view and appeding it to the views's $el.
                    that.$el.html(tmp());

                    that.options.attributes.notificationsCount = { isVisible: false, count: 0, timeout:null };
                    
                    that.$el.find("#ticker1_container").vTicker('init', {showItems: 2, height:40, mousePause: true, startPaused: true });
                    that.$el.find("#ticker1_container").vTicker('pause', true);

                    that.$el.find('.tooltip-this').tooltip();

                    //start: the view was already loaded an is on a div element, but not appended to the main container
                    //here you can perform anything you want DOM related, by getting the dom element via that.$el.find("#id")

                    //:end

                    //appending view to the main container
                    //thatContainer.append(that.$el);

                    that.model.fetch({autorefresh:true});

                });
            });
        }
        , refresh: function (a, b, c) {
            var list = this.model.get("list");
            var ul = this.$el.find("#ticker1_ul");
            var li;
            var newElems = this.model.get("newElems"); 
            if (newElems > 0) {
                for (var i = 0; i < newElems ; i++) {
                    var firstElem = ul.find("li.firstElem");
                    li = document.createElement('li');
                    li.className = "nb-li firstElem";

                    var anchorHREF = document.createElement('a');
                    anchorHREF.href = list[i].HREF; 
                    li.appendChild(anchorHREF); 

                    var spanDate = document.createElement('span');
                    spanDate.className = "nb-msg-datetime";
                    spanDate.innerHTML = list[i].Timestamp;
                    anchorHREF.appendChild(spanDate);
                    
                    var spanMessage = document.createElement('span');
                    spanMessage.className = "nb-msg-body";
                    spanMessage.innerHTML = list[i].Description; 
                    anchorHREF.appendChild(spanMessage);

                    if (firstElem.length > 0 && !ul.children('li:first').hasClass("firstElem")) {
                        firstElem.before(li);    
                    } else {
                        ul.children('.nb-end').before(li);
                        ul.find("#no-new-notifications").remove(); 
                    }
                    if (firstElem.length > 0) firstElem.removeClass("firstElem");
                }

                this.$el.find("#ticker1_container").vTicker('refresh');
                this.showNotificationsCount(newElems); 
                this.top(); 
            }
        }
        , showNotificationsCount: function (count) {
            var nc = this.options.attributes.notificationsCount;
            var nc_elem = this.$el.find("#notifications_count_badge");

            if (nc.isVisible) {
                clearTimeout(nc.timeout);
                nc.count += count;
                nc_elem.html(nc.count);
            } else {
                nc.count += count;
                nc_elem.html(nc.count);
                nc.isVisible = true;                
            }

            nc.timeout = setTimeout(this.hideNotificationsCount, 7000);
            
        }
        , hideNotificationsCount: function () {
            var nc = this.options.attributes.notificationsCount;
            nc_elem = this.$el.find("#notifications_count_badge");

            nc.count = 0;
            nc.timeout = null;
            nc_elem.html("");

            nc.isVisible = false; 
        }
        , next: function () {
            this.$el.find("#ticker1_container").vTicker('next', { animate: true });
        }
        , prev: function () {
            this.$el.find("#ticker1_container").vTicker('prev', { animate: true });
        }
        , top: function () {
            this.$el.find("#ticker1_container").vTicker('scrollToTop', { animate: true });
        }
        , _setSectionsLayout: function () {
            app.models.subnavbar.set("sections", "4-4-4");
        }
        , close: function () {
            this.remove();
            this.unbind();
        }
        , show: function () {
            this._setSectionsLayout(); 
            this.$el.show();
        }
        , hide: function () {
            this.$el.hide();
        }
    });

    // Required, return the module for AMD compliance.
    return NotificationBar;

});
