/***
*
*	Funções Agência DMK
*	Versão: 11.8.2009
*
*	Índice:
*
*	Log para Debug............................: 20
*	Redimensionar por classe..................: 45
*	Link Ativo................................: 65
*	Blank.....................................: 79
*	Classe Voltar.............................: 92
*	Tira bordas do Flash no IE................: 104
*	Reset de formulário.......................: 149
*	Exibe div de bloqueio.....................: 165
*	AbsoluteCenter............................: 230
*
****/


////////////
// Select //
////////////
estiloSelect = {
	init: function(){
		var primeiro = 0;
		$("select.select").each(function(){
			var html =  '<div id="' + $(this).attr("id") + '" class="' + $(this).attr("class") + '">';
				html += '	<div class="ativo"></div>';
				html += '	<input id="' + $(this).attr("id") + '_select" name="' + $(this).attr("name") + '" type="hidden" value="" />';
				html += '	<div class="options">';
				for(i=0;i<$("option",this).length;i++){
					html += '	<a href="javascript:void(0);" title="' + $("option:eq(" + i + ")",this).text() + '" rel="' + $("option:eq(" + i + ")",this).attr("value") + '">' + $("option:eq(" + i + ")",this).text() + '</a>';
				}
				html += '	</div>';
				html += '</div>';
			$(this).replaceWith(html);
			$("option",this).each(function(i){
				primeiro = this.selected ? i : primeiro;
			});
		});
		$("div.select").css("visibility","visible").each(function(){
			var altura = $("a",this).length;
				altura = altura > 5 ? 5 : altura;
			$(".options",this).css({height:(altura * parseInt($("a:first",this).css("height"))) + "px", visibility:"visible", display:"none"});
			estiloSelect.change(this,primeiro);
		})
		$("div.select").each(function(){
			$("a", this).each(function(i){
				$(this).unbind().click(function(){
					estiloSelect.change($(this).parents("div.select:eq(0)"),i);
				});
			});
		});
		$("div.select .ativo").click(function(){estiloSelect.abre(this);});
	},
	abre: function(obj){
		$(obj).parent().parent().css("z-index","3");
		$(obj).unbind('click').siblings(".options").slideDown('fast',function(){
			$("html").unbind('click').bind('click',estiloSelect.fecha);
			$("div.select .ativo").unbind('click');
		});
	},
	change: function(obj,option){
		$("a.optionAtivo",obj).removeClass("optionAtivo");
		$("a:eq(" + option + ")",obj).addClass("optionAtivo");
		var texto = $("a:eq(" + option + ")",obj).text();
		var valor = $("a:eq(" + option + ")",obj).attr("rel");
		$(".ativo",obj).html(texto);
		$("input",obj).val(valor);
		estiloSelect.fecha();
	},
	
	fecha: function(){
		$("div.select .options:visible").slideUp('fast',function(){$(this).parent().parent().css("z-index","2")});
		$("html").unbind('click', estiloSelect.fecha);
		$("div.select .ativo").unbind('click').click(function(){estiloSelect.abre(this)});
	}
}


/***
*	:: Log para Debug ::
*	:: 2007 ::
*
*	l(<Mensagem>,<true ou false para IE>);
*
*	Exibe um log para Debug.
*	ex:
*		l("testando");
*		l("testando",true);
***/
function l(x,consoleIE){
	consoleIE = typeof(consoleIE) == "undefined" ? false : consoleIE;
	if(window.console){
		console.log(x);
	}else if(consoleIE){
		if(!$("#dmDebug").is("div")){
			$("body").append("<div id=\"dmDebug\" style=\"width:"+($(window).width()-50+"px")+"; border:1px solid #000; position:absolute; bottom:0; left:0; height:150px; overflow:auto; filter:alpha(opacity=80); font-size:12px; padding:5px; font-family:Tahoma, Arial, Helvetica, sans-serif; background:#fff; z-index:99999;\"></div>");
		}
		$("#dmDebug").append("<p style=\"margin:0; border-bottom:1px dashed #000; color: #000; font-weight: bold;\">"+x+"</p>");
	}
}


$(document).ready( function(){
	/***
	*	:: Redimensionar por classe ::
	*	:: 2007 ::
	*
	*	Redimenciona um elemente setando uma classe para ele.
	*	ex:
	*		<div class="width150">teste</div>
	*		<div class="height5050">teste</div>
	***/
	$("*[class*=width]").each(function(){
		var dmClasses = $(this).attr("class").split(" ");
		$.each(dmClasses, function(i,n){ if(n.indexOf("width") != -1){ dmTamanho = dmClasses[i].replace("width",""); } });
		$(this).css("width",dmTamanho+"px");
	});
	$("*[class*=height]").each(function(){
		var dmClasses = $(this).attr("class").split(" ");
		$.each(dmClasses, function(i,n){ if(n.indexOf("height") != -1){ dmTamanho = dmClasses[i].replace("height",""); } });
		$(this).css("height",dmTamanho+"px");
	});

	/***
	*	:: Link Ativo ::
	*	:: 2007 ::
	*
	*	Adiciona a classe "ativo" para o link que tiver o destino (href) identico à pagina aberta
	***/
	dmPaginaAtivo = window.location+"";
	dmPaginaAtivo = dmPaginaAtivo.split("/").pop();
	if(dmPaginaAtivo != ""){
		$('a[href="'+dmPaginaAtivo+'"]').addClass('ativo');
		$('a[href="'+dmPaginaAtivo+'"]').siblings('ul').removeClass('hide');
		$('a[href="'+dmPaginaAtivo+'"]').parents('ul').removeClass('hide').siblings('a').addClass('ativo');;
	}
		
	/***
	*	:: Blank ::
	*	:: 2007 ::
	*
	*	Abre um link em uma nova janela.
	*	ex:
	*		<a href="http://www.agenciadmk.com.br/" title="Agencia DMK" class="blank">Agência DMK</a>
	***/
	$(".blank").live('click',function(){
		window.open($(this).attr("href"));
		return false;
	});
	
	/***
	*	:: Classe Voltar ::
	*	:: 2007 ::
	*
	*	Adiciona um evento em um objeto que volta no histórico no navegador
	*	Ex.: <a href="javascript:void(0);" title="voltar" class="voltar">voltar</a>
	***/
	$(".voltar").live('click',function(){
		window.history.go(-1);
		return false;
	});

	/***
	*	:: Tira bordas do Flash no IE ::
	*	:: 2008 ::
	*
	*	Retira as bordas pontilhadas do flash no Internet Explorer
	*	Ex.: 	$("#flash").addFlash({
	*				src: "swf/banner2.swf",
	*				width: 584,
	*				height: 201,
	*				title: "Agência DMK"
	*			});
	***/
	$.extend({
		addFlash: {
			version: 1.2,
			defaults: {
				src: "",
				width: 100,
				height: 50,
				title: "",
				quality: "high",
				menu: "false",
				wmode: "transparent"
			}
		}
	});
	$.fn.extend({
		addFlash: function(options){
			options = $.extend({}, $.addFlash.defaults, options);
			return this.each(function(){
				if(options.src != ""){
					var flash = '<object type="application/x-shockwave-flash" data="'+options.src+'?clicktag=./" width="'+options.width+'" height="'+options.height+'" tabindex="0" title="'+options.title+'">'
					flash += '<param name="movie" value="'+options.src+'?clicktag=./" />'
					flash += '<param name="quality" value="'+options.quality+'" />'
					flash += '<param name="menu" value="'+options.allowFullScreen+'" />'
					flash += '<param name="wmode" value="'+options.wmode+'" />'
					flash += '<p>Para visualizar este conteúdo corretamente, é necessário ter o <a title="Clique para instalar o flash player" href="http://www.macromedia.com/shockwave/download/alternates/" rel="nofollow">Flash Player</a> instalado.</p>'
					flash += '</object>'
					$(this).html(flash);
				}
			});
		}
	});

	/***
	*	:: Reset de formulário ::
	*	:: 2007 ::
	*
	*	Reseta um formulário
	*	Ex.: $("#contato").resetForm();
	***/
	$.fn.resetForm = function() {
		return this.each(function() {
			dmRfName = $(this).attr("name") + "";
			dmRfName = dmRfName == "undefined" || dmRfName == "" ? "dmRfName" : dmRfName;
			$(this).attr("name",dmRfName);
			eval("document."+dmRfName+".reset()");
		});
	}; 

	
	/***
	*	:: Exibe div de bloqueio ::
	*	:: 2007 ::
	*
	*	Função que abre uma div cobrindo toda a tela bloqueando o site, com função de callback.
	*	ex:
	*		bloqueia({ speed: "slow", bgcolor: "#000" });
	*		bloqueia({ speed: "slow", evento: "fim" });
	*
	*	OBS: Nescessário plugin Dimension.
	***/
	bloqueia = function(options,callback){
		var defaults = {
			versao: 2.1,
			id: "bloqueio",
			evento: "inicio",
			bgColor: "#000",
			opacity: "0.5",
			speed: "normal",
			zIndex: "100",
			cursor: "default",
			animate: true
		}
		options = $.fn.extend({},defaults,options);

		if((options.id == "" || options.id == "bloqueio") && !$("#bloqueio").is("div")) $("body").append("<div id=\"bloqueio\" style=\"display:none\"></div>");

		var altura = $(document).height() > $(window).height() ? $(document).height() : $(window).height();

		if(options.evento == "inicio"){
			if($.browser.msie && $.browser.version == "6.0") $("select:visible").addClass("hiddenForDmBlock").css("visibility","hidden");
			$("#"+options.id).css({
				background:options.bgColor,
				cursor:options.cursor,
				height:altura,
				left:"0",
				opacity:options.opacity,
				position:"absolute",
				top:"0",
				width:"100%",
				zIndex:options.zIndex
			});
			if(options.animate){
				$("#"+options.id).fadeIn(options.speed, function(){ if(typeof(callback) != "undefined"){ callback(); } });
			}else{
				$("#"+options.id).css("display","block");
				if(typeof(callback) != "undefined"){ callback(); }
			}
			carregandoResize = function(){
				altura = $(document).height() > $(window).height() ? $(document).height() : $(window).height();
				$("#"+options.id).css({height:altura});
			}
			$(window).bind('resize',carregandoResize);
		}else{
			$("select.hiddenForDmBlock").css("visibility","visible");
			$(window).unbind('resize',carregandoResize);
			if(options.animate){
				$("#"+options.id).fadeOut(options.speed, function(){ if(typeof(callback) == "function"){ callback(); } });
			}else{
				$("#"+options.id).css("display","none");
				if(typeof(callback) == "function"){ callback(); }
			}
		}
	}
	
	/***
	*	:: Absolute Center ::
	*	:: 2008 ::
	*
	*	Função que centraliza um objeto na tela.
	*	ex:
	*		$("#teste").absoluteCenter({limit:[0,10,0,10]});
	*		$("#teste").absoluteCenter({clear:true;}
	*
	*	OBS: Nescessário plugin Dimension.
	***/
	$.fn.extend({
		absoluteCenter: function(options, speed, callback){
			var defaults = {
				dellay: 100,
				limitTop: 0,
				limitRight: 0,
				limitBottom: 0,
				limitLeft: 0,
				limit: null,
				animation: true,
				clear:false
			}
			options = $.extend({}, defaults, options);
					
			if(options.limit != null){
				if(typeof(options.limit) == "object"){
					options.limitTop = typeof(options.limit[0]) != "undefined" ? options.limit[0] : options.limitTop;
					options.limitRight = typeof(options.limit[1]) != "undefined" ? options.limit[1] : options.limitRight;
					options.limitBottom = typeof(options.limit[2]) != "undefined" ? options.limit[2] : options.limitBottom;
					options.limitLeft = typeof(options.limit[3]) != "undefined" ? options.limit[3] : options.limitLeft;
				}else{
					options.limitTop = options.limit;
					options.limitRight = options.limit;
					options.limitBottom = options.limit;
					options.limitLeft = options.limit;
				}
			}
			
			speed = typeof(speed) == "undefined" ? "fast" : speed;
			
			return this.each(function(){

				var obj = this;
				var timeOut = null;
				
				var ajustaScroll = function(){
					
					if($(obj).css("display") == "none") $(window).unbind("scroll",ajustaScroll).unbind("resize",ajustaScroll);
					
					var altura = parseInt($(obj).outerHeight());
					var largura = parseInt($(obj).outerWidth());
					
					var limiteC = parseInt($(obj).css("top"));
					var limiteB = limiteC + altura;
					var limiteE = parseInt($(obj).css("left"));
					var limiteD = limiteE + largura;
					
					var scrollTop = parseInt($(window).scrollTop());
					var scrollLeft = parseInt($(window).scrollLeft());
					var janelaAltura = parseInt($(window).height());
					var janelaLargura = parseInt($(window).width());
					
					var documentoAltura = parseInt($("body").outerHeight());
					var documentoLargura = parseInt($(document).width());
					
					var top = janelaAltura > altura
						? parseInt(scrollTop + (( janelaAltura / 2 ) - parseInt(altura / 2)))
						: scrollTop < (limiteC - options.limitTop)
							? scrollTop + options.limitTop
							: (scrollTop + janelaAltura) > (limiteB + options.limitBottom)
								? scrollTop - (altura - janelaAltura) - options.limitBottom
								: limiteC
					;
					top = (top + altura) > documentoAltura ? documentoAltura - altura : top;
					
					var left = janelaLargura > largura
						? parseInt(scrollLeft + (( janelaLargura / 2 ) - parseInt(largura / 2)))
						: scrollLeft < (limiteE - options.limitLeft)
							? scrollLeft + options.limitLeft
							: (scrollLeft + janelaLargura) > (limiteD + options.limitRight)
								? scrollLeft - (largura - janelaLargura) - options.limitRight
								: limiteE
					;
					left = (left + largura) > documentoLargura ? documentoLargura - largura : left;
														
					top = isNaN(top) ? 0 : top;
					left = isNaN(left) ? 0 : left;
					
					top = top < 0 ? 0 : top;
					
					if(options.animation){
						clearTimeout(timeOut);
						timeOut = setTimeout(function(){
							$(obj).animate({top:top+"px",left:left+"px"},speed,function(){ if(typeof(callback) != "undefined") callback(); });
						},options.dellay);
					}else{
						$(obj).css({top:top+"px",left:left+"px"});
					}
					
				}
				ajustaScroll();
				
				if(options.animation) {
					$(window).unbind('scroll', ajustaScroll).unbind('resize', ajustaScroll);
					$(window).scroll(ajustaScroll).resize(ajustaScroll);
				}

			});
		}
	});

});
	
	
	//////////////
// No Label //
//////////////
noLabel = {
	init: function(){
		$(".noLabel").each(function(){
			$(this).addClass("vazio");
			noLabel.buffer[$(this).attr("id")] = $(this).val();
			$(this).unbind('focus',noLabel.foco).unbind('blur',noLabel.desfoco).bind('focus',noLabel.foco).bind('blur',noLabel.desfoco);
		}).parents("form:eq(0)").unbind('submit',noLabel.formulario).bind('submit',noLabel.formulario);
	},
	
	buffer: {},
	
	foco: function(obj){
		obj = typeof($(obj).attr("id")) == "undefined" ? this : obj;
		if($(obj).hasClass("vazio")){
			if($(obj).is("textarea")){
				$(obj).html("");
			}else{
				$(obj).val("");
			}
			$(obj).removeClass("vazio");
		}
	},
	
	desfoco: function(){
		if($.trim($(this).val()) == ""){
			if($(this).is("textarea")){
				$(this).html(noLabel.buffer[$(this).attr("id")]);
			}else{
				$(this).val(noLabel.buffer[$(this).attr("id")]);
			}
			$(this).addClass("vazio");
		}
	},
	
	formulario: function(){
		$(".vazio",this).each(function(){
			noLabel.foco(this);
		});
		return true;
	}
}
