/**
 * JS for adding a Contact to a company.
 *
 * 1. open a new model window on the add form.
 *
 * 2. When the submit button is clicked, check it for errors
 *
 * 3. If it passes the first validation, submit it to PHP controller via AJAX.
 *
 * 4a. If PHP reports sucessful save
 *	   i.	close the Modal Window
 *	   ii.  add the new contacts user details to the contact table.
 *
 * 4b. If PHP reports validation error. Display error. Set error class to the fields that failed.
 *
 */

$(function() {


    //Style the Button
    $( "#addUser" ).button({
        text: true,
        icons: {
            primary: "ui-icon-plus"
        }
            
    });

    //The diaglog box for Adding a contact.
    $("#addUserDiv").dialog({
        autoOpen: false,
        width: 300,
        modal: true,
        position: 'top'
    });

    $("#addContactUser").live('click', function() { //Adding a Contact to a Customer.
        var userType = 'contact';
        var customer_id = $('.customer_id').attr('id');
        var thisAction = 'add'

        $("#addUserDiv").dialog( "option", "title", 'Add Contact to Customer' );
	
        
        
        
        getForm('/users/add_edit/action:'+thisAction+'/type:'+userType+'/customer_id:'+customer_id);
	
        
        $("#addUserDiv").dialog('open');
        return false;
    });



    $("#addPrincipleUser").click(function() {
        var userType = 'principle';
        var customer_id = $('.principle_id').attr('id');
        var thisAction = 'add'

        $("#addUserDiv").dialog( "option", "title", 'Add Contact to Principle' );
         getForm('/users/add_edit/action:'+thisAction+'/type:'+userType+'/principle_id:'+customer_id);
        $("#addUserDiv").dialog('open');

    });

    //Editing a Customer Contact
    $('.ViewEditButton').click(function() {
        var userType = $('#userType').html();
        var thisAction = 'edit';
        var user_id = $(this).attr('id');
        $("#addUserDiv").dialog( "option", "title", 'Edit Contact' );
         getForm('/users/add_edit/action:'+thisAction+'/type:'+userType+'/user_id:'+user_id);
        $("#addUserDiv").dialog('open');


    });
    

    function getForm(url) {
        $.ajax({
            url: url,
            cache: false,
            success: function(data) {
                $("#addUserDiv").html(data);
                $("#addUserDiv").dialog('open');
            }
               
        });
    }

});

