/*jslint         browser : true, continue : true,
  devel  : true, indent  : 2,    maxerr   : 50,
  newcap : true, nomen   : true, plusplus : true,
  regexp : true, sloppy  : true, vars     : false,
  white  : true
*/

/*global $, app */

app.licenseTemplates = (function () {

    'use strict';
    //---------------- BEGIN MODULE SCOPE VARIABLES --------------
    var
        stateMap = {},
        onSave, configModule, initModule;
    //----------------- END MODULE SCOPE VARIABLES ---------------

    //------------------- BEGIN UTILITY METHODS ------------------
    //-------------------- END UTILITY METHODS -------------------

    //------------------- BEGIN EVENT HANDLERS -------------------


    //different than the other edit routes because it's global and there is only one
    //so no ID
    onSave = function (event) {

        event.preventDefault();
        $.gevent.publish('app-clear-error');
        //get form data
        var formData = $("form").serializeArray({
            checkboxesAsBools: true
        });

        var submitData = app.utilB.objectifyFormDataArray(formData);
        submitData["id"] = '1';

        app.api.update('licenseTemplates', submitData, function (res) {
            if (res.error) {
                $.gevent.publish('app-show-error',res.msg);
            }
        });

        return false; //prevent default
    };




    //-------------------- END EVENT HANDLERS --------------------

    //------------------- BEGIN PUBLIC METHODS -------------------
    //CONFIGMODULE
    //
    configModule = function (context) {
        stateMap.context = context.context;
        // if (stateMap.context.params.id) {
        //     stateMap.id = stateMap.context.params.id;
        // }
    };

    //INITMODULE
    //
    initModule = function ($container) {
        if (typeof $container === 'undefined') {
            $container = $('#app-shell-main-content');
        }

        $container.html(Handlebars.templates['app.licenseTemplates']({}));

        //fetch existing record
        //Note license templates record id is always 1 as there is only ever one record in db
        app.api.get('licenseTemplates/' + '1', function (res) {
            if (res.error) {
                $.gevent.publish('app-show-error',res.msg);
            } else {
                //fill out form
                app.utilB.formData(res);
            }
        });

        //set title 
        // var title = "License message templates";
        // //app.nav.setContextTitle(title);

        // bind actions
        $('#btn-save').bind('click', onSave);
        
        //Context menu           
        app.nav.contextClear();
        app.nav.contextAddLink("license/", "License", "key");
    };


    // return public methods
    return {
        configModule: configModule,
        initModule: initModule
    };
    //------------------- END PUBLIC METHODS ---------------------
}());