var freemoGUI = (function(){
    var xhrForm = function() {
       var form = $(this);
       $.post($(this).attr('action'),
            { data: $(this).serializeArray(), source: 'xhr' } ,
             function(response){
             if(response.data.status == true) {
                form.closest('.dialog').dialog('destroy'); 
             } else if(response.data.status == false 
                 && response.data.formErrors.length > 0) {
                $.each(response.data.formErrors.entries,function(field,errors){
                    $('#'+field+'-label ul.errors').remove();
                    var $errorList = $('<ul/>').addClass('errors');
                    $.each(errors,function(key,message){
                        $('<li/>').html(message).appendTo($errorList);    
                    });
                    $errorList.appendTo('#'+field+'-label');
                }); 
             }
        });
     
        return false;
    };
    var showDialog = function() {
        var config = $(this).attr('data-dialog').split(';');
        $('<div class="dialog"></div>').appendTo('body').load($(this).attr('href')).dialog({
            modal: true,
            width: parseInt(config[1]),
            height: parseInt(config[2])
        });
        $('.ui-resizable-handle').attr('style', 'z-index: 1001; display: none; -moz-user-select: none;');
        return false;
    };

    return {
        init: function() {
           $('.xhr-form').live('submit', xhrForm);
           $('.xhr-form input[type=submit]').live('click',function(){
                $(this).closest('.xhr-form').submit(); 
                return false;
           });
           $('a[data-dialog]').live('click',showDialog);
        } 
    }
})(); 

