$(document).ready(function(){
	setInputFocus();
	uiElements();
	$("a[rel*=external]").attr("target", "_blank");
	$("a[rel*=back]").click( function(){ history.back(); return false });
	$("a[rel*=print]").click( function(){ print(); });
	homeFunctions();
	contactFunctions();
});

function setInputFocus() {
    $('.txtFocus').focus(function(e) {
        var elm = $(e.target);
        if (elm.val() == elm.attr("title")) {
            elm.val('');
        }
    }).blur(function(e) {
        var elm = $(e.target);
        if (elm.val() == "") {
            elm.val(elm.attr("title"));
        }
    });
}

function uiElements(){
	$(".datepicker").datepicker();
}

String.prototype.isEmail = function() {
	var rx = new RegExp("\\w+([-+.\â€™]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");
   	var matches = rx.exec(this);
   	return (matches != null && this == matches[0]);
}

function homeFunctions(){
	$(".sendVote").live('click',function(){
		closeAll();
		var idC = $(this).attr("id").substring(5);
		$.post(rootUrl + "home/getCaptcha",{},function(response){
			$("#showCaptcha-" + idC).html(response).show();
		});
	});
	
	$(".sendVoteCaptcha").live('click',function(){
		var elm = $(this).parent();
		$.post(
			rootUrl + "home/vote/" + elm.attr("id").substring(12),
			{captcha : elm.find("input").val() },
			function(response){
				if(response == "ok=1"){
					closeAll();
					$.post(rootUrl+"home/showResult",{},function(response){
						var votes = response.split(";");
						$("#perc1").text(votes[0] + "%");
						$("#perc2").text(votes[1] + "%");
						$("#perc3").text(votes[2] + "%");
					});
				}else if(response == "ok=2"){
					elm.html("<p class='left'>Voc&ecirc; j&aacute; votou</p>").show();
					setTimeout("closeAll()",2000);
				}else{
					elm.html(response).show();
				}
			}
		);
	});
	
	$("a#btnColletion").colorbox({
		opacity: "0.8",
		onLoad: function() {
		    $('#cboxClose').remove();
		}
	});
	
	$("a#btnContact").colorbox({
		opacity: "0.8",
		onLoad: function() {
		    $('#cboxClose').remove();
		}
	});	
}

function closeAll(){
	$("#showCaptcha-1").hide();
	$("#showCaptcha-2").hide();
	$("#showCaptcha-3").hide();
}

function tracker(name){
	try {
		var pageTracker = _gat._getTracker("UA-11882596-1");
		pageTracker._trackPageview(name);
	} catch(err) {}
}

function contactFunctions(){
	$("#sendContact").live("click",function(){
		if($("#name").val() == ""){
			$("#contactMessage").html("Nome &eacute; obrigat&oacute;rio!");
		}else if (!$("#email").val().isEmail()){
			$("#contactMessage").html("Digite um e-mail valido!");
		}else{
			$.post(rootUrl + "contact/send",$("#contactForm").serialize(),function(response){
				if(response == "ok"){
					$("#contactMessage").html("Mensagem enviada com sucesso!");
				}else{
					$("#contactMessage").html(response);
				}
			});
		}
	});
	
	$("#closeBtn").live("click",function(){
		$.fn.colorbox.close();
	});
}
