var urlencode = escape;
var urldecode = unescape;

Date.prototype.getDays = function() { // retorna a quantidade de dias que tem o mês
    var a = new Date(this.getFullYear(), this.getMonth() + 1, 0, 0, 0, 1);
    return a.getDate();
};
Date.prototype.getStartDay = function() { // retorna o dia da semana que começa o mês
    var a = new Date(this.getFullYear(), this.getMonth(), 1, 0, 0, 1);
    return a.getDay();
};

var in_array = function (str, arr) {
	var	str = str || "",
		arr = arr || [];
	for (var i in arr) {
		if (arr[i] == str) {
			return true;
		};
	};
	return false;
};

var animation = function (objects, callback) {
	var	callback = callback || function(){},
		objects = objects,
		start = [],
		diff = [],
		end = [],
		cn = 0;
	for (var i in objects) {
		start[i] = parseInt(objects[i].object.css(objects[i].param));
		end[i] = parseInt(objects[i].value);
		diff[i] = (start[i] > end[i] ? start[i] - end[i] : end[i] - start[i]) / 10;
	};
	var animationInterval = setInterval(function(){
		for (var i in objects) {
			var nv = (start[i] > end[i] ? start[i] - (diff[i] * cn) : start[i] + (diff[i] * cn));
			if ((start[i] > end[i] && nv < end[i]) || (start[i] < end[i] && nv > end[i])) {
				nv = end[i];
				clearInterval(animationInterval);
				animationInterval = false;
			};
			eval("objects[i].object.css({"+objects[i].param+":nv})");
		};
		if (!animationInterval) {
			callback();
		};
		cn++;
	}, 25);
};
/*	ANIMATION
	OBJETIVO:	Fazer animação simultânea de objetos diferentes e
			valores diferentes.
	DESTINADO:	Para parâmetros medidos em pixels
			(height, width, paddingLeft, etc...)
	USO:		animation([{p,v,o},{p,v,o},{p,v,o}], callback)
				p = param:parametro - width, height, etc
				c = value:valor final - 50
				o = object:chamada JQuery do objeto - $("#main")
				callback =	função que será chamada
						no final da animação
	EXEMPLO DE USO:
**************************************************************************
	animation([
	    {param:"height",value:25,object:$(".hi0")},
	    {param:"height",value:50,object:$(".hi1")},
	    {param:"height",value:75,object:$(".hi2")},
	    {param:"height",value:100,object:$(".hi3")},
	    {param:"height",value:125,object:$(".hi4")}
	], function() {
	    alert("acabou")
	});
**************************************************************************/

var hotspot = {
	animando:false,
	titulo: [],
	aberto: 0,
	corrigeTitulo: function (hi) {
		var	$img =	$("#hotspot .hi"+hi+" .ht-titulo img");
		if (!/\.php\?title/.test($img[0].src)) {
			$img[0].src = __URL_TEMPLATE+"/inc/hotspot-image-title.php?title="+urlencode($img[0].alt.toUpperCase());
			$img[0].onload = function() {
				hotspot.corrigeTitulo(hi);
			};
			return false;
		};
		$img.css({display:"block"});
		var	hei =	($img.height() > 70 ? 70 : $img.height()),
			wid =	($img.width() * hei) / $img.height(),
			top =	75 - hei;
		this.titulo[hi] = {
			width:wid,
			height:hei,
			marginTop:top
		};
		$img.css(this.titulo[hi]);
	},
	change: function(hi) {
		if (this.animando) {
			return false;
		} else if (hi == this.aberto) {
			return true;
		};
		this.animando = true;

		$(".hotspot-title", $hsAberto).css({textAlign:"left"});
		$(".hotspot-title", $hsFechado).css({textAlign:"center"});

		var	$hsAberto	= $("#hotspot .hi"+this.aberto),
			$hsFechado	= $("#hotspot .hi"+hi),
			$hi		= hi;
		animation([
			{param:"width",value:68,object:$hsAberto},
			{param:"width",value:680,object:$hsFechado},
			{param:"width",value:40,object:$(".hotspot-title", $hsAberto)},
			{param:"width",value:530,object:$(".hotspot-title", $hsFechado)}
		], function() {
			if (!hotspot.titulo[$hi]) {
				hotspot.corrigeTitulo(hi);
			};
			hotspot.aberto = $hi;
			hotspot.animando = false;
			$(".ht-titulo, .ht-promocao", $hsAberto).hide();
			$(".ht-titulo, .ht-promocao", $hsFechado).show();
			$(".ht-numero", $hsAberto).css({color:"#FFFFFF"}).animate({marginLeft:11,lineHeight:126,fontSize:22});
			$(".ht-numero", $hsFechado).css({color:"#F6911F"}).animate({marginLeft:0,lineHeight:90,fontSize:70});
			$("#hotspot-description").html($hsFechado[0].onblur().description);
		});
		return false;
	},
	change_v2:function(hi) {
		if (this.animando) {
			return false;
		} else if (hi == this.aberto) {
			return true;
		};
		this.animando = true;
		var	aberto		= {start:680,end:68,ts:530},
			fechado		= {start:68,end:680,ts:40},
			$hsAberto	= $("#hotspot .hi"+this.aberto),
			$hsFechado	= $("#hotspot .hi"+hi),
			$hi		= hi;

		$(".hotspot-title", $hsAberto).css({textAlign:"left"});
		$(".hotspot-title", $hsFechado).css({textAlign:"center"});

		var hsInterval = setInterval(function(){
			if (aberto.start <= aberto.end) {
				clearInterval(hsInterval);
				hotspot.aberto = $hi;
				hotspot.animando = false;
				if (!hotspot.titulo[$hi]) {
					hotspot.corrigeTitulo(hi);
				};
				return void(0);
			};
			aberto.start -= 68;
			fechado.start += 68;
			aberto.ts -= 55;
			fechado.ts += 55;
			aberto.ts = aberto.ts < 40 ? 40 : aberto.ts;
			fechado.ts = fechado.ts > 530 ? 530 : fechado.ts;

			$hsAberto.css({width:aberto.start});
			$hsFechado.css({width:fechado.start});
			$(".hotspot-title", $hsAberto).css({width:aberto.ts});
			$(".hotspot-title", $hsFechado).css({width:fechado.ts});
		}, 25);

		$(".ht-titulo, .ht-promocao", $hsAberto).hide();
		$(".ht-titulo, .ht-promocao", $hsFechado).show();

		$(".ht-numero", $hsAberto).css({color:"#FFFFFF"}).animate({marginLeft:11,lineHeight:126,fontSize:22});
		$(".ht-numero", $hsFechado).css({color:"#F6911F"}).animate({marginLeft:0,lineHeight:90,fontSize:70});

		$("#hotspot-description").html($hsFechado[0].onblur().description);

		return false;
	}
};

var view_image = function (obj) {
	obj.blur();
	var	$via = $("#view-image-area"),
		atual = (parseInt(obj.className.replace(/[^0-9]+/g,'')) + 1),
		total = ($(".midia a").length),
		proxima = (atual + 1 > total ? 1 : atual + 1),
		anterior = (atual - 1 < 1 ? total : atual - 1);
	if (!$via[0]) {
		var	bg =	'<div id="view-image-bg" onclick="return false"></div>',
		 	html =	'<div id="view-image-area">'+
					'<div class="image-area">'+
						'<div class="navigate prev">Voltar</div>'+
						'<div class="navigate next">Avançar</div>'+
						'<img border="0" width="500" />'+
					'</div>'+
					'<div class="legenda"></div>'+
					'<div class="numero">Foto '+atual+' de '+total+'</div>'+
					'<div class="navigate close'+(window.is_ie7 ? " close_ie7" : "")+'">Fechar</div>'+
				'</div>';
		$("#wrapper").prepend(bg);
		$("#view-image-bg").css({
			height:$("body").height()
		}).after(html);
		$via = $("#view-image-area");
		$(".navigate").css({
			background:"#FFF url("+__URL_TEMPLATE+"/images/sprite/icons-35.gif) 0 0 no-repeat"
		});
		$(".close", $via).css({
			backgroundPosition:"61px -177px"
		})[0].onclick = function () {
			this.blur();
			var $ani = {width:0,height:0,top:0,left:0,opacity:0};
			$via.animate($ani, function(){
				$(this).remove();
				$("#view-image-bg").remove();
			});
			return false;
		};
		$via.animate({
			top:$(obj).offset().top-150,
			left:$("h1.entry-title").offset().left-20
		});
	};
	$(".next", $via).css({
		backgroundPosition:"61px -107px"
	})[0].onclick = function () {
		$(".midia a.p"+(proxima - 1))[0].onclick();
	};
	$(".prev", $via).css({
		backgroundPosition:"-4px -143px"
	})[0].onclick = function () {
		$(".midia a.p"+(anterior - 1))[0].onclick();
	};
	$(".numero", $via).html("Foto "+atual+" de "+total);
	$(".image-area img", $via).attr("src",obj.href);
	return false;
};

var submenu = function (a) {
	a.blur();
	var $sm = $(".submenu", $(a).parent());
	if ($sm[0].style.display == "none") {
		$(".plus", a).html("-");
		$sm.slideDown();
	} else {
		$(".plus", a).html("+");
		$sm.slideUp();
	};
	return false;
}

var getForm = function (formName, callback, hide_content) {
	submitForm.send({
		action:"get-form",
		formName:formName,
		onSuccess:function(retorno) {
			$(hide_content, $(/^\#/g.test(hide_content) ? "#main" : "#content")).fadeOut(150, function(){
				callback(retorno);
				documentScrollTop(100);
			});
		}
	});

};

var inscricao = function (sub_categoria) {
	getForm ("inscricao", function(retorno) {
		$content = $("#content");
		if (!$(".colunaA-contato", $content)[0]) {
			$content.prepend(retorno.data);
			$(".candario-title-small", $content).html(sub_categoria.name);
		};
	});
	return false;
};

var reservation_remove = function (hide_content) {
	$content = $(/^\#/g.test(hide_content) ? "#main" : "#content");
	$(".colunaA-reserve", $content).fadeOut(function(){
		$(this).remove();
		documentScrollTop(100);
		$(hide_content, $content).fadeIn();
	});
	return false;
};

var reservation = function (category, is_duvidas, hide_content) {
	var hide_content = hide_content || ".post, .post-leftbar";
	getForm("reservation", function(retorno){
		$content = $(/^\#/g.test(hide_content) ? "#main" : "#content");
		if (!$(".colunaA-reserve", $content)[0]) {
			$content.prepend(retorno.data);
			$(".colunaA-reserve", $content).append(
				'<div class="conteudo-botoes'+(is_duvidas ? ' gray' : '')+'"><a href="#cancelar" onclick="return reservation_remove(\''+hide_content+'\')" class="whiteLink">Cancelar</a></div>'
			);
			$("#form_reserve_roteiro", $content).val(($("h1")[0] ? $("h1").html().toUpperCase()+" - "+$(".conteudo-subtitulo").html() : ""));
			$("#form_reserve_category", $content).val(category);
			$("#form_reserve_tipo_contato", $content).val(is_duvidas ? "duvida" : "reserva");
			if (is_duvidas) {
				$(".colunaA-contato-title-text").html('Tire suas<br /><span style="height:55px;line-height:65px;display:block">dÚvidas</span>');
				$(".colunaA-contato-subtitle").html("Aqui você obtém informações com a praticidade da internet.");
			};
		};
	}, hide_content);
	return false;
};

var submitForm = {
	validate: {
		notEmpty: function (str) {
			var str = str.replace(/(^\s+|\s+$)/g, "");
			return (str != "");
		},
		equalTo: function (strA, strB) {
			return (strA === strB);
		},
		email: function (email) {
			var	chr = "[a-z0-9_-]+",
				reg = chr+"((\\."+chr+")+)?",
				reg = "^"+reg+"\@"+reg+"(\\.[a-z]{2,4})+$";
				reg = new RegExp(reg, "gi");
			return reg.test(email);
		},
		fields: function (fieldList, retorna) {
			var	fieldList	= fieldList || {},
				error		= [],
				retorna		= retorna || false;
			for (var i in fieldList) {
				o = fieldList[i];
				if (o.type == "notEmpty" && !this.notEmpty(o.value)) {
					error.push(o.name+(!retorna ? " está em branco." : ""));
				} else if (o.type == "equalTo" && !this.equalTo(o.value, o.value2)) {
					error.push(o.name+(!retorna ? " e "+o.name2+" não conferem." : ""));
				} else if (o.type == "email") {
					if (!this.notEmpty(o.value)) {
						error.push(o.name+(!retorna ? " está em branco." : ""));
					} else if (!this.email(o.value)) {
						error.push(o.name+(!retorna ? " ("+o.value+") não é um e-mail válido." : ""));
					};
				} else if (o.type == "data") {
					if (typeof(o.value) == "string" && !/^(\d{4}([- \/\.])\d{2}\2\d{2}|\d{2}([- \/\.])\d{2}\3\d{4})$/g.test(o.value)) {
						error.push(o.name+(!retorna ? " deve ser preenchido corretamente." : ""));
					} else if (!(o.value.ano.length == 4 && o.value.mes.length == 2 && o.value.dia.length == 2)) {
						error.push(o.name+(!retorna ? " deve ser preenchido corretamente." : ""));
					};
				};
			};
			if (error.length > 0) {
				if (retorna) {
					return error;
				}
				alert(error.join("\n"));
				return false;
			};
			return true;
		}
	},
	defaults: {
		method: "POST",
		target: __URL_TEMPLATE+"/inc/ajax.php",
		params: {
			action:"do-nothing",
			onSuccess: function () {},
			onError: function () {}
		}
	},
	callback: function (retorno) {
		if (!retorno) {
			/*
				colocar no PHP que retorna <?php header("Content-type: application/json"); ?>
				tipo padrão de retorno (em JSON)
				-----------
				retorno = {
					type: "error/success", type deve estar em lowercase
					message: "mensagem de retorno (pode ser de erro, de sucesso ou em branco)",
					data: {} --> informações que podem ser usadas no retorno, caso necessite
				}
			------------------------------------------------------------------------------------------- */
			alert("Tipo de retorno inválido");
			return false;
		};
		if (typeof(retorno) !== "object") {
			var t = retorno.match(/\[\[\[START-JSON-CODE\]\]\](\{.+\})$/g)[0].replace(/\[\[\[START-JSON-CODE\]\]\]/g,"");
			eval("t="+t);
			t.data = retorno.replace(/\[\[\[START-JSON-CODE\]\]\].+/g,"");
			retorno = t;delete t;
		};
		if (retorno.type == "success") {
			window[retorno.cbName].onSuccess(retorno);
			return true;
		} else if (retorno.type == urldecode("%64%65%62%75%67")) {
			return true;
		};
		window[retorno.cbName].onError(retorno);
		delete window[retorno.cbName];
		return false;
	},
	send: function (params,method,target,getFile) {
		var	target	= target || this.defaults.target,
			method	= method || this.defaults.method,
			params	= params || this.defaults.params,
			getFile	= (getFile === true),
			cbName	= "cbClass_"+parseInt(Math.random() * 1000000)+"_"+(new Date().getTime()), // callback function name
			mCall	= '$.'+method.toLowerCase()+'("'+target+'?getFile='+(getFile ? "true" : "false")+'&cbName='+cbName; // method call
		params.onError = params.onError	|| this.defaults.params.onError;
		params.onSuccess = params.onSuccess || this.defaults.params.onSuccess;
		window[cbName] = {
			onSuccess: params.onSuccess,
			onError: params.onError
		};
		if (method.toLowerCase() == "get") {
			var queryString = "";
			for (var i in params) {
				if (typeof(params[i]) == "string") {
					queryString += "&"+i+"="+params[i];
				};
			};
			mCall += queryString+'",';
		} else {
			var	p = params;
			delete	p.onError;
			delete	p.onSuccess;
			mCall += '", p,';
		};
		mCall += " submitForm.callback)";
		eval(mCall);
	}
};

var formNewsletterApplyText = function () {
	var	fneText = "Digite seu email!",
		$formNewsletterEmail = $("#form-newsletter-email")[0]
	if ($formNewsletterEmail) {
		$formNewsletterEmail.onfocus = function () {
			this.value = (this.value == fneText ? "" : this.value);
			this.style.color = "#666";
		};
		$formNewsletterEmail.onblur = function () {
			if (this.value == "" || this.value == fneText) {
				this.value = fneText;
				this.style.color = "#BBB";
			} else {
				this.style.color = "#666";
			};
		};
		$formNewsletterEmail.onblur();
	};
};

var formNewsletterSubmit = function () {
	var email = $("#form-newsletter-email")[0].value;
	if (!submitForm.validate.email(email)) {
		var	txt = $("#form-newsletter").html(),
			txt = txt.replace(/^([^\<]+)/g,"Digite um e-mail válido, por favor! ");
                        txt = txt.replace("receber novidades sobre a<br>", "");
                        txt = txt.replace("receber novidades sobre a", "");
                        txt = txt.replace("Xtravel.", "");
		$("#form-newsletter").html(txt);
		formNewsletterApplyText();
		return false;
	};
	submitForm.send ({
		action:"add-newsletter",
		email:email,
		onError:function(retorno) {
			alert(retorno.message);
		},
		onSuccess:function(retorno) {
			$("#form-newsletter").html(retorno.message).append(
				'<span class="clear"></span>'+
				'<div class="button" style="margin-top:2px;">VOLTAR</div>'
			);
			$("#form-newsletter .button").css({width:50})[0].onclick = function() {
				$("#form-newsletter").html(
					'Informe seu e-mail para<br />'+
					'receber novidades sobre a<br />'+
					'Xtravel.'+
					'<div class="form-newsletter-fields">'+
						'<input style="color: rgb(102, 102, 102);" name="email" id="form-newsletter-email" value="" type="text">'+
						'<div class="button" onclick="formNewsletterSubmit()">OK</div>'+
						'<span class="clear"></span>'+
					'</div>'
				);
			};
		}
	}, "POST");
};

var formTestimonialSubmit = function () {
	if ($(".contato-form")[0].style.display != "none") {
		$(".contato-form, .contato-form2").fadeOut(100, function(){
			$(".erro" , this).remove();
			formTestimonialSubmit();
		});
		return false;
	};
	var params = {
		action:		"add-testimonial",
		nome:		$("#form_testimonial_nome")[0].value,
		email:		$("#form_testimonial_email")[0].value,
		nasc: {
				ano:$("#form_testimonial_nasc_ano")[0].value,
				mes:$("#form_testimonial_nasc_mes")[0].value,
				dia:$("#form_testimonial_nasc_dia")[0].value
		},
		sexo:		$("#form_testimonial_sexo_m")[0].checked ? "masculino" : ($("#form_testimonial_sexo_f")[0].checked ? "feminino" : ""),
		destino:	$("#form_testimonial_destino")[0].value,
		depoimento:	$("#form_testimonial_depoimento")[0].value,
		onSuccess:	function (retorno) {
			documentScrollTop(100);
			$(".colunaA-contato-subtitle").html(retorno.message);
			$(".contato-form, .contato-form2").remove();
		},
		onError:	function (retorno) {
			documentScrollTop(100);
			$(".colunaA-contato-subtitle").html(retorno.message);
			$(".contato-form, .contato-form2").fadeIn();
		}
	};
	var validate = submitForm.validate.fields([
		{type:"email",name:"email",value:params.email},
		{type:"notEmpty",name:"nome",value:params.nome},
		{type:"notEmpty",name:"sexo",value:params.sexo},
		{type:"notEmpty",name:"destino",value:params.destino},
		{type:"notEmpty",name:"depoimento",value:params.depoimento}
	], true);
	if (validate !== true) {
		$(".contato-form, .contato-form2").fadeIn(100, function(){
			for (var i in validate) {
				var	t = validate[i],
					$ob = $("#form_testimonial_"+t+(t == "sexo" ? "_f" : ""));
				$ob.parent().parent().append('<img class="erro" style="" width="20" height="20" border="0" src="'+__URL_TEMPLATE+'/images/contato-alert.gif">');
				$(".erro", $ob.parent().parent()).css({
					position:"absolute",
					float:"left",
					top:$ob.offset().top,
					left:$(".contato-form").offset().left + 330
				});
			};

		});
		return false;
	};
	submitForm.send(params, "POST");
	return false;
};

var formReserveSubmit = function () {
	if ($(".contato-form2")[0].style.display != "none") {
		$(".contato-form").fadeOut(100, function(){
			$(".erro" , this).remove();
		});
		$(".contato-form2").fadeOut(100, function(){
			$(".erro" , this).remove();
			formReserveSubmit();
		});
		return false;
	};
	var params = {
		action:		"add-reservation",
		category:	$("#form_reserve_category")[0].value,
		tipo_contato:	$("#form_reserve_tipo_contato")[0].value,
		nome:		$("#form_reserve_nome")[0].value,
		email:		$("#form_reserve_email")[0].value,
		telefone: [
				{ddd:$("#form_reserve_ddd_1")[0].value,telefone:$("#form_reserve_telefone_1")[0].value},
				{ddd:$("#form_reserve_ddd_2")[0].value,telefone:$("#form_reserve_telefone_2")[0].value}
		],
		embarque: {	
				ano:$("#form_reserve_embarque_ano")[0].value,
				mes:$("#form_reserve_embarque_mes")[0].value,
				dia:$("#form_reserve_embarque_dia")[0].value
		},
		retorno: {	
				ano:$("#form_reserve_retorno_ano")[0].value,
				mes:$("#form_reserve_retorno_mes")[0].value,
				dia:$("#form_reserve_retorno_dia")[0].value
		},
		qtd_menor:	$("#form_reserve_qtd_menor")[0].value,
		qtd_maior:	$("#form_reserve_qtd_maior")[0].value,
		cliente:	$("#form_reserve_cliente_s")[0].checked ? "sim" : ($("#form_reserve_cliente_n")[0].checked ? "nao" : ""),
		como_conheceu:	$("#form_reserve_como_conheceu")[0].value,
		newsletter:	$("#form_reserve_newsletter")[0].checked == true,
		roteiro:	$("#form_reserve_roteiro")[0].value,
		mensagem:	$("#form_reserve_mensagem")[0].value,
		onSuccess:	function (retorno) {
			documentScrollTop(100);
			$(".colunaA-contato-subtitle").html(retorno.message);
			$(".contato-form, .contato-form2").remove();
		},
		onError:	function (retorno) {
			documentScrollTop(100);
			$(".colunaA-contato-subtitle").html(retorno.message);
			$(".contato-form, .contato-form2").fadeIn(100);
		}
	};
	var validate = submitForm.validate.fields([
		{type:"notEmpty",name:"nome",value:params.nome},
		{type:"notEmpty",name:"qtd_maior",value:params.qtd_maior},
		{type:"notEmpty",name:"cliente",value:params.cliente},
		{type:"notEmpty",name:"roteiro",value:params.roteiro},
		{type:"notEmpty",name:"mensagem",value:params.mensagem},
		{type:"email",name:"email",value:params.email},
		{type:"data",name:"embarque",value:params.embarque},
		{type:"data",name:"retorno",value:params.retorno}
	], true);


	var validate_telefone = submitForm.validate.fields([
		{type:"notEmpty",name:"ddd_1",value:params.telefone[0].ddd},
		{type:"notEmpty",name:"telefone_1",value:params.telefone[0].telefone},
		{type:"notEmpty",name:"ddd_2",value:params.telefone[1].ddd},
		{type:"notEmpty",name:"telefone_2",value:params.telefone[1].telefone},
	], true);
	if (validate !== true || validate_telefone !== true) {
		var ddd_1 = false, ddd_2 = ddd_1, telefone_1 = ddd_2, telefone_2 = telefone_1, telefone_2;
		if (typeof(validate) != "object") {
			var validate = [];
		};
		for (var i in validate_telefone) {
			var i = parseInt(i);
			if (in_array(validate_telefone[i], ["ddd_1", "ddd_2", "telefone_1", "telefone_2"])) {
				eval(validate_telefone[i]+"="+(i+1));
			};
		};

		if (!((!ddd_1 && !telefone_1 && ddd_2 && telefone_2) || (ddd_1 && telefone_1 && !ddd_2 && !telefone_2) || (!ddd_1 && !telefone_1 && !ddd_2 && !telefone_2))) {
			validate[validate.length] = "ddd_1";
		};

		if (validate.length > 0) {
			var p = {
				cliente:100,
				assunto:240,
				mensagem:500,
				qtd_maior:240,
				embarque:140
			};
			$(".contato-form, .contato-form2").fadeIn(100, function() {
				for (var i in validate) {
					var	t = validate[i],
						$ob = $("#form_reserve_"+t+(t == "sexo" ? "_f" : (t == "cliente" ? "_n" : (t == "embarque" ? "_dia" : (t == "retorno" ? "_dia" : "")))));
					$ob.parent().parent().append('<img class="erro" style="" width="20" height="20" border="0" src="'+__URL_TEMPLATE+'/images/contato-alert.gif">');
					$(".erro", $ob.parent().parent()).css({
						position:"absolute",
						float:"left",
						top:$ob.offset().top,
						left:$(".contato-form2").offset().left + (p[t] || 330)
					});
				};
			});
			return false;
		};
	};
	submitForm.send(params, "POST");
	return false;
};

var formContactSubmit = function () {
	$(".contato-form, .contato-form2").fadeOut(100);
	var params = {
		action:		"add-contact",
		nome:		$("#form_contact_nome")[0].value,
		email:		$("#form_contact_email")[0].value,
		telefone: [
				{ddd:$("#form_contact_ddd_1")[0].value,telefone:$("#form_contact_telefone_1")[0].value},
				{ddd:$("#form_contact_ddd_2")[0].value,telefone:$("#form_contact_telefone_2")[0].value}
		],
		nasc: {	
				ano:$("#form_contact_nasc_ano")[0].value,
				mes:$("#form_contact_nasc_mes")[0].value,
				dia:$("#form_contact_nasc_dia")[0].value
		},
		sexo:		$("#form_contact_sexo_m")[0].checked ? "masculino" : ($("#form_contact_sexo_f")[0].checked ? "feminino" : ""),
		endereco:	$("#form_contact_endereco")[0].value,
		cep:		$("#form_contact_cep_1")[0].value+"-"+$("#form_contact_cep_2")[0].value,
		cidade:		$("#form_contact_cidade")[0].value,
		uf:		$("#form_contact_uf")[0].value,
		pais:		$("#form_contact_pais")[0].value,
		assunto:	$("#form_contact_assunto")[0].value,
		perfil:		$("#form_contact_perfil")[0].value,
		cliente:	$("#form_contact_cliente_s")[0].checked ? "sim" : ($("#form_contact_cliente_n")[0].checked ? "nao" : ""),
		como_conheceu:	$("#form_contact_como_conheceu")[0].value,
		newsletter:	$("#form_contact_newsletter")[0].checked == true,
		mensagem:	$("#form_contact_mensagem")[0].value,
		onSuccess:	function (retorno) {
			documentScrollTop(100);
			$(".colunaA-contato-subtitle").html(retorno.message);
			$(".contato-form, .contato-form2").remove();
		},
		onError:	function (retorno) {
			documentScrollTop(100);
			$(".colunaA-contato-subtitle").html(retorno.message);
			$(".contato-form, .contato-form2").fadeIn();
		}
	};
	var validate = submitForm.validate.fields([
		{type:"notEmpty",name:"nome",value:params.nome},
		{type:"notEmpty",name:"sexo",value:params.sexo},
		{type:"notEmpty",name:"cliente",value:params.cliente},
		{type:"notEmpty",name:"assunto",value:params.assunto},
		{type:"notEmpty",name:"mensagem",value:params.mensagem},
		{type:"email",name:"email",value:params.email}
	], true);
	if (validate !== true) {
		var p = {
			cliente:100,
			assunto:240,
			mensagem:500
		};
		for (var i in validate) {
			var	t = validate[i],
				$ob = $("#form_contact_"+t+(t == "sexo" ? "_f" : (t == "cliente" ? "_n" : "")));
			$ob.parent().parent().append('<img class="erro" style="" width="20" height="20" border="0" src="'+__URL_TEMPLATE+'/images/contato-alert.gif">');
			$(".erro", $ob.parent().parent()).css({
				position:"absolute",
				float:"left",
				top:$ob.offset().top,
				left:$(".contato-form2").offset().left + (p[t] || 330)
			});
			$(".contato-form, .contato-form2").fadeIn();
		};
		return false;
	};
	submitForm.send(params, "POST");
	return false;
};


var calendario = {
	modalidade:false,
	$target:$("body"),
	$target_method:"html",
	marcadores: { // marcadores.ano.mes = {dia:#,info:{}} - (marcadores.2010.11 || marcadores[2010][11]) = {dia:25,info:{evento:"confraternização",motivacao:"natal"}}
		/*2010: {
			11: [
				{dia:21,info:{modalidade:"Corrida",cidade:"Barcelona",pais:"Espanha",nome:"Vuelta à España",detalhes:"10km, 21km e 42km",ativo:"false",resultado:"http://192.168.2.29/xtravel/index.php/esporte/bike/barcelona/"}},
				{dia:25,info:{modalidade:"Corrida",cidade:"Nova Iorque",pais:"Estados Unidos da América",nome:"Maratona de Nova Iorque",ativo:"false",detalhes:"130km"}},
				{dia:29,info:{modalidade:"Corrida",cidade:"São Paulo",pais:"Brasil",nome:"Maratona de São Paulo",ativo:"true",detalhes:"130km"}}
			]
		}*/
	},
	proximos:[
		/*{inicio:"21/12",fim:"22/12",url:"http:192.168.2.29/xtravel/index.php/esporte/bike/barcelona/",local:"Buenos Aires"},
		{inicio:"25/12",fim:"27/12",url:"http:192.168.2.29/xtravel/index.php/esporte/bike/nova-iorque/",local:"Nova Iorque"},
		{inicio:"01/01",fim:"06/01",url:"http:192.168.2.29/xtravel/index.php/esporte/bike/emirados-arabes-unidos/",local:"Emirados Árabes Unidos"}*/
	],
	date:{
		ano:(new Date()).getFullYear(),
		mes:(new Date()).getMonth(),
		dia:(new Date()).getDate(),
		dow:0,	// day of week - dia da semana que começa o mês
		mmd:{	// max month days - número máximo de dias do mês
			atual:31,
			anterior:30
		}
	},
	show: function(ano,mes,$target,$target_method) {
		$("#box-calendario").remove();
		this.$target = $target;
		this.$target_method = $target_method;
		this.date = {
			ano:ano,
			mes:mes
		};
		this.date.mmd = this.define_dia_maximo();
		this.date.dow = this.define_dia_semana();
		$target[$target_method](calendario.render());
		this.pega_marcadores(function(eventos){
			var html = "";
			for(var i in eventos) {
				e = eventos[i];
				$(".dia-"+e.dia, $("#calendario")).addClass("selected");
				html +=	'<div class="cd-item calendario-rodape-group">'+
						'<div class="cd-item-dia calendario-data-rodape">'+e.dia+'</div>'+
						'<div class="calendario-data-rodape-info">'+
							'<font color="#'+(e.info.resultado ? '666666' : '333333')+'">'+
								(e.info.url && e.info.url.length > 10 ? '<a href="'+e.info.url+'" style="color:#F26522">' : '')+
								e.info.cidade+(e.info.detalhes ? ": "+e.info.detalhes : "")+
								(e.info.url && e.info.url.length > 10 ? '</a>' : '')+
							'</font>'+
							(e.info.ativo == "true" ? "" :
								'<font color="#'+(e.info.resultado ? 'ff4e00' : '666666')+'">| '+
									(e.info.resultado ? '<a href="'+e.info.resultado+'" class="linkOrange">Ver resultados</a>' : 'Inscrições Encerradas')+
								'</font>')+
						'</div>'+
						'<span class="clear"></span>'+
					'</div>';
			};
			html += '<span class="clear"></span><br />';
			$("#calendario-detalhes").html(html);
		});
		this.pega_proximos(3, function(eventos){
			if (eventos.length == 0) {
				$("#proximas-provas .pp-list").html('Não há próximas ' + (calendario.modalidade == "bike" ? "saídas" : (calendario.modalidade == "ski" ? "temporadas" : "provas")) + ' até o momento');
				return void(0);
			};
			calendario.pega_proximos_render(eventos, 3);
		});
	},
	render: function() {
		var	d = 0,
			f = d,
			html = "", cal = html, nex = cal, det = nex, pptext = det,
			head = '<span class="clear"></span><ul><li>S</li><li>T</li><li>Q</li><li>Q</li><li>S</li><li>S</li><li>D</li></ul>';
		while (d < this.date.mmd.atual) {
			html += '<span class="clear"></span><ul>';
			for (var i = 0; i < 7; i++) {
				if (i == this.date.dow || d > 0) {
					d++;
				};
				html += '<li class="calendario-item '+(d > 0 && d <= this.date.mmd.atual ? 'dia-'+d : 'mes-anterior')+'">'+(d > 0 && d <= this.date.mmd.atual ? d : (d == 0 ? (this.date.mmd.anterior - (this.date.dow - i - 1)) : ++f))+"</li>";
			};
			html += "</ul>";
		};
		cal = 	'<div id="calendario">'+
				'<div class="nav-calendario">'+
					'<a href="#mes-anterior" class="nav-calendario-arrow nca-left" onclick="this.blur(); return calendario.nav.anterior()"></a>'+
					'<span class="nav-calendario-title">'+this.retorna_nome_mes(this.date.mes)+" "+this.date.ano+'</span>'+
					'<a href="#mes-posterior" class="nav-calendario-arrow nca-right" onclick="this.blur(); return calendario.nav.proximo()"></a>'+
				'</div>'+
				head+html+
				'<span class="clear"></span>'+
			'</div>';
		pptext = (calendario.modalidade == "bike" ? "saídas" : (calendario.modalidade == "ski" ? "temporadas" : "provas"));
		nex =	'<div id="proximas-provas" class="proximas-provas">';
                        if (calendario.modalidade == "ski") {
                            nex += '<span class="nav-calendario-title" style="font-size:15px;">próximas temporadas</span>';
                        }
                        else {
                            nex += '<span class="nav-calendario-title">próximas ' + (calendario.modalidade == "bike" ? "saídas" : "provas") + '</span>';
                        }
		nex +=	'<span class="clear"></span>'+
				'<span class="pp-list">carregando...</span>'+
			'</div>';
		det =	'<div id="calendario-detalhes"></div>';
		return	'<div id="box-calendario">'+
				cal+nex+
				'<span class="clear"></span>'+
				det+
				'<span class="clear"></span>'+
			'</div>';
	},
	retorna_nome_mes: function(mes) {	// retorna o nome do mês
		var	meses = ["Janeiro","Fevereiro","Março","Abril","Maio","Junho","Julho","Agosto","Setembro","Outubro","Novembro","Dezembro"];
		return	meses[mes];
	},
        retorna_nome_mes2: function(mes) {	// retorna o nome do mês
		var	meses = ["","Janeiro","Fevereiro","Março","Abril","Maio","Junho","Julho","Agosto","Setembro","Outubro","Novembro","Dezembro"];
		return	meses[mes];
	},
	define_dia_maximo: function () {	// define o número de dias que tem o mês
		var	d_atual =	new Date(this.date.ano, this.date.mes + 1, 0, "00", "00", "01"),
			d_anterior =	new Date(this.date.ano, this.date.mes, 0, "00", "00", "01");
		return {atual:d_atual.getDate(),anterior:d_anterior.getDate()};
	},
	define_dia_semana: function () {	// define em que dia da semana começa o mês
		var	d = new Date(this.date.ano, this.date.mes, 1, "00", "00", "01"),
			d = (d.getDay() -1),
			d = d < 0 ? 6 : d;
		return	d;
	},
	pega_marcadores: function(callback) {
		if (this.marcadores[this.date.ano] && this.marcadores[this.date.ano][this.date.mes]) {
			callback(this.marcadores[this.date.ano][this.date.mes]);
			return void(0);
		};
		submitForm.send({
			action:"get-calendario",
			date:this.date.ano+"-"+(this.date.mes < 9 ? "0" : "")+(this.date.mes + 1).toString(),
			modalidade:calendario.modalidade,
			onSuccess:function(retorno){
				if (!calendario.marcadores[calendario.date.ano]) {
					calendario.marcadores[calendario.date.ano] = [];
				};
				if (!calendario.marcadores[calendario.date.ano][calendario.date.mes]) {
					calendario.marcadores[calendario.date.ano][calendario.date.mes] = [];
				};
				calendario.marcadores[calendario.date.ano][calendario.date.mes] = retorno.data;
				callback(calendario.marcadores[calendario.date.ano][calendario.date.mes]);
			}
		});
	},
	pega_proximos_render: function (eventos, quantidade, oid, url) {
		var	html = '<ul style="margin-bottom:5px;">',
			oid = oid || "#proximas-provas",
			modalidade = oid.replace(/^\#proximas\-provas\-?/gi, ""),
                        mes_prova_inicio = "",
                        mes_prova_fim = "",
                        converte_nome_mes = false;
		for(var i in eventos) {
			var e = eventos[i];
			html +=	'<li style="margin-bottom:1px;">'+
					'<span class="pp-mark"></span>'+
					(e.url && e.url.length > 10 ? '<a href="'+e.url+'" class="pp-local linkOrange">' : '');
					if (modalidade == "ski" || (modalidade == "" && calendario.modalidade == "ski"))
                                            html += e.local;
                                        else
                                            html += e.detalhe;
					html += (e.url && e.url.length > 10 ? '</a>' : '')+
					'<span class="clear"></span>';
                                        if (modalidade == "ski" || (modalidade == "" && calendario.modalidade == "ski"))
                                        {
                                            if (e.inicio.charAt(3) == "0")
                                                mes_prova_inicio = calendario.retorna_nome_mes2(e.inicio.charAt(4));
                                            else
                                                mes_prova_inicio = calendario.retorna_nome_mes2((e.inicio.charAt(3))+(e.inicio.charAt(4)));
                                            if (e.fim.charAt(3) == "0")
                                                mes_prova_fim = calendario.retorna_nome_mes2(e.fim.charAt(4));
                                            else
                                                mes_prova_fim = calendario.retorna_nome_mes2(e.fim.charAt(3)+e.fim.charAt(4));
                                            converte_nome_mes = true
                                        }
					if (e.inicio != e.fim) {
                                            if(converte_nome_mes)
                                                html += '<span class="pp-data" style="margin-bottom:1px;">'+mes_prova_inicio+" a "+mes_prova_fim+'</span>';
                                            else
                                                html += '<span class="pp-data" style="margin-bottom:1px;">'+e.inicio+" a "+e.fim+'</span>';
					} else {
                                            if(converte_nome_mes)
                                                html += '<span class="pp-data" style="margin-bottom:1px;">'+mes_prova_inicio+'</span>';
                                            else
                                                html += '<span class="pp-data" style="margin-bottom:1px;">'+e.inicio+'</span>';
					}
					html += '<span class="clear"></span>'+
				'</li>';
		};
		html += '</ul>'+
			'<span class="clear"></span>'+(!quantidade || quantidade == 0 || eventos.length != 3 ? '' :
			'<a class="pp-veja-todas linkOrange" href="'+(modalidade == "" ? '#veja-todas' : (url+'/esporte/'+modalidade+'/'))+'">+veja todas as ' + (calendario.modalidade == "bike" ? "saídas" : (calendario.modalidade == "ski" ? "temporadas" : "provas")) + '</a>')+
			'<span class="clear"></span>';

		$(oid+" .pp-list").html(html);

                if (modalidade == "") {
                    if (!$(oid+" .pp-veja-todas")[0]) {
                            if ($(oid+" .pp-list").height() >= 180) {
                                    $(oid).css({
                                            position:"absolute",
                                            float:"left",
                                            marginLeft:(is_ie7 ? 20 : 540),
                                            width:210,
                                            height:330,
                                            "-o-box-shadow":"1px 2px 5px #111",
                                            "-moz-box-shadow":"1px 2px 5px #111",
                                            "-webkit-box-shadow":"1px 2px 5px #111"
                                    });
                                    if (is_ie) {
                                            $(oid).css({
                                                    border:"1px SOLID #CCC"
                                            });
                                    };
                            };
                            if ($(oid+" .pp-list").height() >= 280) {
                                    $(oid+" .pp-list").css({
                                            height:280,
                                            overflow:"hidden",
                                            backgroundColor:"#EEE",
                                            display:"block"
                                    }).scrollbar({
                                            autoHide:3500
                                    });
                            };
                            return void(0);
                    };

                    $(oid+" .pp-veja-todas")[0].onclick = function () {
                            if (modalidade != "") {
                                    calendario.modalidade = modalidade;
                            };
                            this.blur();
                            calendario.pega_proximos(0, function(eventos){
                                    if (eventos.length == 0) {
                                            $(oid+" .pp-list").html('Não há próximas ' + (calendario.modalidade == "bike" ? "saídas" : (calendario.modalidade == "ski" ? "temporadas" : "provas")) + ' até o momento');
                                            return void(0);
                                    };
                                    calendario.pega_proximos_render(eventos, null, oid);
                            });
                            return false;
                    };
                };

	},
	pega_proximos: function(quantidade, callback) {
		if (this.proximos && this.proximos.length > 0 && quantidade > 0) {
			callback(this.proximos);
			return void(0);
		};
		submitForm.send({
			action:"get-proximas-provas",
			quantidade:(quantidade ? quantidade : "false"),
			modalidade:calendario.modalidade,
			onSuccess:function(retorno) {
				if (!calendario.proximos) {
					calendario.proximos = [];
				};
				calendario.proximos = retorno.data;
				callback(calendario.proximos);
			}
		});
	},
	nav: {
		proximo: function () {
			var	mes = calendario.date.mes+1,
				ano = calendario.date.ano;
			if (mes > 11) {
				mes = 0;
				ano++;
			};
			calendario.show(ano,mes,calendario.$target,calendario.$target_method);
			return false;
		},
		anterior: function () {
			var	mes = calendario.date.mes-1,
				ano = calendario.date.ano;
			if (mes < 0) {
				mes = 11;
				ano--;
			};
			calendario.show(ano,mes,calendario.$target,calendario.$target_method);
			return false;
		}
	}
};

var dicas = function (odi) {
	var is_oid_opened = $(".dica-item", $(odi).parent()).hasClass("aberto");
	$(".aberto").removeClass("aberto").hide();
	if (is_oid_opened) {
		return false;
	};
	$(".dica-item", $(odi).parent()).addClass("aberto").show()
};


var admin = {
	depoimento: {
		remove: function(id_contato) {
			$("#post-"+id_contato).fadeOut(function(){
				$(this).remove();
			});
		},
		aprova: function(id_contato) {
			if (!confirm("Você está preste a aprovar este depoimento.\nDeseja continuar?")) {
				return  false;
			};
			$.post(__URL_TEMPLATE+"/inc/ajax.php?action=aprova-depoimento", {
				id_contato:id_contato
			}, function(retorno){
				admin.depoimento.remove(id_contato);
			});
			return  false;
		},
		reprova: function(id_contato, is_delete) {
			var msg = "Você está preste a "+(is_delete ? "excluir" : "reprovar")+" este depoimento.\nDeseja continuar?";
			if (!confirm(msg)) {
				return  false;
			};
			$.post(__URL_TEMPLATE+"/inc/ajax.php?action=reprova-depoimento", {
				id_contato:id_contato
			}, function(retorno){
				admin.depoimento.remove(id_contato);
			});
			return  false;
		}
	},
	calendario: {
		editArea: function (obj) {
			var	dt = new Date(),
				d = obj ? obj.onblur() : {};
			d.id_calendario = d.id_calendario || 0;
			d.data_inicio = d.data_inicio || dt.getFullYear()+"-"+(dt.getMonth() < 9 ? "0" : "")+(dt.getMonth()+1)+"-"+(dt.getDate() < 10 ? "0" : "")+dt.getDate()+" "+(dt.getHours() < 10 ? "0" : "")+dt.getHours()+":"+(dt.getMinutes() < 10 ? "0" : "")+dt.getMinutes()+":"+(dt.getSeconds() < 10 ? "0" : "")+dt.getSeconds();
			d.data_fim = d.data_fim || d.data_inicio;
			d.prova = d.prova || "";
			d.detalhes = d.detalhes || "";
			d.cidade = d.cidade || "";
			d.pais = d.pais || "";
			d.url = d.url || "";
			d.resultado_publicado = d.resultado_publicado || "nao";
			d.ativa = d.ativa || "sim";
			d.categoria = d.categoria || "outros";

			$calEditArea = $("#calendario-edit-area");
			if (!$calEditArea[0]) {
				$("body").prepend('<div id="calendario-edit-area"></div>');
				$calEditArea = $("#calendario-edit-area");
			}
			var	html =	'\
					<input type="hidden" id="id_calendario" name="id_calendario" value="'+d.id_calendario+'" />\
					<label for="prova">Prova: </label><br />\
						<input type="text" id="prova" name="prova" value="'+d.prova+'" /><br />\
					<br /><label class="data" for="data_inicio">Data de Início: </label><input type="text" id="data_inicio" name="data_inicio" value="'+d.data_inicio.replace(/^(\d+)-(\d+)-(\d+).+$/, "$3/$2/$1")+'" /><br />\
					<br /><label class="data" for="data_fim">Data Final: </label><input type="text" id="data_fim" name="data_fim" value="'+d.data_fim.replace(/^(\d+)-(\d+)-(\d+).+$/, "$3/$2/$1")+'" /><br />\
					<br /><label for="detalhes">Detalhes: </label><br />\
						<input type="text" id="detalhes" name="detalhes" value="'+d.detalhes+'" /><br />\
					<br /><label for="cidade">Cidade: </label><br />\
						<input type="text" id="cidade" name="cidade" value="'+d.cidade+'" /><br />\
					<br /><label for="pais">Pais: </label><br />\
						<input type="text" id="pais" name="pais" value="'+d.pais+'" /><br />\
					<br /><label for="url">URL: </label><br />\
						<input type="text" id="url" name="url" value="'+d.url+'" /><br />\
					<br /><label class="check" for="rp-nao">Resultado Publicado: </label>\
						<input type="radio" id="rp-nao" name="rp" value="nao" '+(d.resultado_publicado == "nao" ? 'checked="checked"' : "")+'/><label for="rp-nao"> Não</label>\
						<input type="radio" id="rp-sim" name="rp" value="sim" '+(d.resultado_publicado == "sim" ? 'checked="checked"' : "")+'/><label for="rp-sim"> Sim</label><br />\
					<br /><label class="check" for="ativa-nao">Prova Ativa: </label>\
						<input type="radio" id="ativa-nao" name="ativa" value="nao" '+(d.ativa == "nao" ? 'checked="checked"' : "")+'/><label for="ativa-nao"> Não</label>\
						<input type="radio" id="ativa-sim" name="ativa" value="sim" '+(d.ativa == "sim" ? 'checked="checked"' : "")+'/><label for="ativa-sim"> Sim</label><br />\
					<br /><label for="modalidade">Modalidade: </label>\
					<select name="modalidade" id="modalidade" style="width:170px">\
						<option value="0"> -- Selecione -- </option>\
						<option value="corrida" '+(d.modalidade == "corrida" ? 'selected="selected"' : '')+'>Corrida</option>\
						<option value="bike" '+(d.modalidade == "bike" ? 'selected="selected"' : '')+'>Bike</option>\
						<option value="ski" '+(d.modalidade == "ski" ? 'selected="selected"' : '')+'>Ski</option>\
						<option value="triathlon" '+(d.modalidade == "triathlon" ? 'selected="selected"' : '')+'>Triathlon</option>\
						<option value="outros" '+(d.modalidade == "outros" ? 'selected="selected"' : '')+'>Outros</option>\
					</select><br />\
					<br /><button onclick="admin.calendario.salva()" class="button">Salvar</button>\
					<button onclick="admin.calendario.close()" class="button">Cancelar</button>\
				';
			$calEditArea.html(html);
			$("label, input, select, option", $calEditArea).css({
				fontSize:"11px",
				height:"2em",
				padding:"2px"
			});
			$("button", $calEditArea).css({
				fontSize:"11px"
			});
			$("#prova, #detalhes, #cidade, #pais, #url", $calEditArea).css({
				width:260
			});
			$(".data, .check", $calEditArea).css({
				display:"block",
				float:"left",
				width:140
			});
			$("#data_inicio, #data_fim", $calEditArea).css({
				width:100,
				textAlign:"center"
			});
			$calEditArea.css({
				position:"absolute",
				border:"1px SOLID #DFDFDF",
				"border-radius":10,
				"o-border-radius":10,
				"-moz-border-radius":10,
				"-webkit-border-radius":10,
				"-moz-box-shadow":"0px 3px 10px #000",
				width:260,
				padding:20,
				backgroundColor:"#FFF",
				zIndex:99
			}).animate({
				top:($(document).scrollTop() + 40),
				left:300
			});
			$("#data_inicio, #data_fim").datepicker({
				showOtherMonths: true,
				selectOtherMonths: true,
				dateFormat:"dd/mm/yy"
			});
			return false;
		},
		close: function () {
			$("#calendario-edit-area").animate({
				width:0,
				height:0,
				top:0,
				left:0,
				opacity:0
			}, function(){
				$(this).remove();
			});
		},
		massAction: function() {
			if ($("#massActionCombo").val() != "excluir" || !confirm("Deseja excluir estas provas?")) {
				return false;
			};
			$(".post-input-mass").each(function(){
				if (this.checked) {
					admin.calendario.excluir(this.value, true);
				};
			});
			setTimeout(function(){
				alert("Provas excluídas com sucesso.");
				location.reload();
			}, 150);
			return false;
		},
		excluir: function (cal_id, ignore_confirm) {
			if (!ignore_confirm && !confirm("Deseja excluir esta prova?")) {
				return false;
			};
			var params = {codigo:cal_id};
			$.post(__URL_TEMPLATE+"/inc/ajax.php?action=delete-calendario", params, function(retorno){
				if (!ignore_confirm) {
					if (retorno.type == "success") {
							alert("Prova excluída com sucesso.");
							location.reload();
					} else {
						alert(retorno.message);
					};
				}
			});
		},
		salva: function (obj) {
			var	codigo	= $("#id_calendario").val(),
				prova	= $("#prova").val(),
				dt_ini	= $("#data_inicio").val().replace(/^(\d+)\/(\d+)\/(\d+)$/, "$3-$2-$1"),
				dt_fim	= $("#data_fim").val().replace(/^(\d+)\/(\d+)\/(\d+)$/, "$3-$2-$1"),
				det	= $("#detalhes").val(),
				cidade	= $("#cidade").val(),
				pais	= $("#pais").val(),
				url	= $("#url").val();
				rp	= ($("#rp-sim")[0].checked ? "sim" : "nao"),
				ativa	= ($("#ativa-sim")[0].checked ? "sim" : "nao"),
				modal	= $("#modalidade").val(),
				error	= [];
			if (prova.length < 5) {
				error[error.length] = "A prova deve ter pelo menos 5 caracteres";
			};
			if (!/^(\d{4}-\d{2}-\d{2})$/.test(dt_ini)) {
				error[error.length] = "Data inicial inválida";
			};
			if (!/^(\d{4}-\d{2}-\d{2})$/.test(dt_fim)) {
				error[error.length] = "Data final inválida";
			};
			if (cidade == "") {
				error[error.length] = "A cidade deve ser preenchida.";
			};
			if (pais == "") {
				error[error.length] = "O país deve ser preenchido.";
			};
			if (url == "") {
				error[error.length] = "A URL deve ser preenchida.";
			};
			if (modal == "0" || modal == 0) {
				error[error.length] = "Você deve selecionar uma modalidade.";
			};
			if (error.length > 0) {
				alert(error.join("\n"));
				return false;
			};
			var params = {
				codigo:codigo,
				prova:prova,
				data_inicio:dt_ini,
				data_fim:dt_fim,
				detalhes:det,
				cidade:cidade,
				pais:pais,
				url:url,
				resultado_publicado:rp,
				ativa:ativa,
				modalidade:modal
			};
			$.post(__URL_TEMPLATE+"/inc/ajax.php?action=save-calendario", params, function(retorno){
				if (retorno.type == "success") {
					alert("Calendário salvo com sucesso.");
					location.reload();
				} else {
					alert(retorno.message);
				};
			});
			return false;
		}
	}
};




if (navigator.appName=="Netscape" && parseInt(navigator.appVersion)==4) {
 widthCheck = window.innerWidth;
 heightCheck = window.innerHeight;
 window.onResize = resizeFix;
}

function resizeFix() {
 if (widthCheck != window.innerWidth || heightCheck != window.innerHeight)
 document.location.href = document.location.href;
}




var isNew=0;
var isNS4=0;
var isIE4=0;
var brow= ((navigator.appName)+(parseInt(navigator.appVersion)));
if (parseInt(navigator.appVersion >=5)) {
isNew=1}
else if (brow=="Netscape4")
{isNS4 = 1;}
else if(brow=="Microsoft Internet Explorer4")
{isIE4=1;}

docObj=(isNS4)?'document' :'document.all';
styleObj= (isNS4)?'':'.style';

function lyroff(currElem){
	$("#"+currElem).fadeOut();
/* dom= eval(docObj+'.'+currElem+styleObj);
 state = dom.visibility;
 if(state=="visible" || state=="show"){dom.visibility="hidden";}*/
}
function MM_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}

function lyron(currElem){
	$("#"+currElem).fadeIn().attr("visibility","visible");
 /*dom=eval(docObj+'.'+currElem+styleObj);
 state=dom.visibility;
 if(state=="hide" || state=="hidden"){dom.visibility="visible"};*/
}

function alterNate(elm){
if (!elm.base) elm.base = elm.value
if (elm.value == elm.base) elm.value = "";
else if (elm.value == "") elm.value = elm.base;
}

function checkmail(str)
{
 var filter = new RegExp("^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$");
 if (filter.test(str))
 {
 return true;
 }
 else
 {
 alert("O e-mail digitado não é válido!")
 return false;
 }
}


function openpopup(url, width, height, scrollbars){
window.open(url,"","toolbar=no,status=no,menubar=no,scrollbars=" + scrollbars + "top=10,left=10,width=" + width + ",height=" + height)
}

function MM_jumpMenu(targ,selObj,restore){ //v3.0
 eval(targ+".location='"+selObj.options[selObj.selectedIndex].value+"'");
 if (restore) selObj.selectedIndex=0;
}

function PegaHora(gmt) {
 data = new Date();
 //
 Horas = Math.floor(gmt);
 Minutos = 0;
 RestoMin = (gmt*60)-(Math.floor(gmt)*60);
 //
 tmpMinutos = data.getUTCMinutes()+RestoMin;
 // se for minutos > 59, aumenta 1 hora e ajusta minutos
 if (tmpMinutos > 59) {
 Minutos = Math.floor((((data.getUTCMinutes()+RestoMin)/60)-1)*60);
 Horas++;
 } else {
 Minutos = Math.abs(data.getUTCMinutes()+Math.abs(RestoMin));
 }
 //
 if (Minutos < 10) {
 Minutos = "0"+Minutos;
 }
 //
 Horas += data.getUTCHours();
 if (Horas >= 24) {
 Horas -= 24;
 }
 //
 //alert("Horário Londres:"+data.getUTCHours()+":"+data.getUTCMinutes());
 //alert("Horário Local (usuário):"+Horas+":"+Minutos);
 return Horas+":"+Minutos;
}

function documentScrollTop (pos) {
	if (window.is_safari || window.is_chrome) {
		$(document).scrollTop(pos);
	} else {
		$("html").animate({scrollTop:pos});
	};
};

$(function(){
	window.is_ie = /MSIE/g.test(navigator.appVersion);
	window.is_ie7 = /MSIE[ ]?[67]/g.test(navigator.appVersion);
	window.is_chrome = /applewebkit(.+)chrome/gi.test(navigator.appVersion);
	window.is_safari = /applewebkit(.+)safari/gi.test(navigator.appVersion);
	if(window.is_ie7) {
		var footerReTop = function () {
			var	$s =	$("#sidebar"),
				$c =	($("#dicas-conteudo")[0] ?
						$("#dicas-conteudo") : ($("#main .conteudo")[0] ?
							$("#main .conteudo") :
							($("#container")[0] ?
								$("#container") :
								($("#content")[0] ?
									$("#content") :
									$("#main")
								)
							)
						)
					);
			$(".menu li", $s).css({lineHeight:"20px",width:"auto"});
			$(".menu .titulo", $s).css({lineHeight:"35px"});
			//$s.css({position:"absolute",left:$c.offset().left,top:$("#main").offset().top});
			$("#main-menu").css({marginTop:-60});
			var	mh = $("#main").offset().top + $("#main").height(),
				sh = $s.offset().top + $("#sidebar").height(),
				nh = ((sh > mh ? sh : mh) + 20);
			$(".rodape").css({position:"absolute",top:nh,left:$c.offset().left});
		};
		footerReTop();
	};
	document.onclick = function (e) {
		// bubbling
		var	e =	e || window.event,
			tgt =	e.target || e.srcElement,
			tag =	tgt.tagName.toLowerCase();
		if (tgt && tag && (tag == "a" || tag == "button" || tag == "option" || (tag == "input" && (tgt.type == "checkbox" || tgt.type == "radio")))) {
			tgt.blur();
		};
		if (window.is_ie7) {
			if (window.footerReTopTimeout) {
				clearTimeout(window.footerReTopTimeout);
			};
			window.footerReTopTimeout = setTimeout(function(){
				footerReTop();
				window.footerReTopTimeout = false;
			}, 1000);
		};
	};
});
