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

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

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

    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);


        //is this a new record?
        if (stateMap.id != 'new') {
            //put id into the form data
            submitData._id = stateMap.id;

            app.api.update('incident', submitData, function(res) {
                if (res.error) {
                    $('#app-error-message').text(res.msg);
                }
            });
        } else {
            //create new record
            app.api.create('incident', submitData, function(res) {
                if (res.error) {
                    $('#app-error-message').text(res.msg);
                } else {
                    page('#!/incident_edit/' + res.insertedId + '/' + stateMap.context.params.site_id);
                    return false;
                }
            });
        }
        return false; //prevent default
    };


    //ONDELETE
    //
    onDelete = function(event) {
        event.preventDefault();
        $('#app-error-message').text('');

        var r = confirm("Are you sure you want to delete this record?");
        if (r == true) {

            //====  DELETE  ====
            app.api.deleteOne('incident', stateMap.id, function(res) {
                if (res.error) {
                    $('#app-error-message').text(res.msg);
                } else {
                    //deleted, return to master list
                    page('#!/incidents/' + stateMap.context.params.site_id);
                    return false;
                }
            });
        } else {
            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.incident_edit']({}));
        var title = "incident";

        if (!stateMap.context.params.site_id) {
            throw ('app.incident_edit.js::initModule - There is no stateMap.context.params.site_id!');
        }


        //Append master record id as a hidden form field for referential integrity
        $('<input />').attr('type', 'hidden')
            .attr('name', "site_id")
            .attr('value', stateMap.context.params.site_id)
            .appendTo('#frm');




        //fetch entire site record to get name *and* customer id which is required for redundancy
        app.api.get('site', stateMap.context.params.site_id, function(res) {
            if (res.error) {
                $('#app-error-message').text(res.msg);
            } else {
                //Also append customer ID redundantly
                $('<input />').attr('type', 'hidden')
                    .attr('name', "customer_id")
                    .attr('value', res.customer_id)
                    .appendTo('#frm');

                title = 'incident - ' + res.name;
                if (stateMap.id != 'new') {
                    //fetch existing record
                    app.api.get('incident', stateMap.id, function(res) {
                        if (res.error) {
                            $('#app-error-message').text(res.msg);
                        } else {
                            //fill out form
                            app.util_b.formData(res);
                        }
                    });
                } else {
                    //it's a new record, set default
                    $("#incidentDate").val(new Date().toISOString().substring(0, 10));
                }
                //set title 
                $("#app-form-title").text(title);
            }
        });

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

        //make context menu
        $(".app-context-nav").append('<li><a href="#!/incidents/' + stateMap.context.params.site_id + '">Back</a></li>');

        //Autocomplete
        app.util_b.autoComplete('email', 'email');
    };




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