﻿$(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");*/
	
	$("body").bind("ajaxSend", function(){
		$(this).css("cursor","wait");
	}).bind("ajaxComplete", function(){
		$(this).css("cursor","default");
	})
	
	$("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()) + " é 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;
		}
	});
	
	$("#search").submit(function(){
		var ac = $(this).attr("action");
		if (!$(this).find(":text").val()){
			alert("Preencha o campo com o valor da busca");
			$(this).find(":text").focus();
		} else {
			var acr = ac.replace(/ooooo/,"0-"+$(this).find(":text").val());
			document.location.href = acr;
			return false;
		}
		
	});
	
	$("#search input[type='image'], #search input[type='button']").click(function(e) {
		$(this).parents("form").trigger("submit");
	});
	
	$(".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]').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");
	});
	
	$(".formunit .radio .figura").click(function(){
        var elemhidden = $(this).attr("rel");
        var opcao = $(this).text();
        
		$(this).parent().parent().find("a.figura").removeClass("escolhida");
		$(this).addClass("escolhida");
        $("#"+elemhidden).val(opcao);
	});
    
	$(".formunit .check .figura").click(function(){
        var elemhidden = $(this).attr("rel");
        var opcao = $(this).text();
		var valores = $("#"+elemhidden).val().split("<br />");
        var localnoarray = $.inArray(opcao,valores);
        if (localnoarray != -1){
            valores.splice(localnoarray,1);
        } else {
            valores.push(opcao);
        }
        $("#"+elemhidden).val(valores.join("<br />")); 
        if ($("#"+elemhidden).val().substring(0,6) == "<br />"){
            $("#"+elemhidden).val($("#"+elemhidden).val().substring(6));
        }
        
        //alert($("#"+elemhidden).val())
		$(this).toggleClass("escolhida");
	});
	$(".enquete .opcao").click(function(e){
		$(this).parent().find("a.opcao").removeClass("escolhida");
		
		$(this).parent().parent().find("input:hidden").eq(0).val($(this).attr("href"));
		$(this).addClass("escolhida");
		e.preventDefault();
	});
	$(".enquete .botoes a").eq(0).click(function(e){
		var valor = $(this).parent().parent().find("input:hidden").eq(0).val();
		var enquete = $(this).attr("href");
		e.preventDefault();
		if (valor){
			$.ajax({
				type: "GET",
				url: "mestri/modulos/enquetes/site/post.php",
				data: {valor:valor, enquete:enquete},
				cache: false,
				success: function(obj){ 
					$("#enquete"+enquete+" .opcoes .placefb").html(obj);
					$("#enquete"+enquete+" .botoes").hide();
				},
				error: function(obj, status, erro){
					alert("ERRO: " + obj.statusText);
				}
		
			});
			
		} else {
			alert("Escolha uma alternativa!");
		}
	});
	$(".enquete .opcoes a.resultados").eq(0).click(function(e){
		var enquete = $(this).attr("href");
		var cont = 0;
		e.preventDefault();
		$.ajax({
			type: "GET",
			url: "mestri/modulos/enquetes/site/resultados.php",
			data: {enquete:enquete},
			cache: false,
			success: function(obj){ 
				$("#enquete"+enquete+" .resmostra .placeres").html(obj);
				$("#enquete"+enquete+" .opcoes").hide();
				$("#enquete"+enquete+" .resmostra").fadeIn('fast');
				$("#enquete"+enquete+" a.gaugeres .barra").each(function(){
					cont = $(this).parent().attr("rel");
					$(this).animate({width:cont+"px"},1500);

					$(this).find("span").css("top",($(this).position().top+7)+"px");
					//$(this).parent().click(function(e){ e.preventDefault();	});
				});
				
			},
			error: function(obj, status, erro){
				alert("ERRO: " + obj.statusText);
			}
	
		});
	});
	
	$(".enquete .resmostra a.resultados").eq(0).click(function(e){
		e.preventDefault();
		$(this).parent().hide().parent().find(".opcoes").fadeIn("fast");
	});
	
	$(".formunit label").hover(
        function(){
		    if (!$(this).siblings("div.infocampo").is(":empty")){
			    var pos = $(this).offset().top+16;
			    $(this).siblings("div.infocampo").css({top:parseInt(pos)+"px", opacity:.8}).fadeIn("fast");
		    }
		
	    }, function(){
		    $(this).siblings("div.infocampo").fadeOut("fast");
		
	    }
    );
    
    $("#carregandosite").fadeOut(250);
    
    $(".hilitemouseover").hover(function(){
        $(this).animate({opacity:.7});
        
    }, function(){
        $(this).animate({opacity:1});
        
    });
    
    $(".itemmenu span.menuover").hover(function(){
        $(this).find("img.mouseover").show();
        $(this).find("img.mouseout").hide();
        
    }, function(){
        $(this).find("img.mouseover").hide();
        $(this).find("img.mouseout").show();
        
    });
});

///////////////////////////////////////////////////////

// GERAIS //

///////////////////////////////////////////////////////
(function(jQuery){
    jQuery.extend($, {
        notNow: function (timeOut, func) {
            var msIntervalValue;
            var timeoutFunction = function() {
                clearInterval(msIntervalValue);
                if (typeof func === 'function') {
                    func();
                };
            };
            msIntervalValue = setInterval(timeoutFunction, timeOut || 1500);
        }
    });
})(jQuery);
/*   *
     * @param {String} url The URL of the page to load.
     * @param {Object} form The form object (or jQuery object holding the form) whose elements values should be sent.
     * @param {Function} callback (optional) A function to be executed whenever the data is loaded successfully.
     * @param {String} type (optional) Type of data to be returned to callback function (JSON, XML, etc.)
     * @param {Object} target (optional) Event target element which triggered this postForm call. Used to emulate behaviour of browsers standard form handling, which is: the form fields name and value triggering the form action will be sent, too.
     */
$.postForm = function( url, form, callback, type, target ) {
    var data = {}, i, j, field, fTag, fType;

    // remove jQuery wrapping of form object
    if (form.jquery) {
        form = form.get( 0 );
    }

    if (!form || !form.tagName || !form.tagName.toLowerCase() === 'form') {
        throw( 'Attempted to post a non-form element.' );
    }

    if (target.tagName.toLowerCase() !== 'button' && !target.type.match( /^submit|image$/i )) {
        target = null;
    }

    for (i = 0; i < form.elements.length; ++i) {
        field = form.elements[ i ];

        if (!field) {
            continue;
        }

        fTag = field.tagName.toLowerCase();
        fType = field.type.toLowerCase();

        // Never submit <fieldset>, <input type="reset"> and <button type="reset">.
        // Submit <button> or <input type="submit|image"> values if this element was used to trigger the form submit.
        if (fTag === 'fieldset' || fType === 'reset' || (fTag === 'button' || fType === 'submit' || fType === 'image') && field !== target) {
            continue;
        }

        if (fType === 'select-multiple') {
            for (j = 0; j < field.options.length; ++j) {
                if (field.options[ j ].selected) {
                    add( data, field.name, field.options[ j ].value );
                }
            }
        }
        else if (fType === 'radio' || fType === 'checkbox') {
            if (field.checked) {
                add( data, field.name, field.value );
            }
        }
        else {
            add( data, field.name, field.value );
        }
    }

    jQuery.post( url, data, callback, type );
};

/**
 * extends the value of an object's key dynamically to an array if more than one is added
 * @private
 * @param {Object} object a normal object
 * @param {String} name object's key
 * @param {Any} value value to add to object's key
 */
function add( object, name, value ) {
    if (object[ name ]) {
        if (typeof object[ name ] === 'object') {
            object[ name ].push( value );
        }
        else {
            object[ name ] = [ object[ name ], value ];
        }
    }
    else {
        object[ name ] = value;
    }
}


$.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 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);

    $("body").eq(0).append("<div id='camadabody'></div>");
    $("#camadabody").height(Altura).css("opacity",0).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;
        
        $("body").eq(0).append("<div id='camada'><a class='fecharampliacao' href='javascript:RemoveCamada(\"img\")'>fechar</a><div class='imagemampliada'><img src='"+uri+"' alt='imagem ampliada' /></img></div></div>");
        $("#camada").css({width:"100%", height:Altura+"px", display:"none", top:((AlturaTela/2)-(referenciah/2)) + "px", left:((LarguraTela/2)-(referenciaw/2)) + "px"})
        $(".fecharampliacao").width((referenciaw-28));
        $(".imagemampliada").width(w+"px");

        if (w>Largura80)
            $(".imagemampliada").css({width:Largura80+"px", overflowX: "auto"});

        if (h>Altura80)
            $(".imagemampliada").css({height:Altura80+"px", overflowY: "auto"}); 
		
		$('#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){
			obj = obj.replace(/ï»¿/g, "");
			$("#"+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 || 'mestri/estilo/imagens/padrao/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);
