$(document).ready( function(){
	$("body").append('<div id="carregando_geral"><div class="dentro">&nbsp;</div></div>');
	$("#carregando_geral").css("height",$(window).height()+"px").bind("ajaxSend", function(){
		$(this).show();
	}).bind("ajaxComplete", function(){
		$(this).hide();
	}).children().css("height",$(window).height()+"px");
	$("input.tip").focus(function(){
		if ($(this).val() == $(this).prev("span.tip").text()){
			$(this).val("").removeClass("tipped");
		}
		
	}).blur(function(){
		if ($(this).val() == ""){
			$(this).val($(this).prev("span.tip").text()).addClass("tipped");
		}
	});
	
	$("form").submit(function(){ $(this).find("input[type='image'], input[type='submit']").click() });
	
	$("#formcontato input[type='image'], #formcontato input[type='submit']").click(function(e) {
		var ob = $("#formcontato_obrigatorios").val().split(",");
		var faltando = 0;
		//alert(ob);
		$.each(ob,function(){
			if (!$("#formunitcampo"+this).val()){
				alert("O campo "+ ($("#formunitlabel"+this).text()).substr(1) + " é obrigatório");
				faltando = 1;
				var bgorig = $("#formunitcampo"+this).css("backgroundColor");
				var v = 200;
				$("#formunitcampo"+this).animate({"backgroundColor":"#fe0"},v).animate({"backgroundColor":bgorig},v).animate({"backgroundColor":"#fe0"},v).animate({"backgroundColor":bgorig},v).focus();
			}
		});
		if (faltando){
			return false;
		} else {
			$(this).attr("disabled",1);
		}
	});
	
	$(".formbusca input[type='image'], .formbusca input[type='submit']").click(function(e) {
		e.preventDefault();
		var ac = $(this).parents('form').attr("action");
		if (!$(this).parents().find(":text").val()){
			alert("Preencha o campo com o valor da busca");
			$(this).parents().find(":text").focus();
		} else {
			var acr = ac.replace(/ooooo/,"0-"+$(this).parents().find(":text").val());
			document.location.href = acr;
		}
	});
	
	$(".formblog input[type='image'], .formblog input[type='submit']").click(function(e) {
		//alert($(this).parents().find(":text").eq(0).val());
		if (!$(this).parents().find(":text").eq(0).val()){
			alert("Preencha o seu nome");
			$(this).parents().find(":text").get(0).focus();
			e.preventDefault();
			
		} else if (!$(this).parents().find("textarea").eq(0).val()){
			alert("Preencha o comentário");
			$(this).parents().find("textarea").get(0).focus();
			e.preventDefault();
			
		} else
			$(this).parents("form").get(0).submit();
	});
	
	$("#formcv input[type='image'], #formcv input[type='submit']").click(function(e) { 
		var reqs = $("label:contains(\*)").next("div").find("input");
		
		$.each(reqs,function(){
			if (!$(this).val()){
				alert("O campo " + $(this).parent().prev("label").text().replace(/\*/,"") + " tem que ser preenchido");
				$(this).focus();
				e.preventDefault();
			}
		});
		
	});
	
	$("#formcad input[type='image'], #formcad input[type='submit']").click(function(e) {
		e.preventDefault();
		if (!$(this).parents("form").eq(0).find(":text").eq(0).val() || $(this).parents("form").eq(0).find(":text").eq(0).val() == "nome"){
			alert("Preencha o seu nome");
			$(this).parents("form").eq(0).find(":text").get(0).focus();
			
		} else if (!$(this).parents("form").eq(0).find(":text").eq(1).val() || $(this).parents("form").eq(0).find(":text").eq(1).val() == "e-mail" || $(this).parents("form").eq(0).find(":text").eq(1).val().indexOf("@") == -1){
			alert("Preencha o seu e-mail corretamente");
			$(this).parents("form").eq(0).find(":text").get(1).focus();
			
		} else {
			var valores = $(this).parents("form").eq(0).serialize();
			AlertAJAX($(this).parents("form").eq(0).attr("action")+"?"+valores);
		}
		
	});
	
	$("a.email").refaz();
	$(".telefone").refaztel(false);
	$('img[src$=.png] .png').ifixpng();
	
	$("#texto a[href*='://']").addClass("linkexterno").attr("target","_blank").attr("title","Abrir endereço em nova página");
	//$(".gmapscx").jmap('init', {'mapType':'map','mapCenter':[-23.600902, -46.673387],'mapZoom':15});
	$(".gmapslink").removeClass('linkexterno').addClass('gmapslink').click(function(e){
		e.preventDefault();
		var uri = $(this).attr("href").substr(35);
		var titulo = $(this).prev(".titulo").text();
		$(this).next(".gmapscx").attr("src","http://www.mestri.com.br/mapa/mapa.php?u="+uri+"&t="+titulo).toggle("slide", { direction: "up" }, 500);
		$(this).toggleClass("gmapslink_voltar");
	}).mouseover(function(){
		$(this).animate({"backgroundColor":"#f4f4f4"},500).css("color","#000");
	}).mouseout(function(){
		$(this).animate({"backgroundColor":"#fff"},500).css("color","#777");
	});
});

///////////////////////////////////////////////////////

// GERAIS //

///////////////////////////////////////////////////////

$.fn.refaz = function(){
	
	$(this).each(function(k,v){
		var nome = $(this).text();
		var dom = $(this).attr("href");
		var supl = $(this).attr("rel").replace(" ",".");
		
		var supl2 = supl;
		var eml = nome + "@" + dom + "." + supl2;
		$(this).removeAttr("rel").attr("href","mailto:"+eml).attr("title","Enviar e-mail para este endereço").text(eml);
	
	});
	return this;
}

$.fn.refaztel = function(){
	$(this).each(function(k,v){
		var telbruto = $(this).text();
		var partes = telbruto.split(",");
		var tel = "(" + partes[0] + ") " + partes[1] + " " + partes[2];
		if (partes[3]) tel += " " + partes[3];
	
		$(this).text(tel);
	});
	
	return this;
}
$.fn.refazlink = function(){
	$(this).each(function(k,v){
		alert()
	});
}

function Grupo(num){
	var bloco = $("#grupo"+num);
	bloco.toggleClass("retraido").toggleClass("expandido");
	
	$("#conteudo"+num).toggle("slide", { direction: "up" }, 200);
}
function ExpInfo(idp){
	$("#expinfo"+idp).toggle("slide", { direction: "up" }, 200);
}


function AmpliaImg(uri,w,h) {
	var objBody = document.getElementsByTagName('body').item(0);
	var Largura = $(document).width();
	var Altura = $(document).height();
	var LarguraTela = $(window).width();
	var AlturaTela = $(window).height();
	var Largura80 = Math.ceil(LarguraTela * 0.8);
	var Altura80 = Math.ceil(AlturaTela * 0.8);
	var bodyOverlay = document.createElement("div");
	bodyOverlay.setAttribute('id','camadabody');
	bodyOverlay.style.height = Altura + 'px'; // fundo com o tamanho total da página.
	if (!document.getElementById('camadabody')) {
		objBody.insertBefore(bodyOverlay, objBody.firstChild);
	}
	$("#camadabody").css("opacity",0);
	$("#camadabody").animate({"opacity":.7},300);
	if (uri!="-janela-"){
		if (w<Largura80) var referenciaw = w; else var referenciaw = Largura80;
		if (h<Altura80) var referenciah = h; else var referenciah = Altura80;
		
		var bed = document.createElement("div");
		bed.setAttribute('id','camada');
		bed.style.width = '100%';
		bed.style.height = Altura + 'px';
		bed.style.display = 'none';
		bed.style.top = ((AlturaTela/2)-(referenciah/2)) + "px";
		bed.style.left = ((LarguraTela/2)-(referenciaw/2)) + "px";
		objBody.insertBefore(bed, objBody.firstChild);
		
		var fechar = document.createElement("a");
		fechar.className = "fecharampliacao";
		fechar.innerHTML = "fechar";
		fechar.setAttribute('href','javascript:RemoveCamada("img")');
		fechar.style.width = (referenciaw-28) + "px";
		bed.appendChild(fechar);
		
		var imagemdiv = document.createElement("div");
		imagemdiv.className = 'imagemampliada';
		if (w>Largura80){
			imagemdiv.style.overflowX = "auto";
			imagemdiv.style.width = Largura80+"px";
		} else 
			imagemdiv.style.width = w+"px";
		if (h>Altura80){
			imagemdiv.style.overflowY = "auto";
			imagemdiv.style.height = Altura80+"px";
		}
		var imagem = document.createElement("img");
		imagem.setAttribute('src',uri);
		imagemdiv.appendChild(imagem);
		
		bed.appendChild(imagemdiv);
		
		$('#camada').fadeIn('fast');
	
	} else { 
		$("#"+w).fadeIn('fast');
	}
}

function Janela(elem){
	AmpliaImg("-janela-",elem,0);
	if ($.browser.msie && parseInt($.browser.version)<7) scrollTo(0,0);
}

function RemoveCamada(modo) {
	var camada = $('#camadabody');
	camada.fadeOut('fast', function(){ $(this).remove(); });
	if (modo=="img") $("#camada").fadeOut('fast', function(){ $(this).remove(); });
	else $("#"+modo).fadeOut('fast');
}

function Menu(num){
	$("menu div").toggle("slide", { direction: "up" }, 200);
}

function MostrAJAX(uri, elem){
	$("#"+elem).html("<div class='carregando'><span>carregando...</span></div>");
	$.ajax({
		type: "GET",
		url: uri,
		cache: false,
		success: function(obj){ 
			$("#"+elem).html(obj); 
		},
		error: function(obj, status, erro){
			if ($.isFunction(Caixa)){
				$("#"+elem).html("<div class='titulo'>"+"<a href='javascript:;' onclick='RemoveCamada(\"caixageral\"); return false'>"+"<img class='fechar' src='mestri/sistema/estilo/imagens/x.gif' border='0' />"+"</a>"+"<span class='iconetitulo'></span>"+"<span class='textotitulo''>ERRO</span>"+"</div>"+"<div class='menu'></div>"+"<div class='conteudo'><div class='minititulo erro'>Erro ao chamar a página "+uri+"</div></div>"+"<div class='rodape'>"+"<div class='localbotoes'>"+"<a href='javascript:;' onclick='RemoveCamada(\"caixageral\"); return false'>"+"<img src='mestri/sistema/estilo/imagens/botoes/fechar.gif' border='0' alt='fechar' />"+"</a>"+"</div>"+"</div>");
			} else {
				$("#"+elem).html("<div class='caixadeerro'>Erro: <span>" + obj.statusText + "<h3>"+ uri + "</h3></span></div>");
			}
		}

	});

}
function AlertAJAX(uri){
	$.ajax({
		type: "GET",
		url: uri,
		cache: false,
		success: function(obj){ 
			alert(obj); 
		},
		error: function(obj, status, erro){
			alert("ERRO: " + obj.statusText + "\n\nPágina Chamada: "+ uri);
		}

	});
	
}

/* ##### Modulo Blog ##### */

function ModBlogVerCom(idb){
	$("#linkcoms"+idb).toggle();
	$("#cxcomentarios"+idb).toggle("slide", { direction: "up" }, 200);
}
function ModBlogFormCom(idb){
	$("#linkcomsn"+idb).toggle();
	$("#cxcomentariosn"+idb).toggle("slide", { direction: "up" }, 200);
}
function ModBlogResto(idb,elem){
	if (elem.value.length>249){ 
	 	elem.value = elem.value.substring(0, 250) 
	};
	$("#restoch"+idb).html("restam "+(250 - elem.value.length));
}

/* ##### Modulo Curriculos ##### */

function ModCV_CampoExtra(elem){
	var ult_e = $(elem).parent().parent().prev().find(".subsub:last");
	$(elem).parent().parent().prev().find(".subsub:first").clone().hide().insertAfter(ult_e).show("slide", { direction: "up" }, 200).find("input,select").val("");
}
function ModCV_NovoIdioma(elem){
	if ($(elem).val()==7){
		$(elem).width(86).parent().find(":text").show("slide", { direction: "up" }, 200);
	} else {
		$(elem).width(252).parent().find(":text").hide();
	}
}

/* ##### Modulo Galeria Fotos ##### */

function ModGaleria_Amp(idf){
	$("#imagemampliada").fadeOut('fast',function(){ $(this).html($("#imagemampliada_"+idf).html()); }).fadeIn('fast');
}

/////////////////////////////////////////////////////////////////////////////////

// FIX PNG IE 6-

/////////////////////////////////////////////////////////////////////////////////

;(function($) {

	/**
	 * helper variables and function
	 */
	$.ifixpng = function(customPixel) {
		$.ifixpng.pixel = customPixel;
	};
	
	$.ifixpng.regexp = {
		bg: /^url\(["']?(.*\.png([?].*)?)["']?\)$/i,
		img: /.*\.png([?].*)?$/i
	},
	
	$.ifixpng.getPixel = function() {
		return $.ifixpng.pixel || 'images/pixel.gif';
	};
	
	var hack = {
		base	: $('base').attr('href'),
		ltie7	: $.browser.msie && $.browser.version < 7,
		filter	: function(src) {
			return "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true,sizingMethod=crop,src='"+src+"')";
		}
	};
	
	/**
	 * Applies ie png hack to selected dom elements
	 *
	 * $('img[@src$=.png]').ifixpng();
	 * @desc apply hack to all images with png extensions
	 *
	 * $('#panel, img[@src$=.png]').ifixpng();
	 * @desc apply hack to element #panel and all images with png extensions
	 *
	 * @name ifixpng
	 */
	 
	$.fn.ifixpng = hack.ltie7 ? function() {
		function fixImage(image, source, width, height, hidden) {
			image.css({filter:hack.filter(source), width: width, height: height})
			  .attr({src:$.ifixpng.getPixel()})
			  .positionFix();
		}
		
    	return this.each(function() {
			var $$ = $(this);
			if ($$.is('img') || $$.is('input')) { // hack image tags present in dom
				var source, img;
				if (this.src && this.src.match($.ifixpng.regexp.img)) { // make sure it is png image
					// use source tag value if set 
					source = (hack.base && this.src.substring(0,1)!='/' && this.src.indexOf(hack.base) === -1) ? hack.base + this.src : this.src;
					// If the width is not set, we have a problem; the image is not probably visible or not loaded
					// and we need a work around.
					if (!this.width || !this.height) {
						$(new Image()).one('load', function() {
							fixImage($$, source, this.width, this.height);
							$(this).remove();
						}).attr('src', source);
					// If the image already has dimensions (it's loaded and visible) we can fix it straight away.
					} else fixImage($$, source, this.width, this.height);
				}
			} else if (this.style) { // hack png css properties present inside css
				var imageSrc = $$.css('backgroundImage');
				// Background repeated images we cannot fix unfortunately
				if (imageSrc && imageSrc.match($.ifixpng.regexp.bg) && this.currentStyle.backgroundRepeat == 'no-repeat') {
					imageSrc = RegExp.$1;
					var x = this.currentStyle.backgroundPositionX || 0, y = this.currentStyle.backgroundPositionY || 0;
					if (x || y) {
						var css = {}, img;
						if (typeof x != 'undefined') {
							if (x == 'left') css.left = 0; 
							// if right is 0, we have to check if the parent has an odd width, because of an IE bug
							else if (x == 'right') css.right = $$.width() % 2 === 1 ? -1 : 0;
							else css.left = x;
						}
						if (typeof y != 'undefined') {
							// if bottom is 0, we have to check if the parent has an odd height, because of an IE bug
							if (y == 'bottom') css.bottom = $$.height() % 2 === 1 ? -1 : 0; 
							else if (y == 'top') css.top = 0;
							else css.top = y;
						}
						img = new Image();
						$(img).one('load', function() {
							var x,y, expr = {}, prop;
							// Now the image is loaded for sure, we can see if the background position needs fixing with an expression (in case of percentages)
							if (/center|%/.test(css.top)) {
								expr.top = "(this.parentNode.offsetHeight - this.offsetHeight) * " + (css.top == 'center' ? 0.5 : (parseInt(css.top) / 100));
								delete css.top;
							}
							if (/center|%/.test(css.left)) {
								expr.left = "(this.parentNode.offsetWidth - this.offsetWidth) * " + (css.left == 'center' ? 0.5 : (parseInt(css.left) / 100));
								delete css.left;
							}
							// Let's add the helper DIV which will simulate the background image
							$$.positionFix().css({backgroundImage: 'none'}).prepend(
								$('<div></div>').css(css).css({
									width: this.width,
									height: this.height,
									position: 'absolute',
									filter: hack.filter(imageSrc)
								})
							);
							if (expr.top || expr.left) {
								var elem = $$.children(':first')[0];
								for (prop in expr) elem.style.setExpression(prop, expr[prop], 'JavaScript');
							}
							$(this).remove();
						});
						img.src = imageSrc;
					} else {
						$$.css({backgroundImage: 'none', filter:hack.filter(imageSrc)});
					}
				}
			}
		});
	} : function() { return this; };
	
	/**
	 * positions selected item relatively
	 */
	$.fn.positionFix = function() {
		return this.each(function() {
			var $$ = $(this);
			if ($$.css('position') != 'absolute') $$.css({position:'relative'});
		});
	};

})(jQuery);