// funcoes gerais ---------------------------------------------------------------------------------------------
$(function() {
	// Initialize history plugin.
	// The callback is called at once by present location.hash. 
	$.historyInit(pageload);
	
	
	// set onlick event for buttons
	$("a[@rel='history']").click(function(){
		var hash = this.href;
		hash = hash.replace(/^.*#/, '');
		// moves to a new page. 
		// pageload is called at once. 
		$.historyLoad(hash);
		return false;
	});
	
	
	// fix background imagem on ie
	try {
	  document.execCommand('BackgroundImageCache', false, true);
	} catch(e) {}


	// focus nos campos do formulario
	$('#contato input, #contato textarea').focus(function(){
		if ($(this).val()==$(this).attr('default')) {
			$(this).val('');
		}
	});
	// blur nos campos do formulario
	$('#contato input, #contato textarea').blur(function(){
		if ($(this).val()=='') {
			$(this).val($(this).attr('default'));
		}
	});
	// envia formulario de contato
	$('#contato').submit(function(){
		for (i=0; i<$(this).children('*').length; i++){
			if($(this).children('*:eq('+i+')').val() == $(this).children('*:eq('+i+')').attr('default')) {
				alert('Preencha o campo ' + $(this).children('*:eq('+i+')').attr('default'));
				$(this).children('*:eq('+i+')').focus();
				return false;
			}
			if ($(this).children('*:eq('+i+')').attr('name')=='email' && !checkMail($(this).children('*:eq('+i+')').val())) {
				alert('Informe um e-mail válido');
				$(this).children('*:eq('+i+')').focus();
				return false;
			}
		}
	$('#contatoLoading').html('<img src="img/loading_right.gif" width="16" height="16" align="absmiddle" /> &nbsp; enviando...');
	// envia o form via ajax
	$.ajax({
		type: "POST",
		url: "fmail.php",
		data: $("#contato").serialize(),
		success: function(msg){
			if(msg=='sucesso'){
				$('#contatoLoading').html('');
				document.forms['contato'].reset();
				alert('Recebemos a sua mensagem.\nEm breve entraremos em contato.');
			} else {
				$('#contatoLoading').html('<div class="erro">Ocorreu um erro ao enviar a mensagem.<br />\nTente novamente mais tarde!</div>');
			}
		},
		error: function(){
			$('#contatoLoading').html('<div class="erro">Ocorreu um erro na requisição ajax.<br />\nTente novamente mais tarde!</div>');
		}
	 });

	return false;
	});


	// clientes do portfolio
	vAtual = parseInt($('span#atual').html());
	slideshow(vAtual);
	
	// botoes de controle dos clientes (proximo)
	$('a.next').click(function(){
		if (typeof(cliCont) != 'undefined') {
			clearTimeout(cliCont);
		}
		vAtual = parseInt($('span#atual').html());
		slideshow(vAtual);
		return false;
	});
	// botoes de controle dos clientes (anterior)
	$('a.prev').click(function(){
		if (typeof(cliCont) != 'undefined') {
			clearTimeout(cliCont);
		}
		vAtual = parseInt($('span#atual').html()) - 2;
		if (vAtual < 0) vAtual=parseInt($('span#total').html()-1);
		slideshow(vAtual);
		return false;
	});
	
});
// ------------------------------------------------------------------------------------------------------------




// hover nas noticias -----------------------------------------------------------------------------------------
function noticiaHover(obj, act) {
	if (act=='hover') {
		$(obj).addClass('noticiaHover');
	} else {
		$(obj).removeClass('noticiaHover');
	}
}
// ------------------------------------------------------------------------------------------------------------




// carrega clientes da home -----------------------------------------------------------------------------------
function slideshow(pAtual) {
	pTotal = parseInt($('span#total').html());
	proximo = pAtual + 1;
	if (proximo > pTotal) proximo=1;
	$('#portfolioLoad').html('<div class="ident"><img src="img/loading_branco.gif" align="absmiddle" />&nbsp; carregando...</div><div id="note" style="color:#999999;padding:30px 0px 0px 102px;width:410px;height:382px;"><img src="img/loading_cinza.gif" style="width:16px;height:16px;top:30px;left:82px;" align="absmiddle" />carregando...</div>');
	$.ajax({
	   type: "GET",
   	url: "clientes.php",
	   data: "offset="+proximo,
		cache: false,
   	success: function(data){
			$('#portfolioLoad').html(data);
   	}
	});
	$('span#atual').html(proximo);
}
// ------------------------------------------------------------------------------------------------------------




// PageLoad function ------------------------------------------------------------------------------------------
// This function is called when:
// 1. after calling $.historyInit();
// 2. after calling $.historyLoad();
// 3. after pushing "Go Back" button of a browser
function pageload(hash) {
	$("#left").html('<img src="img/loading_left.gif" width="16" height="16" align="absmiddle" /> &nbsp; carregando...');
	if (!hash) {
		hash = 3;
	}

	$.ajax({
	   type: "GET",
   	url: "_conteudo.php",
	   data: "id="+hash,
		cache: false,
   	success: function(data){
			$('#left').html(data);
   	}
	});
	
	// classe do link ativo
	$("a[@rel='history']").removeClass('active');
	$("a[@href=#"+hash+"]").addClass('active');
	
}
// ------------------------------------------------------------------------------------------------------------




// valida formulario de orcamento -----------------------------------------------------------------------------
function validaOrcamento(o){
	// campos obrigatorios
	for(i=0; i<o.elements.length; i++){
		if($('#orcamento input[@name='+o.elements[i].name+']').attr('label')!=null) {
			val = $('#orcamento input[@name='+o.elements[i].name+']').val();
			if (val=='') {
				alert('Preencha o campo ' + $('#orcamento input[@name='+o.elements[i].name+']').attr('label'));
				o.elements[i].focus();
				return false;
			}
			if (o.elements[i].name=='email' && !checkMail(val)) {
				alert('Informe um e-mail válido');
				o.elements[i].focus();
				return false;
			}
		}
	}
	
	$('#orcamentoLoading').html('<img src="img/loading_left.gif" width="16" height="16" align="absmiddle" /> &nbsp; enviando...');
	$('#orcamentoForm').hide();
	// envia o form via ajax
	$.ajax({
		type: "POST",
		url: "fmail.php",
		data: $("#orcamento").serialize(),
		success: function(msg){
			if(msg=='sucesso'){
				$('#orcamentoLoading').html('Recebemos sua solicitação de orçamento.<br />\nEm breve entraremos em contato.');
			} else {
				$('#orcamentoLoading').html('<div class="erro">Ocorreu um erro ao enviar o orçamento.<br />\nTente novamente mais tarde!</div>');
				$('#orcamentoForm').show();
			}
		},
		error: function(){
			$('#orcamentoLoading').html('<div class="erro">Ocorreu um erro na requisição ajax.<br />\nTente novamente mais tarde!</div>');
			$('#orcamentoForm').show();
		}
	 });

	return false;
}
// ------------------------------------------------------------------------------------------------------------




// abre zoom para fotos ---------------------------------------------------------------------------------------
function zoom(pImg) {
	window.open('../img/_zoom.php?foto='+pImg, 'zoom', 'top=160, left=252, width=510, height=410, status=yes');
}
// ------------------------------------------------------------------------------------------------------------




// valida endereco de e-mail ----------------------------------------------------------------------------------
function checkMail(mail){
	var er = new RegExp(/^[A-Za-z0-9_\-\.]+@[A-Za-z0-9_\-\.]{2,}\.[A-Za-z0-9]{2,}(\.[A-Za-z0-9])?/);
	if(typeof(mail) == "string"){
		if(er.test(mail)){ return true; }
	}else if(typeof(mail) == "object"){
		if(er.test(mail.value)){
			return true;
		}
	}else{
		return false;
	}
}
// ------------------------------------------------------------------------------------------------------------




// preload images ---------------------------------------------------------------------------------------------
jQuery.preloadImages = function() {
  for(var i = 0; i<arguments.length; i++)   {
    jQuery("<img>").attr("src", arguments[i]);
  }
}
// ------------------------------------------------------------------------------------------------------------