/*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.licenseRequestEdit = (function () {
    'use strict';
    //---------------- BEGIN MODULE SCOPE VARIABLES --------------
    var
        stateMap = {},
        onSend, onCancel, onRegenerate, configModule, initModule;
    //----------------- END MODULE SCOPE VARIABLES ---------------

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

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

    ////////////////////
    //
    onSend = function (event) {

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

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

        app.api.licenseEmailResponse(submitData, function (res) {
            if (res.error) {
                $.gevent.publish('app-show-error',res.msg);
            } else {
                //navigate back to licenseRequests
                //alert("key has been sent!");
                window.location.href = "#!/inbox/";

                //$('#key').val(res);
                return false;
            }
        });

        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.licenseRequestEdit']({}));       
        ////app.nav.setContextTitle("Request");  

        //Append key hidden values for submit and processing by server
        //This is set from the original click to open this form
        $('<input />').attr('type', 'hidden')
            .attr('name', "request_email_uid")
            .attr('value', stateMap.id)
            .appendTo('#frm');

        //These are empty but will be filled in when the server responds with the "record"
        //They are for re-submission back to the server to save a step of refetching the original info
        //and recalculating stuff that was already done

        $('<input />').attr('type', 'hidden')
            .attr('name', "requestReplyToAddress")
            .attr('value', '')
            .appendTo('#frm');

        $('<input />').attr('type', 'hidden')
            .attr('name', "requestFromReplySubject")
            .attr('value', '')
            .appendTo('#frm');

        //rfcore unused?
        $('<input />').attr('type', 'hidden')
            .attr('name', "greetingReplySubject")
            .attr('value', '')
            .appendTo('#frm');

        $('<input />').attr('type', 'hidden')
            .attr('name', "requestFromReplySubject")
            .attr('value', '')
            .appendTo('#frm');




        //fetch existing record
        app.api.generateFromRequest(stateMap.id, function (res) {
            if (res.error) {
                $.gevent.publish('app-show-error',res.msg);
            } else {
                //fill out form
                app.utilB.formData(res);
            }
        });

        //Context menu           
        app.nav.contextClear();
        app.nav.contextAddButton('btn-generate', 'Send', 'send', onSend);
        app.nav.contextAddLink("inbox/", "Inbox", "inbox");



    };




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