var legendaTimer 		= '';
var serviceTextTimer 	= '';
var serviceLinkTimer	= '';

var docHeight=$(document).height();var winHeight=$(window).height();var imgLoaded=false;var offset=50;function imgOndemand(){if(!imgLoaded){var p=$(window).height()+$(window).scrollTop();$('img.img-ondemand').each(function(){var $img=$(this);if($img.offset().top<p+offset){$img.attr('src',$img.attr('longdesc')).removeClass('img-ondemand')}});imgLoaded=p>=docHeight}}$(function(){imgOndemand()});$(window).scroll(function(){imgOndemand()});

(function($) {
  var cache = [];
  // Arguments are image paths relative to the current page.
  $.preLoadImages = function() {
    var args_len = arguments.length;
    for (var i = args_len; i--;) {
      var cacheImage = document.createElement('img');
      cacheImage.src = arguments[i];
      cache.push(cacheImage);
    }
  }
})(jQuery)

$(function(){
	
	jQuery.preLoadImages( raiz + '_img/bg-orcamento.png', raiz + '_img/bg-work-thumb.png', raiz + '_img/search-field-hover.jpg' );
	
	$('a[rel=external]').attr( 'target', '_blank' );
	
	$('a.nav').click(
		function(){

			var atual 	= parseInt( $('span#screen').find('a').attr('id').replace(/highlight-/,'') );
			var cod		= 0;
			
			if( $(this).hasClass('left') )
			{
				if( atual < 1 ) cod = total_destaques - 1;
				else cod = atual - 1;
			}
			else
			{
				if( atual >= ( total_destaques - 1 ) ) cod = 0;
				else cod = atual + 1;
			}

			var num		= parseInt( cod ) * 429;
			var margin	= '-'+num+'px';
			
			$('#tv-text').fadeOut(function(){
				$('#tv-text div').hide();
				$('#projeto-screen-'+cod).show();
				
				$('div#screen-slider').animate({marginLeft: margin});
				
				$('span#screen').find('a').attr('id', 'highlight-'+cod);
				
				$('#tv-text').fadeIn(1500);
				
			});
			return false;
		}
	);
	
	$('input[type="text"], textarea').each(function(){
		if(!$(this).val()) $(this).val($(this).attr('title'));
	});
	$('input[type="text"], textarea').focus(function(){
		if($(this).val() == $(this).attr('title')) $(this).val('');
		$(this).removeClass('erro');
	});
	$('input[type="text"], textarea').blur(function(){
		if(!$(this).val()) $(this).val($(this).attr('title'));
	});
	$('div#blog-tab a').click(function(){
		if( $('div#blog').css('margin-top') == '-35px' )
		{
			$(this).parent().animate({
				marginTop: '0'
			});
			$('div#blog').animate({ 
				marginTop: '-206px'
			});
			$('div#content').unbind('click');
		}
		else
		{
			$(this).parent().animate({
				marginTop: '171px'
			});
			$('div#blog').animate({ 
				marginTop: '-35px'
			});
			$('div#content').click(function(){
				$(this).unbind('click');
				$('div#blog-tab a').parent().animate({
					marginTop: '0'
				});
				$('div#blog').animate({ 
					marginTop: '-206px'
				});
			});
		}
		return false;
	});
	
	$('a.lnk-work').live( 'click', function(){
		var cod_projetos = $(this).attr('rel');
		slideProject( cod_projetos );
		return false;
	});
	
	$('#div-btn-orcamento a, a#lnk-contato-orcamento').click(function(){
		$('body').prepend('<div id="overlay"></div>');
		$('#overlay').css({
			height : $(document).height() + 'px',
			width : $(document).width() + 'px',
		});
		$('#overlay').fadeIn('fast',function(){
			if ( $.browser.msie == true )
			{
				$(this).css( { 
					'opacity': 0.85,
					'-moz-opacity': 0.85
				});
			}
			$('#content-orcamento').css( 'top', $(window).scrollTop() + 30 );
			$('#content-orcamento').show(function(){
				$('#orcamento-top').slideDown(100,function(){
					$('#orcamento-middle').slideDown();
				});
			});
		});
		$('#overlay, #lnk-cancelar-orcamento, #lnk-fechar-orcamento').live( 'click', function(){
			$('#orcamento-middle').slideUp(function(){
				$('#orcamento-top').slideUp(100,function(){
					$('#content-orcamento').hide(function(){
						$('#overlay').fadeOut(200,function(){
							$(this).remove();
						});
					});
				});
			});
			return false;
		});
		return false;
	});
	
	$('ul#list-services a').click(function(){return false;});
	
	$('ul#list-services a').mouseover(function(){
		clearTimeout( serviceTextTimer );
		clearTimeout( serviceLinkTimer );
		var c 	= $(this).offset();
		$('#service-text').css( 'top', c.top - 30 );
		if( c.top + $('#service-text').height() > $('body').height() ) $('body').height( $('body').height() + 200 );
		$('ul#list-services a').removeClass('active');
		$(this).addClass('active');
		var cod = $(this).attr('rel');
		if( $('#service-text').is(':visible') )
		{
			$('#service-text ul li').hide();
			$('#service-'+cod).fadeIn();
		}
		else
		{
			$('#service-text').fadeIn('fast',function(){
				$('#service-text ul li').hide();
				$('#service-'+cod).show();
			});
		}
	});
	$('ul#list-services a').mouseout(function(){
		var cod = $(this).attr('rel');
		serviceTextTimer = setTimeout( "$('#service-text').fadeOut('fast',function(){$('#service-text ul li').hide();});", 1000 );
		serviceLinkTimer = setTimeout( "$('ul#list-services a').removeClass('active');", 1000 );
	});
	
	$('#service-text').mouseover(function(){
		clearTimeout( serviceTextTimer );
		clearTimeout( serviceLinkTimer );
	});
	
	$('#service-text').mouseout(function(){
		serviceTextTimer = setTimeout( "$('#service-text').fadeOut('fast',function(){$('#service-text ul li').hide();});", 1000 );
		serviceLinkTimer = setTimeout( "$('ul#list-services a').removeClass('active');", 1000 );
	});
	
	$('#frm-contato, #frm-orcamento').submit(function(){
		return false;
	});
	
	$('#btn-orcamento').click(function(){
		
		var erro 		= false;
		
		$('#frm-orcamento input, #frm-orcamento select, #frm-orcamento textarea').each(function(){
			if( !$(this).val() || $(this).val() == $(this).attr('title') ) 
			{
				$(this).addClass('erro');
				erro = true;
			}
		});
				
		if( !erro )
		{
			var nome 		= $('#orcamento_nome').val();
			var email		= $('#orcamento_email').val();
			var empresa		= $('#orcamento_empresa').val();
			var tipo		= $('#orcamento_tipo').val();
			var faixa		= $('#orcamento_faixa').val();
			var referencias	= $('#orcamento_referencias').val();
			var descricao	= $('#orcamento_descricao').val();
			
			$.post(raiz+"_inc/orcamento.inc.php",{nome:nome,email:email,empresa:empresa,tipo:tipo,faixa:faixa,referencias:referencias,descricao:descricao},function(data){
				$('#orcamento-middle').html('<p style="font-weight:900;padding-left:40px;padding-top:40px;color:#666;">Seu pedido de orçamento foi enviado!<br /><br />Em breve estarei em contato para definirmos mais pontos do projeto.<br /><br /><a href="#" id="lnk-fechar-orcamento">fechar</a></p>')
			});
			
		}
		
		return false;
	});
	
	$('#btn-contato').click(function(){
		$(this).val('Aguarde...');
		$(this).css('background-position', '0px -33px');
		
		$('#nome').removeClass( 'erro' );
		$('#email').removeClass( 'erro' );
		$('#mensagem').removeClass( 'erro' );
		
		var erro 		= false;
		var nome		= $('#nome').val();
		var email		= $('#email').val();
		var mensagem	= $('#mensagem').val();
		
		if( nome == 'Como você se chama?' ) nome = '';
		if( email == 'Respondo pra qual e-mail?' ) email = '';
		if( mensagem == 'Diga.' ) mensagem = '';
		
		if( !nome )
		{
			$('#nome').addClass('erro');
			erro = true;
		}
		
		if( !email || !validaEmail( email ) )
		{
			$('#email').addClass('erro');
			erro = true;
		}
		
		if( !mensagem )
		{
			$('#mensagem').addClass('erro');
			erro = true;
		}
		
		if( erro )
		{
			$(this).val( 'Erro' );
			$(this).css('background-position', '0px -66px');
		}
		else
		{
			$.post(raiz+"_inc/contato.inc.php",{nome:nome,email:email,mensagem:mensagem},function(data){
				$('#nome').val('');
				$('#email').val('');
				$('#mensagem').val('');
				$('#btn-contato').css('background-position', '0px -99px');
				$('#btn-contato').val( 'Enviado!' );
			});
		}
		
		return false;
	});
	
	$('#f_keyword').keyup(function(){
		var keyword = $(this).val();
		if( keyword.length > 2 )
		{
			$.getJSON( raiz + '_inc/livesearch.inc.php?search=', {keyword: keyword, ajax: 'true'}, function(j){
				var options = '';
				if( j.length > 0 )
				{
					var alt 	= '';
					var total	= j[0].total;
					for (var i = 0; i < j.length; i++) {
						if( i%2 ) alt = '';
						else alt = 'alt';
						options += '<li class="clearfix '+alt+'">';
						options += '<p class="details"><a href="#" class="lnk-work" rel="'+j[i].cod_projetos+'">+ info</a></p>';
						options += '<img src="'+raiz+'_img/projetos/'+j[i].cod_projetos+'/'+j[i].imagem+'_ls.jpg" width="60" height="60" />';
						options += '<h3>'+j[i].titulo+'</h3>';
						options += '<p class="date">'+j[i].data_publicacao+' <span>'+j[i].tipo+'</span></p>';
						options += '</li>';
					}
					options += '<li class="allresults"><a href="#" id="lnk-fechar-ls">fechar</a>';
					if( total > 4 )
					{
						options += ' ou <a href="'+raiz+'?f_keyword='+keyword+'">ver todos os resultados ('+total+')</a>';
					}
					options += '</li>';
					if( !$('#search-results').html() )
					{
						$('div#search').append( '<ul id="search-results">'+options+'</ul>' );
					}
					else
					{
						$('ul#search-results').html( options );
					}
					if( !$('ul#search-results').is(':visible') ) $('ul#search-results').slideDown( 'fast' );
					$('#lnk-fechar-ls').unbind('click');
					$('#lnk-fechar-ls').click(function(){
						$('ul#search-results').remove();
						return false;
					});
				}	
				else
				{
					$('ul#search-results').remove();
				}
			});
		}
		else
		{
			$('ul#search-results').remove();
		}
	});
	
	$('ul#pagination li a').click(function(){
		
		$('ul#pagination li a').removeClass( 'active' );
		$(this).addClass( 'active' );
		
		var pg 			= parseInt( $(this).attr('href') );
		var pg_atual 	= parseInt( $('#pagina_atual').val() );
		$('#pagina_atual').val(pg);
		var margin		= 0;
		margin			-= 942 * ( pg - 1);
		
		$('div#projects-slider').animate({marginLeft: margin},function(){
			
		});
		return false;
	});
	
}); // fim document.readyit

var slideProject = function( cod_projetos )
{
	$('body').prepend('<div id="overlay"></div>');
	$('#overlay').css({
		height : $(document).height() + 'px',
		width : $(document).width() + 'px',
	});
	$('#overlay').fadeIn('fast',function(){
		if ( $.browser.msie == true )
		{
			$(this).css( { 
				'opacity': 0.85,
				'-moz-opacity': 0.85
			});
		}
		$('#work-space').css( 'top', $(window).scrollTop() + 30 );
		$('#work-space').show(function(){
			$('#work-space-top').slideDown(100,function(){
				$('#work-space-middle').slideDown(function(){
					//$('.work-nav').fadeIn('fast');
					$('#work-space-loading').show();
					$.getJSON( raiz + '_inc/projeto.inc.php?search=', {cod_projetos: cod_projetos, ajax: 'true'}, function(j){
						$('#work-space-container h3 strong').html( j.titulo );
						$('#work-space-container h3 span:last a').html( '#' + j.categoria );
						$('#work-space-container h3 span:last a').attr('href', raiz + 'projetos/' + j.categoria + '/' );
						$('#work-desc p:first').html( j.descricao );
						$('#work-when').html( j.data_projeto );
						$('#work-where').html( j.onde );
						$('#work-tags').html( j.tags );
						var options = '';

						if( j.multimidia.length > 0 )
						{
							for( var i = 0; i < j.multimidia.length; i++ )
							{
								options += '<li><a href="'+raiz+'_img/projetos/'+j.cod_projetos+'/'+j.multimidia[i].codigo+'.jpg" class="thumb-project" rel="projeto" title="'+j.multimidia[i].legenda+'"><img src="'+raiz+'_img/projetos/'+j.cod_projetos+'/'+j.multimidia[i].codigo+'_ws.jpg" width="120" height="80" /></a></li>';
							}
							$('#work-pictures ul').html( options );
							$('a.thumb-project').fancybox({ 'zoomSpeedIn': 300, 'zoomSpeedOut': 300, 'overlayShow': false });
							$('#work-space-loading').fadeOut( 'fast', function(){
								$('#work-space-container').fadeIn('fast');
							});
						}
						else
						{
							$('#work-pictures ul').html( '' );
						}
						
						Cufon.replace('#work-space-container h3 strong');
						
					});
				});
			});
		});
	});
	$('.work-close a').unbind('click');
	$('#overlay, .work-close a').click(function(){
		//$('.work-nav').fadeOut(function(){
		$('#work-space-container').fadeOut('fast', function(){
			$('#work-space-middle').slideUp(function(){
				$('#work-space-top').slideUp(100,function(){
					$('#work-space').hide(function(){
						$('#overlay').fadeOut(200,function(){
							$(this).remove();
						});
					});
				});
			});
		});
		//});
		return false;
	});
};

// valida e-mail
var validaEmail = function(s) {
	var regexpEmail = /\w{1,}[@][\w\-]{1,}([.]([\w\-]{1,})){1,3}$/;
	return regexpEmail.test(s);
}; // fim validaEmail