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

    //------------------- BEGIN UTILITY METHODS ------------------
    //Convert sentToRaw multiline text to sentTo array of lines of text
    //
    sentToRawToArray = function(formData) {
            var sentToRawIndex = -1;
            for (var i = 0; i < formData.length; i++) {
                if (formData[i].name === "sentToRaw") {
                    sentToRawIndex = i;
                    break;
                }
            }

            //modify the return object with the new array format
            var sentToArray = formData[sentToRawIndex].value.trim().split('\n');
            formData[sentToRawIndex] = {
                name: "sentTo",
                value: sentToArray
            };
        }
        //-------------------- END UTILITY METHODS -------------------

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

    onSave = function(event) {

        event.preventDefault();
        $('#app-error-message').text('');
        //get form data
        var formData = $("form").serializeArray({
            checkboxesAsBools: true
        });
      
        sentToRawToArray(formData);
        var submitData = app.util_b.objectifyFormDataArray(formData);       

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

            app.api.update('notification', submitData, function(res) {
                if (res.error) {
                    $('#app-error-message').text(res.msg);
                }
            });
        } else {
            //Yes...create new record
            app.api.create('notification', submitData, function(res) {
                if (res.error) {
                    $('#app-error-message').text(res.msg);
                } else {
                    page('#!/customer_notification_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) {

            //====  DELETE THE notification ====
            app.api.deleteOne('notification', stateMap.id, function(res) {
                if (res.error) {
                    $('#app-error-message').text(res.msg);
                } else {
                    //deleted, return to customers list
                    page('#!/customer_notifications/' + 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_notification_edit']({}));
        var title = "notification";

        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 = 'notification - ' + res.name;
                    if (stateMap.id != 'new') {
                        //fetch existing record
                        app.api.get('notification', stateMap.id, function(res) {
                            if (res.error) {
                                $('#app-error-message').text(res.msg);
                            } else {
                                //fill out form

                                //turn array of items into /n delimited string
                                //                                
                                var sentTo = '';

                                for (var i = 0; i < res.sentTo.length; i++) {
                                    sentTo = sentTo + res.sentTo[i] + '\n';
                                }
                                res.sentToRaw = sentTo;
                                //---------------------------------------------

                                app.util_b.formData(res);
                            }
                        });
                    }else{
                        //it's a new record, set default
                        $("#sentDate").val(new Date().toISOString().substring(0, 10));                        
                    }

                    //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_notifications/' + stateMap.context.params.cust_id + '">Back</a></li>');

        }
    };




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