// jGrowl defaults
$.jGrowl.defaults.closerTemplate = "<div>[ fechar todos ]</div>";
$.jGrowl.defaults.life = 10000;

// tooltips defaults
$.fn.qtip.defaults.position.corner.target = "rightMiddle"; 
$.fn.qtip.defaults.position.corner.tooltip = "leftMiddle"; 
$.fn.qtip.defaults.show.solo = true; 
$.fn.qtip.defaults.style = { 
	border: {
		radius: 3,
		width: 1
	},
	name: 'cream', 
	tip: {
		corner: "leftMiddle"
	} 
};

// enhance plugin
(function($){
	$.fn.enhance = function() {
	    return this.each(function() {
	    	var $start = $(this);

	    	// elastic textareas
	    	$start.find("textarea.elastic").elastic();
	    	
	    	// input masks
            $start.find("input.CEP").mask("99.999-999");
            $start.find("input.CertificateValidationCode").mask("999.999.999.999");
	    	$start.find("input.CPF").mask("999.999.999-99");
	    	$start.find("input.Date:not([readonly])").mask("99/99/9999");
	    	$start.find("input.DateTime:not([readonly])").mask("99/99/9999 99:99");
	    	$start.find("input.TelefoneBrasil").mask("(99)9999-9999");

	    	// tooltips
	    	$start.find(":input:not(.button)[title], a[title]").qtip({
	    		hide: {
	    			fixed: true,
	    			when: {
	    				event: "blur"
	    			}
	    		},
	    		show: {
	    			when: {
	    				event: "focus"
	    			}
	    		}
	    	});
	    	
	    });
	};
})(jQuery);

// onready script
$(function(){

	$(".accordion").accordion({
		active: false,
		collapsible: true
	});
	
	$(".dialog").dialog();

	$(".tabs").tabs();
	
	// Replace a.button by input.button
	// The href attribute is set on purpose, so we can bind/unbind the click event and still have a place to look for the URL.
	$("div.toolbar a.button").each(function(){
		var $this = $(this);
		$this.replaceWith("<input type='button' class='" + $this.attr("class") + "' value='" + $this.html() + "' href='" + $this.attr("href") + "' title='" + $this.attr("title") + "' />");
	});
	// bind the click event for the replaced buttons
	$("input.button[href]").click(function(){window.location.href = $(this).attr("href")});
	
	// configuracao Ajax
    $(document).ajaxError(function(event, XMLHttpRequest, ajaxOptions, thrownError){
        window.alert('Aconteceu um erro. Caso se repita, entre em contato com o administrador do sistema.');
    });

    $(document).ajaxComplete(function(request, settings){
    	stopWaiting();
	});

	$("input[type=submit], a.new, a.back").click(startWaiting);

	$("form.enhanced").enhance();
	
	$("form:not(.nofocus) :input:visible:first").focus(); // focus first field

});

function startWaiting(){
	$.jGrowl("<span class='wait-dark'>Aguarde...</span>", {sticky: true});
}

function stopWaiting(){
	window.setTimeout(function(){
		$(".jGrowl-notification:has(.wait-dark) div.close").click();
	}, 1000); // give time to the notification to appear before closing it (on fast networks)
}