
var FANCY_OPTS = {
    'transitionIn': 'elastic', 'transitionOut': 'elastic', //'elastic', 'fade' or 'none'	
	'speedIn': '300', 'speedOut': '300',
    'autoScale': true, 'autoDimensions': true, 'centerOnScroll': true,
	'titleShow': false, 'showCloseButton': true, 'enableEscapeButton': true
};


(function($) {

// returns $(obj) from "obj_id", "#obj_id" and $(obj)
get_$ = function(obj){ 
    var $obj = obj;
    if (typeof obj == "string") {
        if (obj[0] != "#") { 
            obj = "#" + obj; 
        }
        $obj = $(obj);
    };
    return $obj;
};


// redirects responses with HTTP 278 code
redirect_by_xhr = function(xhr) {
    window.location.href = xhr.getResponseHeader("Location").replace(/\?.*$/, "?next="+window.location.pathname);
};


// CLICK event of *button*, on <ENTER> key inside *container*
bind_enter_to_click = function(container_id, button_id) {
    get_$(container_id).bind('keypress', function(e) {
       if(e.which === 13) { 
           get_$(button_id).trigger('click');
       } else {
           return true;
       };
    });
};


//  FORM fiels as DATASTRING (arg for $.ajax)
//  datasring="?var1=a1&var2=b&var3=c"
datastring_from_form = function(form_id) {

    var dataString = '';
    $.each($(form_id).serializeArray(), function(i, field) {
        dataString += '&' + field.name + '=' + field.value;
    });    
    return dataString.substring(1);
};




setup_fancybox_form = function(form_id, submit_id, url) {
    $(submit_id).click(function() {
        var dataString = datastring_from_form(form_id);

        $.ajax({ type: "POST", url: url, data: dataString,

            success: function(data, textStatus, xhr) {

                    if (xhr.status == 278) { 
                        redirect_by_xhr(xhr);
                    } else {
                        $('#fancybox-content').html(data); 
                        $.fancybox.resize();
                        setup_fancybox_form(form_id, submit_id, url);
                    }
            },

            error: function(xhr, textStatus, errorThrown) { 
                    return true;
                }

        });
    });            	

    bind_enter_to_click(form_id, submit_id);
};

setup_fancybox = function(link_id, on_complete) {
    var new_fbox = FANCY_OPTS;

    if (on_complete){
        new_fbox['onComplete'] = on_complete;
    }
		
    get_$(link_id).fancybox(new_fbox);    
};


//   POST one var
post_ajax_var = function(key, value, url, success_func) {
    $.ajax({ type: "POST", 
        url: url, 
        data: key + '=' + value, 
        success: success_func,
        error: function(xhr, textStatus, errorThrown) {
                    alert("Ocorreu um erro, tente novamente mais tarde.");
        }, // error
    }); // ajax
};

})(jQuery);
