function abrir(strMensagem)
{
    $(document).ready(function(){
        jQuery.facebox(strMensagem);
	
	
    }) 
    
}

/**
 * This is the callback function which receives notification
 * when an item becomes the first one in the visible range.
 */
function mycarousel_itemFirstInCallback(carousel, item, idx, state) {
    //display('Item #' + idx + ' is now the first item');
	$(item).addClass('first');
};


/**
 * This is the callback function which receives notification
 * when an item becomes the first one in the visible range.
 */
function mycarousel_itemLastInCallback(carousel, item, idx, state) {
    $(item).addClass('last');
};

jQuery(document).ready(function(){	
	
	$('.Colorbox').colorbox();
	
	
	
	    
	
	
	
	//abrir("teste");
	$(".box_error").hide();
	var options2 = {
            caption:    false,
            navigation: 'permanent',
            direction:  'right'
        }
    var options3 = {
            caption:    false,
            navigation: 'permanent',
            direction:  'left'
        }
    

    jQuery('.ppy').popeye(options2);
	
	jQuery('.ppy2').popeye(options3);

	
	$('#gallery a').lightBox();

			
	/*jQuery('.lupa_zoon').fancybox();*/
			
	jQuery('.lupa_zoon').facebox();
	
	jQuery('.pedido ul:last-child li').css('border-bottom', '0');

			

	

	define_layout();
	page();
	Checkbox();
	hover_mapas();
	desloga();
	watermark.init();
	checkbox_estilo();
	abrePedidos();
	validaNewslatter();
	select_fake('.select_padrao');
	pessoaFisicaJuritica();
	validate();
	destaque_produtos();
	hover_produtos();
	vizualizar_detalhe();
	trocafoto();
	abreportas();
    $('input:text').setMask();

	jQuery(".validate").validate();
	
	jQuery('.produtos_pedido ul li:last-child').css('margin-right',0);
	
	jQuery('.mycarousel').jcarousel({
		 itemFirstInCallback:{
		 onAfterAnimation: mycarousel_itemFirstInCallback
		},
		itemLastInCallback: {
		 onAfterAnimation: mycarousel_itemLastInCallback
		},

        vertical: false,
		horizontal: true,
        scroll: 5
    });


	$(".ajaxExcluir").click(function(){
		
		ajaxExcluir($(this).attr('lang'));
		alert($(this).parents("ul").html());
		$(this).parent("ul").fadeOut("slow");
	});


	$('.hide-input-text').bind({
		click: function(){
			if($(this).val() == $(this).attr('lang'))
				$(this).val('');
		},
		blur: function(){
			if($(this).val() == '')
				$(this).val($(this).attr('lang'));
		}
	});
	
	//valor
	var size = $(".indicar_prod").offset().top - 100;
	//alert(size); 
	jQuery('ul#animacao').height(size+"px")
	jQuery('ul#animacao').cycle({  
            fx: 'scrollRight',
			speed: 1000,
			next: '#muda_produtos',
			timeout: 0
    });
	
	
});


function abreportas(){
	/*jQuery('#muda_produtos').click(function(){
		jQuery('#load_produtos').load(jQuery('.aba_ver_todas_portas').attr('href'), function(){
		    jQuery('.jcarousel-next').removeClass('jcarousel-next-disabled').removeClass('jcarousel-next-disabled-horizontal');
		    jQuery('.jcarousel-next').attr('disabled', 'false');
		    jQuery('.jcarousel-item-1').addClass('first');
		    
		});
		jQuery(this).hide('slow');
			
		
		
		
	})*/
}


function vizualizar_detalhe(){
	jQuery('.vizualizar_detalhe').click(function(){
		jQuery('.pedido').hide();
		jQuery(jQuery(this).attr("href")).show('slow');
		return false;
	})
}

function page(){
	jQuery('.indicar_prod').click(function(){
		
		jQuery('#page').toggle();
		return false;
	});
	jQuery('.close').click(function(){
		jQuery('#page').hide('slow');
		return false;
	});
}

function Checkbox(){

    jQuery('.checkbox_revestimento').each(function(){

        jQuery(this).css({
            display: 'none'
        });
		
		var imagem = jQuery(this).metadata().url;
		var id = jQuery(this).metadata().id;
		var nome = jQuery(this).metadata().nome;

        jQuery(this).before(
							'<li class="checkbox">\
                                  <img src="'+imagem+'" width="95px" height="25px" alt="revestimento mirrage" />\
                                  <span>'+ nome +'</span>\
                            </li>'
							)
		
			
       jQuery(this).prev('.checkbox').click(function(){
		    $("#revestimento").val(id);
			$(".revestimento").find(".checkbox").removeClass("active");
		   jQuery(this).addClass('active');
        })
    });
	
	jQuery('.checkbox_tamanho').each(function(){

        jQuery(this).css({
            display: 'none'
        });
		
		var text = jQuery(this).metadata().text;
		var id = jQuery(this).metadata().id;
		
        jQuery(this).before('<li class="checkbox">\
                                 '+text+'\
                            </li>')
		
		jQuery(this).prev('.checkbox').click(function(){
			$("#tamanho").val(id);
			$(this).parent("ul").find(".checkbox").removeClass("active");
		    jQuery(this).addClass('active');
        })

    });

	jQuery('.checkbox_espessura').each(function(){

        jQuery(this).css({
            display: 'none'
        });

		var text = jQuery(this).metadata().text;
		var id = jQuery(this).metadata().id;

        jQuery(this).before('<li class="checkbox">\
                                 '+text+'\
                            </li>')

		jQuery(this).prev('.checkbox').click(function(){
			$("#espessura").val(id);
			jQuery(this).parent(".opcoes").find(".checkbox").removeClass("active");
		   jQuery(this).addClass('active');
        })

    });
	
}


function define_layout(){
	var size = jQuery("body").width();
	jQuery(".layout").css({width: size+'px'});
}

function desloga(){
	jQuery('.logado a').click(function(){
		jQuery('.logado').hide();
		jQuery('.deslogado').fadeIn('slow');
		//return false;
	})
}

function checkbox_estilo(){
	jQuery('.checkbox_stilo').each(function(){
		jQuery(this).css({display: 'none'});
		jQuery(this).before('<span class="checkbox_stilo"></span>');

		jQuery(this).prev('.checkbox_stilo').click(function(){
			if(jQuery(this).hasClass('active_checkbox')){
				jQuery(this).next('.checkbox_stilo').click();
				jQuery(this).removeClass('active_checkbox');
			}else{
				jQuery(this).next('.checkbox_stilo').click();
				jQuery(this).addClass('active_checkbox');
			}

		});
	});
}

function abrePedidos(){
	jQuery('.meus_pedidos').click(
		function(){
			if(jQuery(this).hasClass('ativo')){
				jQuery(this).removeClass('ativo');
				jQuery('.lista_pedidos').hide();
//				return false;
			}else{	
				jQuery(this).addClass('ativo');
				jQuery('.lista_pedidos').toggle('slow');
				return false;
			}
		});
}

//select Fake
function select_fake(start){
		jQuery('.select_padrao').each(function(){
				var el  = jQuery(this).find('option:first-child').html();
				var color = jQuery('.'+jQuery(this).attr('class')).css('color');
				var w = jQuery(this).width() - 15;
				jQuery(this).addClass('select-hide');
				jQuery(this).before('<div class="borda-left"></div><div class="select-fake" style="width:'+w+'px;color:'+color+'">'+el+'</div><div class="clear"></div>');
	
			jQuery(this).change(function(){
									
						var str = jQuery(this).children('option:selected').text();

						jQuery(this).parent('li').find('.select-fake').html(str);
				});
			
				var str = $(this).children('option:selected').text();
				$(this).parent('li').find('.select-fake').html(str);
		});
	}


function pessoaFisicaJuritica(){
	
	jQuery(".pessoa_fisica:first").show();
	jQuery('#pessoa:first').attr('checked', true);
	
	
	jQuery('.fisica').click(function(){
		jQuery('.pessoa_juridica').hide();
		jQuery('.pessoa_fisica').show();
		
		jQuery('#pessoa').attr('checked', true);
		jQuery('#juridica').attr('checked', false);
	});
	jQuery('.juridica').click(function(){
		jQuery('.pessoa_fisica').hide();
		jQuery('.pessoa_juridica').show();
		
		jQuery('#juridica').attr('checked', true);
		jQuery('#pessoa').attr('checked', false);
		
	});
}

function validate(){
	
	jQuery("#contato").validate({
		rules: {
			nome: "required",
			email: {
				required: true,
				email: true
			},
			ddd:{
				required: true,
				number: true,
				maxlength: 2
			},
			telefone:{
				required: true,
				maxlength: 9
			},
			mensagem: "required",
			estado: "required"			
		}
	});
	
	jQuery("#pessoa_fisica").validate({
		rules: {
			nome: "required",
			email: {
				required: true,
				email: true
			},
			ddd:{
				required: true,
				number: true,
				maxlength: 2
			},
			ddd_celular:{
				required: false,
				number: true,
				maxlength: 2
			},
			telefone:{
				required: true,
				number: true,
				maxlength: 8
			},
			celular:{
				required: false,
				number: true,
				maxlength: 8
			},
			mensagem: "required",
			rua: "required",
			senha: {
				required: true
			},
			confim_senha: {
				required: true,
				equalTo: "#password"
			},
			site_houser: "required"
		}

		
	});
	
	jQuery("#pessoa_juridica").validate({
		rules: {
			nome: "required",
			email: {
				required: true,
				email: true
			},
			empresa: "required",
			ddd:{
				required: true,
				number: true,
				maxlength: 2
			},
			ddd_celular:{
				required: false,
				number: true,
				maxlength: 2
			},
			telefone:{
				required: true,
				number: true,
				maxlength: 8
			},
			cnpj:{
				required:true
			},
			celular:{
				required: false,
				number: true,
				maxlength: 8
			},
			rua: "required",
			senha: {
				required: true
			},
			confim_senha: {
				required: true,
				equalTo: "#password"
			},
			site_houser: "required"
		}
	});
	jQuery("#form-coments").validate({
		rules: {
			nome: "required",
			email: {
				required: true,
				email: true
			},
			
			mensagem: "required"
		}
	});
	
	
	
	jQuery("#login").validate({
		rules: {
			email: {
				required: true,
				email: true
			},
			password: {
				required: true
			}
		}
	});
	
	
	jQuery("#relembrar_senha").validate({
		rules: {
			email: {
				required: true,
				email: true
			}
		}
	});
	
	
};

function validaNewslatter(){
	$("#frm_newslatter").click(function(){	
		var status_valida=0;							  
		if($('#nome').val() == 'nome'){
			$('#nome').addClass('erro');
			status_valida=1;
		}
		else{
			$('#nome').removeClass('erro');
		}
		if($('#email').val() == 'email'){
			$('#email').addClass('erro');
			status_valida=1;
		}
		else{
			$('#email').removeClass('erro');
		}
		
		if(status_valida==1){
			$('.box_error').show();
			return false;
		}
		else{
			$('.box_error').hide();
		}
	});
}

function hover_produtos(){
	jQuery('.lista_produtos ul li a').hover(
		function(){
			jQuery(this).offset().left;

			var obj = jQuery(this);
			jQuery(obj.prev('li').addClass('opacity'));
			jQuery(this).addClass('opacity');
			jQuery(obj.attr("lang")).fadeIn('medium');

			/*
			 *.lista_produtos ul li a img{
				opacity:0.35;
				-moz-opacity: 0.35;
				filter: alpha(opacity=35);}*/
			$('.lista_produtos ul li a[lang!='+jQuery(this).attr("lang")+'] img').css("opacity", "0.35");


			jQuery('.hover_produto').not(jQuery(this).attr("lang")).hide('slow');

			jQuery(jQuery(this).attr("lang")).mouseout(function(){
				jQuery('.hover_produto').fadeOut('fast');
				jQuery(obj).removeClass('opacity');
				$('.lista_produtos ul li a[lang!='+jQuery(this).attr("lang")+'] img').css("opacity", "1");
			})
		})








		/*function(e){
			var x = e.pageX;
			var obj = jQuery(this);



			jQuery('.lista_produtos ul li').hasClass('first').(function(){
				x = e.pageX;

			});*/


			/*jQuery('.lista_produtos ul li').hover(function(){
				if(jQuery(this).hasClass('first')){
					x -= 120;
				}
				else if(jQuery(this).hasClass('last')){
					x -= 460;
				}
				else{
					x = e.pageX - 330;
				}
			});





			jQuery('.hover_produto').not(jQuery(this).attr("href")).hide('slow');

			jQuery('.lista_produtos ul li').animate({opacity:0.1},200,"",function(){
														jQuery(obj.attr("href")).css({left: x + 'px'});
														jQuery(obj.attr("href")).show('slow');

													})

			jQuery(jQuery(this).attr("href")).unbind();
			jQuery(jQuery(this).attr("href")).mouseout(function(){
				jQuery(this).hide('slow',function(){
					jQuery('.lista_produtos ul li').animate({
														opacity:1
														},200,"",function(){

									     			   })
				});

			})
		}

	)*/


}


function destaque_produtos(){
	jQuery('.foto_detalhe a').hover(		
		function(){
			jQuery(jQuery(this).attr("href")).fadeIn('slow');
		},
		function(){
			jQuery(jQuery(this).attr("href")).fadeOut('slow');
		}
	);
	
	jQuery('.desativar_detalhes').click(function(){
		jQuery('.box_destaque').hide('slow');
		jQuery(this).hide();
		jQuery('.ativar_detalhes').show();
		return false;
	});
	
	jQuery('.ativar_detalhes').click(function(){
		jQuery('.box_destaque').show('slow');
		jQuery(this).hide();
		jQuery('.desativar_detalhes').show();
		return false;
	});
}


function hover_mapas(){
	jQuery('.img_mapa ul li a').hover(
		
		
		function(e){
			//var aux = jQuery(this).offset().left;
			var x = jQuery(this).css("left");
			var y = jQuery(this).css("bottom");
			//console.info(x +" - "+y);
			jQuery('.hover').not(jQuery(this).next('.hover')).hide('slow');
			jQuery(this).next('.hover').show('slow');
			jQuery(this).next('.hover').css({
											left: x, 
											bottom: y
											});
			//jQuery(this).unbind();
			
		}
	);
	
	jQuery('.hover').click(
	
		function(){
			jQuery('.box_endrecos').not(jQuery(this).attr("lang")).hide('slow');
			jQuery(jQuery(this).attr("lang")).toggle('slow');
		}
	);
}

function get_cidades_from_estado(idEstado, idSelectCidade)
{   
    $("#" + idSelectCidade).text('Carregando...');
    
    $("#" + idSelectCidade).load("cadastro/ajax_get_cidades_from_estado/" + idEstado, '', function() {
        if (idEstado) {
            $('#' + idSelectCidade).parent('li').find('.select-fake').text("Selecione uma Cidade");
        } else {
            $('#' + idSelectCidade).parent('li').find('.select-fake').text("Selecione um Estado");
        }
    });
	
}


function ajaxQuantidade(text) {
	base_url  = $('base').attr('href')+"pedidos/ajax_quantidade/" + $(text).attr("lang") + "/" + $(text).val();

	$.ajax({
		type: "POST",
		url: base_url,
		data: "",
		success: function() {

		},
		error: function(res){
			//alert(res.responseText);
		}
	});
}


function ajaxOptions(option, combo) {
    base_url  = $('base').attr('href')+"pedidos/ajax_options/" + option + "/" + $(combo).attr("lang") + "/" +  $(combo).val();

	$.ajax({
		type: "POST",
		url: base_url,
		data: "",
		success: function() {

		},
		error: function(res){
			//alert(res.responseText);
		}
	});
}



function ajaxExcluir(el, rowid) {
	base_url  = $('base').attr('href')+"pedidos/ajax_excluir/" + rowid;

	$.ajax({
		type: "POST",
		url: base_url,
		data: "",
		success: function(res) {
			$(el).parents("ul").fadeOut("slow");
			if(res == "1") {// carrinho vazio
				$("#frmCarrinho").hide();
				$("#frmCarrinho").html("<ul><li><b>Nenhum produto em seu pré-pedido</b></li></ul>");
				$("#frmCarrinho").fadeIn("slow");
				$(".bt_confirmar_pedido").remove();

				$("#numeroItensCarrinho").html(Number($("#numeroItensCarrinho").html()) - 1);
			}
		},
		error: function(res){
			//alert(res.responseText);
		}
	});

    
}

function confirmar_pedido(){
	var error = false;
	$(".variacoesValidade").each(function(){
		if($(this).val() == 0){
			error = true;
		}
	});


	if(!error){
		base_url  = $('base').attr('href')+"pedidos/ajax_confirmar_pedido";

		$.ajax({
			type: "POST",
			url: base_url,
			data: "",
			success: function(res) {
				if(res == "login"){
					location.href=$('base').attr('href')+"login";
					return false;
				}else if(res == "erro"){
					abrir("Não foi possível confirmar o seu pedido. Por favor, tente novamente.");
					return false;
				}else{
					$("#frmCarrinho").hide();
					$("#frmCarrinho").html("<ul><li><b>Nenhum produto em seu pré-pedido</b></li></ul>");
					$("#frmCarrinho").fadeIn("slow");
					$(".bt_confirmar_pedido").remove();

					$(".pedido_enviado").show();
				}
			},
			error: function(res){
				//alert(res.responseText);
			}
		});
	}else
		abrir("Por favor, selecione uma variação para o seu produto.");
}

function trocafoto(){
	jQuery('.troca_foto .checkbox').click(function(){
		
		var obj = jQuery(this).next('input').attr('lang');

		if(obj != "")
			jQuery('.foto_detalhe img').attr('src',$('base').attr('href')+"uploads/produtos_fotos/"+obj);
		
		
	})
}


function valida_form_indicacao() {
	
	var msg = "";
	var erro = false;

    if($("#nome").val() == "Nome")
		erro = true;

	if($("#email").val() == "E-mail")
		erro = true;

	if($("#nome_amigo").val() == "Nome do Amigo")
		erro = true;

	if($("#email_amigo").val() == "E-mail do Amigo")
		erro = true;


	if(erro){
		abrir("Por favor, informe todos os dados do formulário.");
		return false;
	}

}
