$(function(){
    //var NewScript=document.createElement('script');
    //NewScript.src= baseUrl()+"js/hotsite/colorbox-min.js";
    //$('head').prepend(NewScript);
	try{
	     
        //$('#foto_detalhes img').colorbox({photo: true ,href: function(){
            //return this.src;
        //}});
		$('#foto_detalhes img').lightbox({'background':'#222'},{'trigger':'#aba_fotos img'});
		$('#botao_ampliar').click(function() {
			$('#foto_detalhes img').trigger('click');
		});
			$('#box_acoes_imovel #elementos_aba > li a').click(function() {
			
			var link = $(this);
			$('.conteudo_aba').not(':hidden').fadeOut(250,function() {
				$('.conteudo_aba').filter('[id*='+$(link).html().toLowerCase()+']').fadeIn(100);
				$('#box_acoes_imovel #elementos_aba > li a').filter('.destaque').removeClass('destaque');
				$(link).addClass('destaque');
			});
		});
		
		$('.aba_fotos img').click(function(){
			var separacao = this.src.split('&');
			var troca_de = separacao[1];
                        if (separacao[2]!=undefined)
                            troca_de += '&'+separacao[2];
			var troca_para= $('.foto_detalhes img')[0].src.split('&')[1];
			var src = this.src.replace(troca_de,troca_para);
                        var title = $(this).closest('a').attr('title');
			var data = $(this).attr('data');
			var aguarde = document.createElement('span');
			$(aguarde).html('Aguarde...').css({'position':'absolute','font-size':'20px','color':'black','background':'#fff','width':'95px','opacity':0.5,'padding':'4px','border':'1px solid #000'}).attr('id','aguarde');
			$('.foto_detalhes').prepend(aguarde);
			//Posicionamento ao centro da imagem
			var width = $('.foto_detalhes img').width();
			var height = $('.foto_detalhes img').height();
			var posicao = $('.foto_detalhes img').position();
			var eixo_x = posicao.top + (height/2) - ($(aguarde).height() /2);
			var eixo_y = posicao.left + (width/2) - ($(aguarde).width() /2);
			$(aguarde).css({'top':eixo_x,'left':eixo_y});
			//Fim do posicionamento
			var tempo = $.browser.msie?10:0;
			setTimeout(function(){
				$('.foto_detalhes img').attr('src',src).load(function(){
					$(this).fadeIn(300);
					$(this).attr({'data':data,'title':title});
					$('#aguarde').remove();
				});
			},tempo);
		});
	}catch(e) { 
		
	}
    
	$(document).ready(function(){
	    var gotoAba = $('input#aba-hidden').val();
	    if (gotoAba == 3)
	        $('ul#elementos_aba li:last a').click();
	});
	$('#submit_contato').live('click',function() {
            var bt = this;
            erros = '';
            vazio = new RegExp('[a-z0-9]');
            email = new RegExp(/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/);
            var obrigatorios = ['input[name=nome]','input[name=email]','textarea[name=mensagem]'];
            for(var i in obrigatorios) {
                var elem = $(obrigatorios[i]);
                if (!vazio.test($(elem).val)|| $(elem).attr('title')==$(elem).val()) {
                    $(elem).css('border','1px solid red');
                    erros += '<p>Preencha o campo '+$(elem).attr('name')+'</p>';
                }
                if ($(elem).attr('name')=='email') {
                    if (!email.test($(elem).val())) {
                        $(elem).css('border','1px solid red');
                        erros += '<p>Endereço de email inválido.</p>';
                    }
                }
            }
            if (vazio.test(erros))
                $('#msg_erro').html(erros);
            else {
				if ($('#codigo_imovel').attr('title')==$('#codigo_imovel').val()) {
					$('#codigo_imovel').val('');
				}
				if ($('#telefone').attr('title')==$('#telefone').val()) {
					$('#telefone').val('');
				}
				$('#msg_erro').children().remove();
				var data = $('#form_contato input[type=text],#form_contato input[type=hidden],#form_contato textarea').serialize();
				$.ajax({
						'data':data,
						url:baseUrl()+'ajax/enviarContato/',
						type:'post',
						'dataType':'json',
						success:function(resp) {
							if (resp.status=='ok') {
								alert('Seu contato foi enviado para a imobiliária.');
								$('#form_contato input[type=text],#form_contato textarea').val('');
							}
							else {
								alert('Ocorreu um problema no envio do contato.');
							}
						},
						beforeSend:function() {
							$(bt).attr({'value':'Aguarde','disabled':'true'});
						},
						complete:function() {
							$(bt).attr({'value':'Enviar','disabled':''});
						},
						error:function(jqXHR, textStatus, errorThrown) {
						    if (jqXHR.responseText == '{status:"ok"}') {
						        alert('Seu contato foi enviado para a imobiliária.');
								$('#form_contato input[type=text],#form_contato textarea').val('');
						    }else{
							    alert('Ocorreu algum erro na requisição.Por favor entre em contato com o administrador sobre o erro:'+errorThrown+', Mensagem:'+textStatus);
							}
						}
				});
		}
		return false;
	});
	$('#form_contato input[type=text],#form_contato textarea').change(function(){
		var id = 'campo_'+$(this).attr('name');
		if ($(this).val()!='')
		{
			$(this).css('border','1px solid #F9CDB2');
			$('#'+id).remove();
		}
		else
		{
			if (!document.getElementById(id))
			{
				var p = document.createElement('p');
				$(p).attr('id',id).html('Preencha o campo '+$(this).attr('name'));
				$('#msg_erro').append(p);
			}
			$(this).css('border','1px solid red');
		}
	});
	$('#ddd').keyup(function(){
		if (this.value.length==2)
			$('#telefone').focus();
	});
	$('#video_detalhes').hide();
	$('#videos').click(function(){
		$('#foto_detalhes').fadeOut(300,function(){
			$('#video_detalhes').fadeIn();
		});
	});
	$('#fotos, .fotos').click(function() {
		$('#elementos_aba li a').removeClass();
		$('#elementos_aba li a').slice(1,2).addClass('destaque');
		$('#aba_detalhes,#aba_contato').hide();
		$('#aba_fotos').fadeIn(200);
		$('#video_detalhes').fadeOut(300,function(){
			$('#foto_detalhes').fadeIn();
		});
	});
	$('.imprimir').click(function(){
		var parametros = window.location.href.split('/');
		var ate = parametros.length;
		for(i=3;i<=ate;i++)
		{
			if (parseInt(parametros[i])>0)
			{
				var id = parametros[i];
				break;
			}
		}
		var janela = window.open('../imprimir/'+id,'Impressão','width=640,height=480,scrollbars=true,resizable=false');
		if (janela==null)
		{
			alert('Verifique o bloqueador de pop-up do seu browser e tente novamente.');
		}
	});
	
	$('#fechaLightbox').live('click',function(){ 
	    $('#bglight').fadeOut().remove(); 
	    $('#div_internalight').fadeOut().remove(); 
	});
	
});

