document.getElementsByTagName('html')[0].className = 'js';


var CORTEL_BASE_URL = '/';

// fontes IE
window.Cufon && Cufon('#header .nav > li > a, #header .submenu em, .nav.empreendimento a, #acesso legend, .modulo h2, .nav h2, .interna :header, #right .links h2, ul[class^=lista_] .title');

//registra cookie
function GerarCookie(strCookie, strValor, lngDias){
    var dtmData = new Date();

    if(lngDias){
        dtmData.setTime(dtmData.getTime() + (60*3000));
        var strExpires = "; expires=" + dtmData.toGMTString();
    } else {
        var strExpires = "";
    }
    document.cookie = strCookie + "=" + strValor + strExpires + "; path=/";
}

function LerCookie(strCookie) {
    var strNomeIgual = strCookie + "=";
    var arrCookies = document.cookie.split(';');

    for(var i = 0; i < arrCookies.length; i++) {
        var strValorCookie = arrCookies[i];
        while(strValorCookie.charAt(0) == ' ') {
            strValorCookie = strValorCookie.substring(1, strValorCookie.length);
        }
        if(strValorCookie.indexOf(strNomeIgual) == 0) {
            return strValorCookie.substring(strNomeIgual.length, strValorCookie.length);
        }
    }
    return null;
}

/* ------------------------------- */
// DOMReady
jQuery().ready(function($){

	// DHTML capa
	if (LerCookie('cortelDHTML') != 'dhtml'){
		GerarCookie('cortelDHTML', 'dhtml', 1);
		
		$('#telaAgora').hide();
		$('#telaDepois').hide();
		$('#tela1').show();
		
		$('#btAgora').click(function() {
			$('#tela1').hide();
			$('#telaAgora').fadeIn("slow");
			return false;
		});
		
		$('#btDepois').click(function() {
			$('#tela1').hide();
			$('#telaDepois').fadeIn("slow");
			return false;
		});
		
		$('.btFechar').click(function() {
			$('#tela1').hide();
			$('#telaAgora').hide();
			$('#telaDepois').hide();
			$('#btFechar').hide();
			return false;
		});
		
		$('.btSubmit').click(function() {
			var nome = $('input[name=nome]').val();
			var rodar = $('input[name=rodar]').val();
			var telefone = $('input[name=telefone]').val();
			var dataString = 'nome=' + nome + '&telefone=' + telefone + '&rodar=' + rodar;
			var url = "php/enviaFormDhtml.php"; // the script where you handle the form input.
			$.ajax({
					type: "POST",
					url: url,
					data: dataString,
					success: function(data){
					   alert('Dados enviados com sucesso, em breve um consultor entrará em contato. Obrigado!');
					   $('#tela1').hide();
					   $('#telaAgora').fadeOut("slow");
					   $('#telaDepois').hide();
					}
			});
			return false;
		});
	} else {
		$('#telaAgora').hide();
		$('#telaDepois').hide();
		$('#tela1').hide();
		$('#btFechar').hide();
	}
	// FINAL DHTML CAPA
	
	
	jQuery.fn.delayHide = function(){
		return this.queue(function(){ $(this).hide() });
	};

	// hover menu cortel
	$('#header .nav > li').each(function(){
		var
			self = $(this),
			sub = self.find('.submenu').hide(),
			h = sub.height(),
			speed = 150+~~(h/1.5);
		sub.css({ height: 0 });

		function showMenu(){
			sub.stop().show().animate({ height: h }, speed);
		}
		function hideMenu(){
			sub.stop().animate({ height: 0 }, speed*0.8, function(){
				$(this).hide();
			});
		}
		self.hover(showMenu,hideMenu);
		self.find('a').focus(showMenu).blur(hideMenu);
	});

	//tabela com paginacao
	$("#tabela-velorios")
		.tablesorter({widgets: ['zebra']})
		.tablesorterPager({container: $("#paginacao"), size: 10});

	// menu acesso/login
	$('#acesso input').inlineLabel();

	//adicionar homenagem mural
	$('#lnk-add-homenagem').click(function(){
	  $('#form-add-homenagem').slideToggle();
	  return false;
	});

	// para border-bottom em listas
	$('li:last-child').addClass('last');

	if (jQuery.fn.ride)
		$('#mod-velorios > ul').ride({ loop:false });

	/* -------------- */

	//////////////////////////
	// validacao formulario //
	//////////////////////////
	
	jQuery.extend(jQuery.validator.messages, {
		required: "Preencha este campo"
	});
	
	//nome e email para download
	$('#formdownload #contato').validate({
		submitHandler: function(){  
			$.post(CORTEL_BASE_URL+'cms/index.php?a=conteudoAjax/cerimoniaperson/ajaxEnviaContato', $('#formdownload #contato').serialize(),
	    		function(retorno){
	    			if (/pdf/.test(retorno)){
					$.fancybox.close();
					window.location.href = CORTEL_BASE_URL+'upload/cremacaoperson/'+retorno;
	    			}else{
					alert("Erro ao enviar dados, tente novamente.");
	    				$.fancybox.close();
	    			}
	    		});
	    		return false;
		},
		ignore: '.ignorereq',
		rules: {
			nome: { required: true },
			email: { required: true, email: true }
		},
		messages: {
			nome: "Voce precisa preencher este campo",
			email: "Voce precisa fornecer um e-mail válido"
		}
	});

	//outros formularios	
	var $contato = $('#contato');

	if ($contato.length)
	{
		$contato.validate({
			ignore: '.ignorereq',
			rules: {
				assunto: { required: true },
				nome: { required: true },
				email: { required: true, email: true },
				endereco: { required: true },
				mensagem: { required: true },
				curriculo: { required: true },
				velado: {required: true},
				submitHandler: function(){}
			},
			messages: {
				assunto: "Voce precisa preencher este campo",
				nome: "Voce precisa preencher este campo",
				email: "Voce precisa fornecer um e-mail válido",
				mensagem: "Voce precisa escrever uma mensagem",
				curriculo: "Voce precisa selecionar seu currículo",
				velado: "Você precisa preencher este campo"
			}
		});
	}

	/* -------------- */

	/*
	* NOTICIAS / EVENTOS / ATENDIMENTOS AJAX
	*/
	function carregar_conteudo(id, area){
		$.getJSON(CORTEL_BASE_URL+'cms/index.php?a=conteudoAjax/'+area+'/ajaxBuscaDados', {id: id, site: 1}, function(objUsuario){
			distribuiDados(area, objUsuario);
			window.Cufon && Cufon.refresh();
			window.scrollTo(0, $('#center').offset().top );
		});
	};

	$('.lista_eventos, .lista_noticias').find('li a').click(function(){
		$('#divDetalheItem').slideUp();
		var dados = $(this).closest('li').getData();
		carregar_conteudo(dados.id, dados.area);
		return false;
	});

	var item = location.href.match(/\/(\w+)(#|\/)(\/?\d+)$/);
	if (item){
		var
			area = item[1],
			tipo = item[2],
			id_obj = item[3];
	}
	if (tipo == '/' && (area == 'eventos' || area == 'noticias' || area == 'atendimentos')){
		location.href = location.href.replace(/#\d+$/, '').replace(/\/(?=\d+)/, '#');
	}

	if (item && area && id_obj){
		carregar_conteudo(id_obj, area);
	};

	// transformar links da capa em ajax
	$('#mod-noticias,#mod-eventos').find('li > a').attr('href', function(){
		return this.href.replace(/(\w+)\/(\d+)$/, '$1#$2');
	});

	/* -------------- */

	// lightbox noticias/eventos
	$('#divDetalheItem .imagemlink').fancybox();

	// FancyBox		
	//function formatTitle(title, currentArray, currentIndex, currentOpts) {
	//	return '<div id="tip7-title"><a id="fancybox-right" href="javascript:;" onclick="$.fancybox.next();" style="display: inline;"><span><img src="../cms/classes/fancybox/fancy_right.png" /></span></a><span><a href="javascript:;" onclick="$.fancybox.close();"><img src="../cms/classes/fancybox/fancy_close.png" /><br></a></span><a id="fancybox-left" onclick="$.fancybox.prev();" href="javascript:;" style="display: inline;"><span><img src="../cms/classes/fancybox/fancy_left.png" /></span></a>' + (title && title.length ? '<b>' + title + '</b>' : '' ) + 'Image ' + (currentIndex + 1) + ' of ' + currentArray.length + '</div>';
	//}

	$("a.fancybox").fancybox({
		'showCloseButton'	: false,
		'titlePosition' 	: 'inside',
		'title'		: $("a.fancybox").attr("alt")
	});
	

	//Cerimonia personalizada
	$(".crepers a#cresaojose").click(function(){
		$('#formdownload #empr').val('cresaojose');
	});
	$(".crepers a#crecristorei").click(function(){
		$('#formdownload #empr').val('crecristorei');	
	});
	$(".crepers a#cresainthilaire").click(function(){
		$('#formdownload #empr').val('cresainthilaire');		
	});

	// wait cursor ajax
	$().bind('ajaxStart', function(){
		$('#wrap').addClass('wait');
	}).bind('ajaxStop', function(){
		$('#wrap').removeClass('wait');
	});

});

/* -------------------------------------------- */

function distribuiDados(area, objeto){
	var $item = $('#divDetalheItem');

	$item.htmlData( objeto );

	if (area == 'noticias'){
		var url_img = CORTEL_BASE_URL+'upload/fotos/'+objeto.url_imagem;
		$item.find('.imagem').attr("src", CORTEL_BASE_URL+'cms/classes/TimThumb/timthumb.php?src='+url_img+'&h=200&w=270&zc=1');
		$item.find('.imagemlink').attr("href", url_img).fancybox();
	}

	location.hash = objeto.id;

	$('#divDetalheItem').slideDown();
	//!$.browser.msie && Cufon.refresh();
}


/* ------ */
/* PLUGINS */
/* ------ */
(function($){


// mapear objeto JSON para HTML
jQuery.fn.htmlData = function(data){
	var self = this;
	$.each(data, function(key,val){
		self.find('.'+key).html( val );
	});
}

/* inline labels para inputs */
jQuery.fn.inlineLabel = function(){
	return this.each(function(){

		var label = jQuery(this).prev('span'), self = jQuery(this);
		function fade(){
			label.fadeTo(300, 0.3);
		};
		function clear(){
			this.value
				? label.hide()
				: label.show() && label.css('opacity') < 1 && label.fadeTo(300, 1);
		};

		label
			.click(fade).click(function(){
				self.focus();
			});

		self
			.focus(fade).bind('keypress blur', clear)
			.trigger('blur'); // remover label se o campo ja tem valor
	});
};

// atributos data-*
jQuery.fn.getData = function(){
	var data = {};
	$.each(this[0].attributes, function(){
		if (/data-\w+/.test(this.name))
			data[this.name.replace('data-','')] = this.value;
	});
	return data;
};

// end plugins
})(jQuery);

