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


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

    //ONSAVE
    //
    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('customer', submitData, function(res) {
                if (res.error) {
                    $('#app-error-message').text(res.msg);
                }
            });
        } else {
            //it's a new record - create
            app.api.create('customer', submitData, function(res) {
                if (res.error) {
                    $('#app-error-message').text(res.msg);
                } else {
                    page('#!/customer_edit/' + res.insertedId);
                }
            });
        }
        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 linked records (i.e. contacts notifications etc) 
            //Customer->Contact
            //Customer->notification
            //Customer->site->incident->purchase


            app.api.deleteRelated('notification', 'customer_id', stateMap.id, function(res) {

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


                    app.api.deleteRelated('purchase', 'customer_id', stateMap.id, function(res) {

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




                            app.api.deleteRelated('incident', 'customer_id', stateMap.id, function(res) {

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



                                    app.api.deleteRelated('site', 'customer_id', stateMap.id, function(res) {

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


                                            app.api.deleteRelated('contact', 'customer_id', stateMap.id, function(res) {

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


                                                    //--------------------------------------------
                                                    //==== DELETE THE NEXT CUSTOMER CHILD RECORD IN CHAIN =====
                                                    //for now there are none but contacts...more to come later here

                                                    //==== FINALLY DELETE THE CUSTOMER ====
                                                    app.api.deleteOne('customer', stateMap.id, function(res) {
                                                        if (res.error) {
                                                            $('#app-error-message').text(res.msg);
                                                        } else {
                                                            //deleted, return to customers list
                                                            page('#!/customers');
                                                            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_edit']({}));

        //id should always have a value, either a record id or the keyword 'new' for making a new object
        if (stateMap.id != 'new') {
            //fetch existing record
            app.api.get('customer', stateMap.id, function(res) {
                if (res.error) {
                    $('#app-error-message').text(res.msg);
                } else {
                    //fill out form
                    app.util_b.formData(res);
                }
            });
            //make context menu
            $(".app-context-nav").append('<li><a href="#!/customers">Back</a></li>');
            $(".app-context-nav").append('<li><a href="#!/customer_sites/' + stateMap.id + '">Sites</a></li>');
            $(".app-context-nav").append('<li><a href="#!/customer_contacts/' + stateMap.id + '">Contacts</a></li>');
            $(".app-context-nav").append('<li><a href="#!/customer_notifications/' + stateMap.id + '">Notifications</a></li>');
        } else {
            $('#btn-delete').hide();
        }

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


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