/*
  backgrid-time-cell 1.0.0
*/
(function (root, factory) {

  if (typeof define === 'function' && define.amd) {
    // AMD
    define(["underscore", "backgrid", "moment"], factory);
  } else if (typeof exports === 'object') {
    // CommonJS
    module.exports = factory(require("underscore"), require("backgrid"),
                             require("moment"));
  } else {
    // Browser globals
    factory(root._, root.Backgrid, root.moment);
  }

}(this, function (_, Backgrid, moment) {

    //Fix require config issue with Underscore.
    if (!_)
        _ = this._;

    Backgrid.Extension.TimeCellEditor = Backgrid.InputCellEditor.extend({
        timeFormat: 'H:i:s',
        typeaheadHighlight: false,
        scrollDefault: 'now',

        render: function () {
            var that = this;
            var model = this.model;

            //Get picker options
            var pickerOpt = {};

            _.each($.fn.jqtimepicker.defaults, function (value, key) { pickerOpt[key] = that[key]; });

            this.$el.jqtimepicker(pickerOpt);

            this.$el.bind("change", _.bind(this.save, this));
            this.$el.bind("hideTimepicker", _.bind(this.edited, this));

            var cm = moment(this.formatter.fromRaw(model.get(this.column.get("name")), model), "HH:mm:ss.SSS");

            if (cm.isValid())
                this.$el.jqtimepicker('setTime', cm.toDate());

            return this;
        },
        save: function (e) {
            var formatter = this.formatter;
            var model = this.model;
            var column = this.column;

            var command = new Backgrid.Command(e);
            var blurred = e.type === "blur";

            e.preventDefault();
            e.stopPropagation();

            var val = this.$el.jqtimepicker('getTime');
            val = moment(val).format("HH:mm:ss.SSS");

            var newValue = formatter.toRaw(val, model);

            if (_.isUndefined(newValue)) {
                model.trigger("backgrid:error", model, column, val);
            }
            else {
                model.set(column.get("name"), newValue);
                model.trigger("backgrid:edited", model, column, command);
            }
        },
        edited: function (e) {
            var model = this.model;
            var column = this.column;

            var command = new Backgrid.Command(e);

            // undo
            e.stopPropagation();
            model.trigger("backgrid:edited", model, column, command);
        },
    });

    Backgrid.Extension.DatetimeToTimeFormatter = DatetimeToTimeFormatter = function (options) { };
    DatetimeToTimeFormatter.prototype = new Backgrid.CellFormatter;
    _.extend(DatetimeToTimeFormatter.prototype, {
        columnName: null,
        displayFormat: 'HH:mm:ss',
        modelDateFormat: 'YYYY-MM-DD',
        modelTimeFormat: 'HH:mm:ss.SSS',
        modelFormat: 'YYYY-MM-DD HH:mm:ss.SSS',

        fromRaw: function (rawData) {
            if (rawData == null) return '';

            var m = new moment(rawData, this.modelFormat);

            return m.format(this.displayFormat);
        },
        toRaw: function (formattedData, model) {
            var value = model.get(this.columnName),
                date,
                time = new moment(formattedData, this.displayFormat).format(this.modelTimeFormat);

            date = (value)
                    ? new moment(value, this.modelFormat).format(this.modelDateFormat)
                    : new moment().format(this.modelDateFormat);

            return date + ' ' + time;
        },
    });
    DatetimeToTimeFormatter.extend = Backbone.Model.extend;
}));
