//SCREEN-BOILERPLATE

//this boilerplate builds screens that are gonna be shown in the <div class="content"> tag of our main HTML.
//do not build app components with this boilerplate, only screens (reports)

define([
  // Application variable, always include it to have access to app methods.
  "app",

  //templates-loader: this loads templates async.
  "js/templates-loader",

  "modules/modal",

  "backgrid",

  "moment", 
],

function (app, T, Modal, Backgrid, moment) {

    //replace all "DelaysSimple" with your view's name.
    var DelaysSimple = { 
        Models: {}, 
        Views: {}, 
        Collections: {},
        Config: {
            batchEnabled: false,
        },
    };

    DelaysSimple.Models.Main = Backbone.Model.extend({
        defaults: {
            delaySplits: null, 
        }
    });

    //the generate id method is called everytime a view is going to be shown by the router and returns and id that
    //is used by the router to store in cache (if it is cacheable) and to know the current shown view.
    //this is useful in case your view is reusable, and displays different data depending on url parameters 
    //(such as a catalog view, or a report that doesnt change in terms of UI but it does change in terms of data)
    //so you can always use the same view on the router but the cache can tell which view is which by using differents ids.
    DelaysSimple.generateID = function (viewParams) {
        try {
            //if the viewparams change the view id, then evaluate the viewparams here
            //and return the appropiate id.
            return "delays-simple"; 
        } catch (Error) { }
    }

    DelaysSimple.Models.DelaySplit = Backbone.Model.extend({
        defaults: {
            delayId: null,
            parentId: null,
            line: null,
            productionItem: null, 
            start: null,
            end: null,
            duration: null,
            seconds: null, 
            delayCodeId: null,
            code: null, 
            comments: null,
            batchNumber: null, 
        }, 
    });

    DelaysSimple.Collections.DelaySplits = Backbone.Collection.extend({
        model: DelaysSimple.Models.DelaySplit,
        initialize: function () {
        },
        comparator: function (a, b) {
            var prodItemA = a.get("productionItem");
            var prodItemB = b.get("productionItem");
            var startA = a.get("start");
            var startB = b.get("start");

            if (prodItemA == prodItemB) {
                if (startA > startB) return -1;
                else if (startA < startB) return 1;
                else return 0; 
            } else {
                if (prodItemA > prodItemB) return -1;
                else return 1; 
            }
        }, 
        fetch: function (e) {
            var that = this;
            var QP = new Core.Database.QueryParameters();

            var data = (e.data) ? e.data : {};

            QP.Add("Timezone", "VARCHAR", data["timezone"] ? data["timezone"] : null);

            Core.Json.CallProcedure(app.DatabaseNames.IHDelays + ".WebApp.GetLastDelays", QP, {
                onSuccess: function (data) {
                    if (data && data.Table) {
                        data = data.Table;

                        var delaySplitsModels = [];
                        for (var i = 0, len = data.length; i < len; i++) {

                            var delaySplit = data[i];
                            var delaySplitModel = new DelaysSimple.Models.DelaySplit({
                                id: delaySplit.Id,
                                delayId: delaySplit.Id,
                                parentId: delaySplit.ParentId,
                                line: delaySplit.Line,
                                productionItem: delaySplit.ProductionItem, 
                                start: new moment(delaySplit.Start).format("YYYY-MM-DD HH:mm"),
                                end: new moment(delaySplit.End).format("YYYY-MM-DD HH:mm"),
                                duration: delaySplit.Duration,
                                seconds: delaySplit.Seconds,
                                code: delaySplit.Code,
                                comments: delaySplit.Comments,
                                batchNumber: delaySplit.BatchNumber, 
                            });

                            delaySplitsModels.push(delaySplitModel);
                        }

                        that.set(delaySplitsModels, { from: "fetch" });

                        if (e && e.callback && _.isFunction(e.callback))
                            e.callback.call(that, that, data);

                    }
                },
                onError: function(){
                    if (e && e.callback && _.isFunction(e.callback))
                        e.callback.call(that, that, "error");
                }, 
                Secured: true, 
            }, app.ConnectionStrings.app);
        },
    });

    DelaysSimple.Views.Main = Backbone.View.extend({
        template: "delays-simple"
        , id: "delays-simple"
        , title: "DelaysSimple"
        //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.
        , isCacheable: false
        , initialize: function () {
            this.options.state = app.view_states.loading;
            this.options.onappend = (_.isFunction(this.options.onappend)) ? this.options.onappend : function () { };

            if (this.options.viewParams) {
            }

            var model = new DelaysSimple.Models.Main({
                delaySplits: new DelaysSimple.Collections.DelaySplits(), 
            });

            this.options.MYREFERENCES = {
                subviews: {
                }
                , autoRefresh: {
                    enabled: true
                    , toid: null
                }
            };

            this.model = model;

            this.bindEvents();
            _.bindAll(this);
        },

        events: {
        }, 

        render: function (container) {
            var that = this;
            var thatContainer = (container != null && container != undefined) ? container : this.options.container;
            //the screens have a custompath, so it has to be specified in the customPath variable that is
            //then sent to the template loader.
            var customPath = "/app/custom-screens/delays/delays-simple/";

            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;
                    that.$el.html(tmp());

                    var opt = {
                        showBatchNumber: false,
                    }; 

                    var columns = [
                        {
                            name: "line",
                            label: app.translate(that, "line_label"),
                            editable: false,
                            sortable: false,
                            cell: Backgrid.StringCell.extend({
                                orderSeparator: '',
                                className: "string-cell align-center-cell",
                            })
                        },
                        {
                            name: "productionItem",
                            label: app.translate(that, "machine_label"),
                            editable: false,
                            sortable: false,
                            cell: Backgrid.StringCell.extend({
                                orderSeparator: '',
                                className: "string-cell align-center-cell",
                            })
                        },
                        {
                            name: "start",
                            label: app.translate(that, "start_label"),
                            editable: false,
                            sortable: false,
                            cell: Backgrid.StringCell.extend({
                                orderSeparator: '',
                                className: "string-cell align-center-cell",
                            })
                        },
                        {
                            name: "end",
                            label: app.translate(that, "end_label"),
                            editable: false,
                            sortable: false,
                            cell: Backgrid.StringCell.extend({
                                orderSeparator: '',
                                className: "string-cell align-center-cell",
                            })
                        },
                        {
                            name: "duration",
                            label: app.translate(that, "duration_label"),
                            editable: false,
                            sortable: false,
                            cell: Backgrid.StringCell.extend({
                                orderSeparator: '',
                                className: "string-cell align-center-cell",
                            })
                        },
                        {
                            name: "batchNumber",
                            label: app.translate(that, "batchNumber_label"),
                            editable: false,
                            sortable: false,
                            renderable: opt.showBatchNumber, 
                            cell: Backgrid.StringCell.extend({
                                orderSeparator: '',
                                className: "string-cell align-center-cell",
                            })
                        }, 
                        {
                            name: "code",
                            label: app.translate(that, "code_label"),
                            editable: false,
                            sortable: false,
                            formatter: _.extend({}, Backgrid.CellFormatter.prototype, {
                                fromRaw: function (rawValue, model) {
                                    return (rawValue) ? app.translate(that, rawValue) : rawValue;
                                }
                            }),
                            cell: Backgrid.StringCell.extend({
                                orderSeparator: '',
                                className: "string-cell align-center-cell",
                            })
                        },
                    ]; 

                    var CustomRow = Backgrid.Row.extend({
                        events: {
                            "click": "onClick"
                        },
                        className: "clickeable-row",
                        onClick: function (e) {
                            var target = $(e.target); 
                            var data_prevent = (target.closest("[data-preventclick]").length > 0) ? target.closest("[data-preventclick]").data("preventclick") : false; 

                            if (!data_prevent) {
                                that.showDelayInfoModal(this.model); 
                            }
                        }
                    });

                    // Initialize a new Grid instance
                    var delays_grid;
                    delays_grid = new Backgrid.Grid({
                        row: CustomRow, 
                        className: "backgrid table table-hover",
                        columns: columns,
                        collection: that.model.get("delaySplits"),
                    });

                    that.$el.find(".delays-grid-container").append(delays_grid.render().el);

                    that.append(thatContainer, that.$el);

                    that._startAutoRefresh({ showLoading: true });
                }, true, customPath);
            }, customPath, "main_template");
        }

        , showDelayInfoModal: function (m) {
            var delayinfomodal = new DelaysSimple.Views.DelayInformationModal({
                viewParams: {
                    rowData: {
                        id: m.get("delayId"),
                        model: m,
                    },
                }
            });

            //calling grid refresh as soon as the modal is hidden in case
            //any changes were made.
            delayinfomodal.on("hidden", this._autoRefresh); 

            delayinfomodal.show();
        }

        , _startAutoRefresh: function (opt) {
            try {
                if (this.options.MYREFERENCES.autoRefresh.toid != null) {
                    clearTimeout(this.options.MYREFERENCES.autoRefresh.toid);
                    this.options.MYREFERENCES.autoRefresh.toid = null;
                }

                this.options.MYREFERENCES.autoRefresh.enabled = true;

                this._autoRefresh(opt);
            } catch (Error) { }
        }

        , _autoRefresh: function (opt) {
            var that = this; 
            if (this.options.MYREFERENCES.autoRefresh.toid != null) {
                clearTimeout(this.options.MYREFERENCES.autoRefresh.toid);
                this.options.MYREFERENCES.autoRefresh.toid = null;
            }

            this.refresh(_.extend({}, opt, {
                callback: function () {
                    if (that.options.MYREFERENCES.autoRefresh.enabled == true) {
                        that.options.MYREFERENCES.autoRefresh.toid = setTimeout(that._autoRefresh, 5000);
                    }
                }, 
            }));
        }

        , _stopAutoRefresh: function () {
            if (this.options.MYREFERENCES.autoRefresh.toid != null) {
                clearTimeout(this.options.MYREFERENCES.autoRefresh.toid);
                this.options.MYREFERENCES.autoRefresh.toid = null;
            }
            this.options.MYREFERENCES.autoRefresh.enabled = false;
        }

        , refresh: function (opt) {
            try {
                var that = this;
                var fetched = false; 

                if (opt && opt.showLoading) {
                    setTimeout(function () {
                        if (!fetched) that.showLoading(true);
                    }, 500);
                }

                this.model.get("delaySplits").fetch({
                    data: {
                        timezone: app.models.user.get("timezoneCode"),
                    },
                    callback: function () {
                        fetched = true; 
                        that.showLoading(false);

                        if (opt && opt.callback && _.isFunction(opt.callback))
                            opt.callback.call(that, that); 
                    }, 
                });
            } catch (Error) { }
        }

        , showLoading: function (val) {
            var loadingPoster = this.$el.find(".loading-poster"); 
            var gridContainer = this.$el.find(".delays-grid-container"); 
            
            if (val) {
                gridContainer.addClass("hide");
                loadingPoster.removeClass("hide");
            } else {
                loadingPoster.addClass("hide");
                gridContainer.removeClass("hide"); 
            }
        }

        , append: function (container, el) {
            el = (el != null && el != undefined) ? el : this.$el;

            if (this.options.state == app.view_states.loading
                || this.options.state == app.view_states.shown) {
                //appending view to the main container and set state to shown

                this.options.state = app.view_states.shown;
                container.append(el);

                this.options.onappend(this);
            }

            if (this.options.state == app.view_states.hidden) {
                //append and remain hidden
                container.append(el);
            }

            if (this.options.state == app.view_states.closed) {
                //return without appending.
                return;
            }
        }

        , bindEvents: function () {
            //this function should be in every view that uses listenTo anywhere
            //all the model bindings or view-model binding should be here, to manage
            //the show/hide view easily
            var that = this; 
        }

        , bindViewScopedEvents: function () {
            var that = this; 
        }

        , unbindViewScopedEvents: function () {

        }

        , close: function () {
            this.options.state = app.view_states.closed;
            this._stopAutoRefresh(); 
            this.closeSubviews(); 
            this.remove();
            this.unbindViewScopedEvents();
            this.unbind();
        }

        , closeSubviews: function () {
            _.each(this.options.MYREFERENCES.subviews, function (sview) {
                sview.close();
            });
        }

        , show: function () {
            this.options.state = app.view_states.shown;

            this.showSubviews(); 
            this.bindEvents();
            this.$el.show();
        }

        , showSubviews: function () {
            _.each(this.options.MYREFERENCES.subviews, function (sview) {
                sview.show();
            });
        }

        , hide: function () {
            this.options.state = app.view_states.hidden;

            this.hideSubviews();
            this._stopAutoRefresh(); 

            this.$el.hide();
            this.unbind();
            this.stopListening();
        }

        , hideSubviews: function () {
            _.each(this.options.MYREFERENCES.subviews, function (sview) {
                sview.hide();
            });
        }

        , preRender: function () {
            app.models.subnavbar.set("subnavbar", false);
            app.models.subnavbar.setAll(false);
        }

        , reRender: function () {
            this._startAutoRefresh(); 
        }
    });

    //DelaysSimple.Models.DelaySplitInformationModal = Backbone.Model.extend({
    //    defaults: {
    //        delayId: null,
    //        parentId: null,
    //        line: null,
    //        productionItem: null,
    //        start: null,
    //        end: null,
    //        duration: null,
    //        delayCodeId: null,
    //        comments: null,
    //        delayCodes: null, 
    //    },
    //    initialize: function () {
    //        this.options = {
    //            fetched: false, 
    //        }; 
    //    },
    //    fetch: function (delayId) {
    //        var that = this;
    //        var QP = new Core.Database.QueryParameters();
    //        QP.Add("DelayID", "INT", delayId);
    //        QP.Add("Timezone", "VARCHAR", app.models.user.get("timezoneCode")); 

    //        Core.Json.CallProcedure(app.DatabaseNames.IHDelays + ".WebApp.GetDelayData", QP, {
    //            onSuccess: function (data) {
    //                if (data && data.Table && data.Table.length > 0) {
    //                    var delayCodes = data.Table1;

    //                    var delayCodeItems = {}; 
    //                    for (var i = 0; i < delayCodes.length; i++) {
    //                        var item = {
    //                            description: delayCodes[i].Description,
    //                            delayCodeId: delayCodes[i].DelayCodeID,
    //                            parentId: delayCodes[i].ParentID, 
    //                            children: null, 
    //                        }

    //                        if (item.parentId) {
    //                            if (!delayCodeItems[item.parentId].children) delayCodeItems[item.parentId].children = {};
    //                            delayCodeItems[item.parentId].children[item.delayCodeId] = item;
    //                        }
    //                        else delayCodeItems[item.delayCodeId] = item;
    //                    }

    //                    that.set("delayCodes", delayCodeItems, { silent: true }); 

    //                    data = data.Table[0];

    //                    var values = _.extend({}, that.attributes, {
    //                        delayId: data.DelayId,
    //                        parentId: data.ParentId,
    //                        line: data.Line,
    //                        productionItem: data.ProductionItem,
    //                        start: data.Start,
    //                        end: data.End,
    //                        duration: data.Duration,
    //                        delayCodeId: data.DelayCodeID,
    //                        comments: data.Comments,
    //                    });

    //                    that.options.fetched = true; 
    //                    that.set(values);
    //                }
    //            },
    //            Secured: true, 
    //        }, app.ConnectionStrings.app);
    //    },
    //});

    //DelaysSimple.Views.DelaySplitInformationModal = Backbone.View.extend({
    //    template: "delays-simple"
    //    , id: "delays-simple"
    //    , title: ""
    //    , className: "modal hide fade modal-wider"
    //    //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.
    //    , isCacheable: true
    //    , initialize: function () {

    //        this.options.MYREFERENCES = {
    //            autoRefresh: {
    //                enabled: true
    //                , toid: null
    //            },
    //            rowData: null,
    //        };

    //        if (this.options.viewParams) {
    //            this.options.MYREFERENCES.rowData = this.options.viewParams.rowData;
    //        }

    //        this.options._isRendered = false;

    //        this.model = new DelaysSimple.Models.DelaySplitInformationModal();

    //        this.bindEvents();
    //        _.bindAll(this);
    //    },
    //    events: {
    //        'click .close': function (event) {
    //            event.preventDefault();

    //            this.trigger('cancel');

    //            if (this.options.content && this.options.content.trigger) {
    //                this.options.content.trigger('cancel', this);
    //            }
    //        }
    //        , "click .btn-cancel": function (event) {
    //            event.preventDefault();

    //            this.trigger('cancel');

    //            if (this.options.content && this.options.content.trigger) {
    //                this.options.content.trigger('cancel', this);
    //            }
    //        }
    //        , "click .btn-save": function (event) {
    //            event.preventDefault();
    //            this.save(); 
    //        }
    //        , "change .delaycodes-select": "delayCode_changed"
    //    },

    //    render: function (container) {
    //        var that = this;
    //        var thatContainer = container;

    //        //the screens have a custompath, so it has to be specified in the customPath variable that is
    //        //then sent to the template loader.
    //        var customPath = "/app/custom-screens/delays/delays-simple/";

    //        if (this.model.get("delayId")) {
    //            T.render.call(this, this.template, function (tmp) {

    //                if (!that.options.i18n) that.options.i18n = {};
    //                app.getI18NJed(that, that.template, function (i18nJED) {
    //                    //storing internationalization data
    //                    that.options.i18n[that.template] = i18nJED;

    //                    var delayCodesSelect = [];
    //                    (function _parseDelayCodesOptions(dict, values, description) {
    //                        for (var i in dict) {
    //                            var t = dict[i];
    //                            if (t.children != null) {
    //                                _parseDelayCodesOptions(t.children, values
    //                                    , (description != null) ? description + ' > ' + t.description : t.description
    //                                );
    //                            } else {
    //                                values.push({
    //                                    value: t.delayCodeId,
    //                                    label: (description != null) ? description + ' > ' + t.description : t.description
    //                                });
    //                            }
    //                        }
    //                    })(that.model.get("delayCodes"), delayCodesSelect, null);

    //                    var startMoment = moment(that.model.get("start"), "YYYY-MM-DD HH:mm:ss"); 
    //                    var endMoment = moment(that.model.get("end"), "YYYY-MM-DD HH:mm:ss");

    //                    //loading the view and appeding it to the views's $el.
    //                    that.$el.html(tmp(_.extend(that.model.toJSON(), {
    //                        delayCodesSelect: delayCodesSelect,
    //                        durationText: that.secondsToHHMMSS(that.model.get("duration")),
    //                        startDate: startMoment.format("YYYY-MM-DD"),
    //                        endDate: endMoment.format("YYYY-MM-DD"),
    //                        startTime: startMoment.format("HH:mm:ss"),
    //                        endTime: endMoment.format("HH:mm:ss"),
    //                    })));
                        
    //                }, true, customPath);

    //            }, customPath, "delay_split_info_modal_template");
    //        } else {
    //            setTimeout(function () {
    //                T.render.call(that, that.template, function (tmp) {
    //                    if (!that.model.get("delayId")) {
    //                        that.$el.html(tmp());
    //                    }
    //                }, customPath, "delay_split_info_modal_loading");
    //            }, 500); 
    //        }

    //        that.options._isRendered = true;
    //        that.refresh(); 
    //    }

    //    , secondsToHHMMSS: function (d) {
    //        d = Number(d);
    //        var h = Math.floor(d / 3600);
    //        var m = Math.floor(d % 3600 / 60);
    //        var s = Math.floor(d % 3600 % 60);
    //        return ((h > 0 ? h + " h " : "") + m + " min " + ((s > 0) ? s + " seg" : ""));
    //    }

    //    , delayCode_changed: function (e) {
    //        var el = $(e.target);
    //        var new_delayCodeId = parseInt(el.val());

    //        this.model.set("delayCodeId", new_delayCodeId, { silent: true }); 
    //    }

    //    , save: function () {
    //        var that = this;
    //        var QP = new Core.Database.QueryParameters();

    //        var model = this.model; 
    //        QP.Add("Id", "INT", model.get("delayId"));
    //        QP.Add("DelayCodeID", "INT", model.get("delayCodeId"));

    //        app.CallProcedure(app.DatabaseNames.IHDelays + ".WebApp.SetDelayCode", QP, {
    //            onSuccess: function (data) {
    //                that.hide(); 
    //            },
    //            Secured: true, 
    //        }, app.ConnectionStrings.app);
    //    }

    //    , refresh: function () {
    //        try {
    //            this.model.fetch(this.options.MYREFERENCES.rowData.id);
    //        } catch (Error) { }
    //    }

    //    , _startAutoRefresh: function () {
    //        try {
    //            if (this.options.MYREFERENCES.autoRefresh.toid != null) {
    //                clearTimeout(this.options.MYREFERENCES.autoRefresh.toid);
    //                this.options.MYREFERENCES.autoRefresh.toid = null;
    //            }

    //            this.options.MYREFERENCES.autoRefresh.enabled = true;

    //            this._autoRefresh();
    //        } catch (Error) { }
    //    }

    //    , _autoRefresh: function () {
    //        if (this.options.MYREFERENCES.autoRefresh.toid != null) {
    //            clearTimeout(this.options.MYREFERENCES.autoRefresh.toid);
    //            this.options.MYREFERENCES.autoRefresh.toid = null;
    //        }

    //        this.refresh();

    //        if (this.options.MYREFERENCES.autoRefresh.enabled == true) {
    //            this.options.MYREFERENCES.autoRefresh.toid = setTimeout(this._autoRefresh, 3000);
    //        }
    //    }

    //    , _stopAutoRefresh: function () {
    //        if (this.options.MYREFERENCES.autoRefresh.toid != null) {
    //            clearTimeout(this.options.MYREFERENCES.autoRefresh.toid);
    //            this.options.MYREFERENCES.autoRefresh.toid = null;
    //        }
    //        this.options.MYREFERENCES.autoRefresh.enabled = false;
    //    }
    //    , show: function () {

    //        if (!this.options._isRendered) {
    //            this.render();
    //            setTimeout(this.show, 100);
    //            return;
    //        }

    //        var self = this,
    //        $el = this.$el;

    //        //creating modal
    //        $el.modal({
    //            keyboard: false
    //            , backdrop: "static"
    //        });

    //        $backdrop = $('.modal-backdrop');

    //        $backdrop.one('click', function () {
    //            if (self.options.content && self.options.content.trigger) {
    //                self.options.content.trigger('cancel', self);
    //            }

    //            self.trigger('cancel');
    //        });

    //        $(document).one('keyup.dismiss.modal', function (e) {
    //            e.which == 27 && self.trigger('cancel');

    //            if (self.options.content && self.options.content.trigger) {
    //                e.which == 27 && self.options.content.trigger('shown', self);
    //            }
    //        });

    //        this.on('cancel', function () {
    //            self.hide();
    //        });

    //        return this;

    //    }
    //    , hide: function () {
    //        var self = this,
    //        $el = this.$el;

    //        $el.one('hidden', function onHidden(e) {
    //            // Ignore events propagated from interior objects, like bootstrap tooltips
    //            if (e.target !== e.currentTarget) {
    //                return $el.one('hidden', onHidden);
    //            }

    //            if (self.options.content && self.options.content.trigger) {
    //                self.options.content.trigger('hidden', self);
    //            }

    //            self.trigger('hidden');

    //            self.close();
    //        });

    //        $el.modal('hide');
    //    }
    //    , bindEvents: function () {
    //        //this function should be in every view that uses listenTo anywhere
    //        //all the model bindings or view-model binding should be here, to manage
    //        //the show/hide view easily

    //        //rendering as soon as getting data in the model
    //        this.listenTo(this.model, "change", this.render);
    //    }

    //    , close: function () {
    //        this._stopAutoRefresh();
    //        this.remove();
    //        this.unbind();
    //    }

    //    , preRender: function () {
    //    }

    //    , reRender: function () {
    //    }
    //});

    DelaysSimple.Models.DelayInformationModal = Backbone.Model.extend({
        defaults: {
            delayId: null,
            parentId: null,
            line: null,
            productionItem: null,
            start: null,
            end: null,
            duration: null,
            delayCodeId: null,
            comments: null,
            batchNumber: null, 

            delayCodes: null,
        },
        initialize: function () {
            this.options = {
                fetched: false,
            };
        },
        fetch: function (delayId) {
            var that = this;
            var QP = new Core.Database.QueryParameters();
            QP.Add("DelayID", "INT", delayId);
            QP.Add("Timezone", "VARCHAR", app.models.user.get("timezoneCode"));

            Core.Json.CallProcedure(app.DatabaseNames.IHDelays + ".WebApp.GetDelayData", QP, {
                onSuccess: function (data) {
                    if (data && data.Table && data.Table.length > 0) {
                        var delayCodes = data.Table1;

                        var delayCodeItems = {};
                        for (var i = 0; i < delayCodes.length; i++) {
                            var item = {
                                description: delayCodes[i].Description,
                                delayCodeId: delayCodes[i].DelayCodeID,
                                parentId: delayCodes[i].ParentID,
                                //color: delayCodes[i].Color,
                                children: null,
                            }

                            if (item.parentId) {
                                if (!delayCodeItems[item.parentId].children) delayCodeItems[item.parentId].children = {};
                                delayCodeItems[item.parentId].children[item.delayCodeId] = item;
                            }
                            else delayCodeItems[item.delayCodeId] = item;
                        }

                        that.set("delayCodes", delayCodeItems, { silent: true });

                        data = data.Table[0];

                        var values = _.extend({}, that.attributes, {
                            delayId: data.DelayId,
                            parentId: data.ParentId,
                            line: data.Line,
                            productionItem: data.ProductionItem,
                            start: data.Start,
                            end: data.End,
                            duration: data.Duration,
                            delayCodeId: data.DelayCodeID,
                            comments: data.Comments,
                            batchNumber: data.BatchNumber, 
                        });

                        that.options.fetched = true;
                        that.set(values);
                    }
                },
                Secured: true,
            }, app.ConnectionStrings.app);
        },
    });

    DelaysSimple.Views.DelayInformationModal = Backbone.View.extend({
        template: "delays-simple"
        , id: "delays-simple"
        , title: ""
        , className: "modal hide fade modal-wider"
        //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.
        , isCacheable: true
        , initialize: function () {

            this.options.MYREFERENCES = {
                autoRefresh: {
                    enabled: true
                    , toid: null
                },
                rowData: null,
            };

            if (this.options.viewParams) {
                this.options.MYREFERENCES.rowData = this.options.viewParams.rowData;
            }

            this.options.currentPage = 0;
            this.options.totalPages = 0;

            this.options._isRendering = false;
            this.options._isRendered = false;

            this.model = new DelaysSimple.Models.DelayInformationModal();

            this.bindEvents();
            _.bindAll(this);
        },
        events: {
            'click .close': function (event) {
                event.preventDefault();

                this.trigger('cancel');

                if (this.options.content && this.options.content.trigger) {
                    this.options.content.trigger('cancel', this);
                }
            }
            , 'click .btn-close': function (event) {
                event.preventDefault();

                this.trigger('cancel');

                if (this.options.content && this.options.content.trigger) {
                    this.options.content.trigger('cancel', this);
                }
            }
            , "click .btn-cancel": function (event) {
                event.preventDefault();

                this.trigger('cancel');

                if (this.options.content && this.options.content.trigger) {
                    this.options.content.trigger('cancel', this);
                }
            }
            , "click .btn-save": function (event) {
                event.preventDefault();
                this.save();
            }
            , "click .btn-arrow-left": function () {
                this.movePage('LEFT');
            }
            , "click .btn-arrow-right": function () {
                this.movePage('RIGHT');
            }
            , "click .btn-delay-code": "delayCodeBtn_clicked"
        },

        render: function (container) {
            var that = this;
            var thatContainer = container;

            //the screens have a custompath, so it has to be specified in the customPath variable that is
            //then sent to the template loader.
            var customPath = "/app/custom-screens/delays/delays-simple/";

            if (this.model.get("delayId")) {
                T.render.call(this, this.template, function (tmp) {
                    if (!that.options.i18n) that.options.i18n = {};
                    app.getI18NJed(that, that.template, function (i18nJED) {
                        //storing internationalization data
                        that.options.i18n[that.template] = i18nJED;

                        var delayCodesSelect = [];
                        (function _parseDelayCodesOptions(dict, values, description) {
                            for (var i in dict) {
                                var t = dict[i];
                                if (t.children != null) {
                                    _parseDelayCodesOptions(t.children, values
                                        , (description != null) ? description + ' > ' + t.description : t.description
                                    );
                                } else {
                                    values.push({
                                        value: t.delayCodeId,
                                        label: (description != null) ? description + ' > ' + t.description : t.description
                                    });
                                }
                            }
                        })(that.model.get("delayCodes"), delayCodesSelect, null);

                        var ipp = 9; //itemsPerPage
                        var ipr = 3; //itemsPerRow
                        var pages = [];

                        //sorting delay codes alphabetically
                        delayCodesSelect = _.sortBy(delayCodesSelect, 'label');

                        _.each(delayCodesSelect, function (obj, inx) {
                            var page = Math.floor(inx / ipp);
                            var pageo;
                            if (!(pageo = pages[page])) {
                                pageo = { pageNum: page, rows: [] };
                                pages.push(pageo);
                            }

                            var row = (pageo.rows.length > 0) ? pageo.rows[pageo.rows.length - 1] : null;
                            if (!row || row.columns.length >= ipr) {
                                row = { columns: [], };
                                pageo.rows.push(row);
                            }

                            row.columns.push({
                                text: obj.label,
                                id: obj.value,
                            });
                        });

                        var startMoment = moment(that.model.get("start"), "YYYY-MM-DD HH:mm:ss");
                        var endMoment = moment(that.model.get("end"), "YYYY-MM-DD HH:mm:ss");

                        //loading the view and appeding it to the views's $el.
                        that.$el.html(tmp(_.extend(
                            that.model.toJSON(),
                            DelaysSimple.Config,
                            {
                                pages: pages,
                                durationText: that.secondsToHHMMSS(that.model.get("duration")),
                                startDate: startMoment.format("YYYY-MM-DD"),
                                endDate: endMoment.format("YYYY-MM-DD"),
                                startTime: startMoment.format("HH:mm:ss"),
                                endTime: endMoment.format("HH:mm:ss"),
                            }
                        )));

                        //var dcodes = that.model.get("delayCodes");                        
                        //that.$el.find(".btn-delay-code").each(function (inx, o) {
                        //    o = $(o);
                        //    var dcid = o.data("id");
                        //    var dcat = _.find(dcodes, function (obj) {
                        //        return _.isObject(_.findWhere(obj.children, { delayCodeId: dcid })); 
                        //    });

                        //    if (dcat && dcat.color) {
                        //        o.css({
                        //            "border-top-color": dcat.color,
                        //            "border-bottom-color": dcat.color,
                        //            "border-left-color": dcat.color,
                        //            "border-right-color": dcat.color,
                        //            "border-width": "2px",
                        //            "border-style": "solid"
                        //        }); 
                        //    }
                        //}); 

                        that.options.currentPage = 0;
                        that.options.totalPages = pages.length;
                        that.movePage();
                    }, true, customPath);
                }, customPath, "delay_info_modal_template");
            } else {
                setTimeout(function () {
                    T.render.call(that, that.template, function (tmp) {
                        if (!that.model.get("delayId")) {
                            that.$el.html(tmp());
                        }
                    }, customPath, "delay_info_modal_template_loading");
                }, 500);
            }

            that.options._isRendered = true;
            that.refresh();
        }

        , movePage: function (direction) {
            var leftArrow = this.$el.find(".btn-arrow-left");
            var rightArrow = this.$el.find(".btn-arrow-right");
            var currentPage = this.options.currentPage;

            if (direction == 'LEFT') currentPage--;
            else if (direction == 'RIGHT') currentPage++;

            var pages = this.$el.find('*[data-pagenum]');
            pages.addClass("hide");

            this.$el.find('*[data-pagenum="' + currentPage + '"]').removeClass("hide");

            this.options.currentPage = currentPage;

            leftArrow.attr("disabled", false); rightArrow.attr("disabled", false);
            if (currentPage == 0) leftArrow.attr("disabled", true);
            if (currentPage == this.options.totalPages - 1) rightArrow.attr("disabled", true);
        }

        , delayCodeBtn_clicked: function (e) {
            var btn = $(e.target);
            var delaycodeid = btn.data("id");

            if (delaycodeid) {
                this.setDelayCode(delaycodeid);
            }
        }

        , setDelayCode: function (dcid) {
            var that = this;
            var QP = new Core.Database.QueryParameters();

            var model = this.model;
            QP.Add("Id", "INT", model.get("delayId"));
            QP.Add("DelayCodeID", "INT", dcid);

            app.CallProcedure(app.DatabaseNames.IHDelays + ".WebApp.SetDelayCode", QP, {
                onSuccess: function (data) {
                    that.hide();
                },
                Secured: true,
            }, app.ConnectionStrings.app);
        }

        , secondsToHHMMSS: function (d) {
            d = Number(d);
            var h = Math.floor(d / 3600);
            var m = Math.floor(d % 3600 / 60);
            var s = Math.floor(d % 3600 % 60);
            return ((h > 0 ? h + " h " : "") + m + " min " + ((s > 0) ? s + " seg" : ""));
        }

        , delayCode_changed: function (e) {
            var el = $(e.target);
            var new_delayCodeId = parseInt(el.val());

            this.model.set("delayCodeId", new_delayCodeId, { silent: true });
        }

        , save: function () {
            var that = this;
            var QP = new Core.Database.QueryParameters();

            var model = this.model;
            QP.Add("Id", "INT", model.get("delayId"));
            QP.Add("DelayCodeID", "INT", model.get("delayCodeId"));

            app.CallProcedure(app.DatabaseNames.IHDelays + ".WebApp.SetDelayCode", QP, {
                onSuccess: function (data) {
                    that.hide();
                },
                Secured: true,
            }, app.ConnectionStrings.app);
        }

        , refresh: function () {
            try {
                this.model.fetch(this.options.MYREFERENCES.rowData.id);
            } catch (Error) { }
        }
        , show: function () {

            if (!this.options._isRendered) {
                this.render();
                setTimeout(this.show, 100);
                return;
            }

            var self = this,
            $el = this.$el;

            //creating modal
            $el.modal({
                keyboard: false
                , backdrop: "static"
            });

            $backdrop = $('.modal-backdrop');

            $backdrop.one('click', function () {
                if (self.options.content && self.options.content.trigger) {
                    self.options.content.trigger('cancel', self);
                }

                self.trigger('cancel');
            });

            $(document).one('keyup.dismiss.modal', function (e) {
                e.which == 27 && self.trigger('cancel');

                if (self.options.content && self.options.content.trigger) {
                    e.which == 27 && self.options.content.trigger('shown', self);
                }
            });

            this.on('cancel', function () {
                self.hide();
            });

            return this;

        }
        , hide: function () {
            var self = this,
            $el = this.$el;

            $el.one('hidden', function onHidden(e) {
                // Ignore events propagated from interior objects, like bootstrap tooltips
                if (e.target !== e.currentTarget) {
                    return $el.one('hidden', onHidden);
                }

                if (self.options.content && self.options.content.trigger) {
                    self.options.content.trigger('hidden', self);
                }

                self.trigger('hidden');

                self.close();
            });

            $el.modal('hide');
        }
        , bindEvents: function () {
            //this function should be in every view that uses listenTo anywhere
            //all the model bindings or view-model binding should be here, to manage
            //the show/hide view easily

            //rendering as soon as getting data in the model
            this.listenTo(this.model, "change", this.render);
        }
        , close: function () {
            this.remove();
            this.unbind();
        }

        , preRender: function () {
        }

        , reRender: function () {
        }
    });

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

});

