/*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.customer_site_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('site', submitData, function(res) {
                if (res.error) {
                    $('#app-error-message').text(res.msg);
                }
            });
        } else {
            //create new record
            app.api.create('site', submitData, function(res) {
                if (res.error) {
                    $('#app-error-message').text(res.msg);
                } else {
                    page('#!/customer_site_edit/' + res.insertedId + '/' + stateMap.context.params.cust_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) {

            //Customer->site->incident->purchase->trial

            app.api.deleteRelated('trial', 'customer_id', stateMap.context.params.cust_id, function(res) {

                if (res.error) {
                    $('#app-error-message').text(res.msg);
                    return false;
                } else {


                    app.api.deleteRelated('purchase', 'customer_id', stateMap.context.params.cust_id, function(res) {

                        if (res.error) {
                            $('#app-error-message').text(res.msg);
                            return false;
                        } else {


                            app.api.deleteRelated('incident', 'customer_id', stateMap.context.params.cust_id, function(res) {

                                if (res.error) {
                                    $('#app-error-message').text(res.msg);
                                    return false;
                                } else {


                                    //--------------------------------------------
                                    //====  DELETE THE site ====
                                    app.api.deleteOne('site', stateMap.id, function(res) {
                                        if (res.error) {
                                            $('#app-error-message').text(res.msg);
                                        } else {
                                            //deleted, return to customers list
                                            page('#!/customer_sites/' + 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.customer_site_edit']({}));
        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', "customer_id")
                .attr('value', stateMap.context.params.cust_id)
                .appendTo('#frm');

            //fetch existing record
            app.api.getName('customer', stateMap.context.params.cust_id, function(res) {
                if (res.error) {
                    $('#app-error-message').text(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) {
                                $('#app-error-message').text(res.msg);
                            } else {
                                //fill out form
                                app.util_b.formData(res);
                            }
                        });
                    }
                    //set customer name 
                    $("#app-form-title").text(title);
                }
            });
        }

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

        //make context menu
        if (stateMap.context.params.cust_id) {
            $(".app-context-nav").append('<li><a href="#!/customer_sites/' + stateMap.context.params.cust_id + '">Back</a></li>');
        }

        if (stateMap.id != 'new') {
            $(".app-context-nav").append('<li><a href="#!/purchases/' + stateMap.id + '">Purchases</a></li>');
            $(".app-context-nav").append('<li><a href="#!/incidents/' + stateMap.id + '">Incidents</a></li>');
            $(".app-context-nav").append('<li><a href="#!/trials/' + stateMap.id + '">Trials</a></li>');
        }

    };




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