/*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.license_templates = (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();
        $('#app-error-message').text('');
        //get form data
        var formData = $("form").serializeArray({
            checkboxesAsBools: true
        });

        var submitData = app.util_b.objectifyFormDataArray(formData);


        //TODO: change this to use the UPSERT api route method


        app.api.upsert('license_templates', submitData, function (res) {
            if (res.error) {
                $('#app-error-message').text(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.license_templates']({}));

        //fetch existing record
        app.api.get('license_templates', '', function (res) {
            if (res.error) {
                $('#app-error-message').text(res.msg);
            } else {
                //fill out form
                app.util_b.formData(res);
            }
        });


        //set title 
        $("#app-form-title").text("License message templates");

        // bind actions
        $('#btn-save').bind('click', onSave);

        //make context menu
        $(".app-context-nav").append('<li><a href="#!/license/">Back</a></li>');
    };


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