/*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.customerSiteEdit = (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();
        $.gevent.publish('app-clear-error');
        //get form data
        var formData = $("form").serializeArray({
            checkboxesAsBools: true
        });

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


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

            app.api.update('site', submitData, function (res) {
                if (res.error) {
                    $.gevent.publish('app-show-error',res.msg);
                }
            });
        } else {
            //create new record
            app.api.create('site', submitData, function (res) {
                if (res.error) {
                    $.gevent.publish('app-show-error',res.msg);
                } else {
                    page('#!/customerSiteEdit/' + res.id + '/' + stateMap.context.params.cust_id);
                    return false;
                }
            });
        }
        return false; //prevent default
    };


    //ONDELETE
    //
    onDelete = function (event) {
        event.preventDefault();
        $.gevent.publish('app-clear-error');

        var r = confirm("Are you sure you want to delete this record?");
        if (r == true) {
            //--------------------------------------------
            //====  DELETE THE site and it's children ====
            app.api.remove('site/' + stateMap.id, function (res) {
                if (res.error) {
                    $.gevent.publish('app-show-error',res.msg);
                } else {
                    //deleted, return to customers list
                    page('#!/customerSites/' + stateMap.context.params.cust_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.customerSiteEdit']({}));
        var title = "Site";

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

            //fetch existing record
            app.api.get('customer/' + stateMap.context.params.cust_id + '/name', function (res) {
                if (res.error) {
                    $.gevent.publish('app-show-error',res.msg);
                } else {
                    title = 'Site - ' + res.name;
                    if (stateMap.id != 'new') {
                        //fetch existing record
                        app.api.get('site/' + stateMap.id, function (res) {
                            if (res.error) {
                                $.gevent.publish('app-show-error',res.msg);
                            } else {
                                //fill out form
                                app.utilB.formData(res);
                            }
                        });
                    }
                    //set customer name 
                    //app.nav.setContextTitle(title);
                }
            });
        }

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


        //Context menu 
        app.nav.contextClear();
        app.nav.contextAddLink("customerEdit/" + stateMap.context.params.cust_id, "Customer", "account");
        app.nav.contextAddLink("customerSites/" + stateMap.context.params.cust_id, "Sites", "city");

        if (stateMap.id != 'new') {
            app.nav.contextAddLink("purchases/" + stateMap.id, "Purchases", "basket");
         
        }

    };




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