// JavaScript Document

/*
function On1 () { $(".mp1").fadeTo("fast", 1.0); setTimeout("Off1()",5000) }
function On2 () { $(".mp2").fadeTo("fast", 1.0); setTimeout("Off2()",5000)}
function On3 () { $(".mp3").fadeTo("fast", 1.0); setTimeout("Off3()",5000)}
function On4 () { $(".mp4").fadeTo("fast", 1.0); setTimeout("Off4()",5000)}

function Off1 () { $(".mp1").fadeTo("normal", 0.5, On2()); }
function Off2 () { $(".mp2").fadeTo("normal", 0.5, On3()); }
function Off3 () { $(".mp3").fadeTo("normal", 0.5, On4()); }
function Off4 () { $(".mp4").fadeTo("normal", 0.5, On1()); }

function mainb () {
	On1(); 
	//setTimeout("putOff('.mp1')",10000);
	//setTimeout("mainb()",3000);
}
*/

/*function mainb () {
	$(".mp1").fadeTo("fast", 0.8, 
		setTimeout(function() { 
			$(".mp1").fadeTo("normal", 0.5, function() {
			$('.mp2').fadeTo("normal",0.8,function() {
			$(".mp2").fadeTo("normal", 0.5, function() {
			$('.mp3').fadeTo("normal",0.8,function() {
			$(".mp3").fadeTo("normal", 0.5, function() {
			$('.mp4').fadeTo("normal",0.8,function() {
			$(".mp4").fadeTo("normal", 0.5); 
			}); }); }); }); }); 
	});
	}),10000);
	//setTimeout("mainb()",3000);
}*/

$(document).ready(function() {
			
	$('a[rel*=facebox]').facebox() ;
	//$(document).pngFix(); 	
	jQuery('ul.sf-menu').superfish();			   
	$('#lojafamilias li').each(function() {
		$(this).click(function() {
			$(this).find('ul').slideToggle(300);
		});
	});
	imagePreview();
	$(".tabs_btn").click(function() {
		$('.tabs_btn').removeClass("tab_selected");
		$(this).addClass("tab_selected");
		$(".loja_tabs").hide();
		abre = $(this).attr("href");
		$(abre).show();
		return false;
	});
	
	// alterações aos css importados 
	$(".mainclass").attr({"style" : ""});
	
	/*********************************/
	$('#jqnews').cycle({timeout: 10000, speed: 1000});
	$('.jqnews').cycle({timeout: 10000, speed: 1000});
	$('#prodbanner').cycle({timeout: 10000, speed: 1000});
	
	/*    VALIDAÇÔES */ 
	$(".mainpNewsletterform").validate({
	    rules: { 
			newsletter_email: {required: true, email: true }
			},
		errorLabelContainer: $("#newsletter_erro")
	});
		
	$("#formRecomendar").validate({
	    rules: {
			seuemail: {
				required: true,
				email: true
			},
			destemail: {
				required: true,
				email: true
			}
		},
		messages: {
			seuemail: "Insira emails válidos",
			destemail: "Insira emails válidos"
		}
	});
	$("#formRegCliente").validate({
	    rules: {
			nome: "required",
			morada: "required",
			localidade: "required",
			cpostal: "required",
			username: "required",
			password: "required",
			email: {
				required: true,
				email: true
			},
			confpassword: {
 			    equalTo: "#password"
            }
		},
		messages: {
			nome: "Preencha o seu nome",
			morada: "Preencha uma morada",
			localidade: "Preencha a su localidade",
			cpostal:"Preencha o seu código postal",
			username: "Indique o username pretendido",
			password: "Indique a password pretendida",
			email:"Insira um email válido",
			confpassword:"As passwords tem que ser iguais"
		}
	});
	$("#formAltCliente").validate({
	    rules: {
			nome: "required",
			morada: "required",
			localidade: "required",
			cpostal: "required",
			username: "required",
			email: {
				required: true,
				email: true
			},
			confpassword: {
 			    equalTo: "#password"
            }

		},
		messages: {
			nome: "Preencha o seu nome",
			morada: "Preencha uma morada",
			localidade: "Preencha a su localidade",
			cpostal:"Preencha o seu código postal",
			username: "Indique o username pretendido",
			email:"Insira um email válido",
			confpassword:"As passwords tem que ser iguais"
		}
	});
	$("#formRecPassword").validate({
	    rules: {
			recemail: {
				required: true,
				email: true
			}
		},
		messages: {
			recemail:"Insira um email válido"
		}
	});
	$("#contactForm").validate({
	    rules: {
			contact_nome: "required",
			contact_msg: "required",
			contact_email: {
				required: true,
				email: true
			}
		},
		messages: {
			contact_nome: "Insira o seu nome",
			contact_email: "Insira um endereço de email válido",
			contact_msg: "Insira uma mensagem"
		}
	});
	$("#clientLogin_form").validate({
	    rules: {
			uname: "required",
			pword: "required"
		},
		messages: {
			uname: "Insira o seu nome de utilizador",
			pword: "Insira a sua palavra passe"
		}
	});
	$("#formRecomendar").validate({
	    rules: {
			seunome: "required",
			seuemail: "required",
			destnome:"required",
			destemail:"required"
		},
		messages: {
			seunome: "Insira o seu nome",
			seuemail: "Insira o seu email",
			destnome:"Insira o nome do seu amigo",
			destemail:"Insira o email do seu amigo"
		}
	});
	
	/**********************************/
	
	//$(".mp_banner").fadeTo("slow", 0.5);
	$(".mp_banner").hover(function(){
	$(this).fadeTo("fast", 0.5);
		},function(){
	$(this).fadeTo("normal", 1.0);
	});
	/********* procurar field */
	$('.procurarfield').bind("focus",function() { 
		if($(this).val() == "procurar") {
			$(this).val("");
		}
	}).bind("blur",function() {
		if($(this).val() == "") {
			$(this).val("procurar");
		}	
	});
	$('.procurarbtn').click(function(){
		$('.procurarForm').submit();
	});
	/********* procurar field */
	//mainb();
	
	
	var abertos = new Array ();
	function closeOpened(nivel) {
		for (i=nivel;i<=9;i++) {
				$("."+i).remove();
		}
	}
	
	function putButton (nivel) {
		$(".buttonVerresultados").remove();
		valorappend = "<div class='buttonVerresultados'><a class='sim_submit'>Ver resultados parciais</a></div>";
		$("."+(nivel-1)).append(valorappend);
		simSubmit();
	}
	function clearButton (nivel) {
		for (i=1;i<nivel;i++) {
			$("#btn"+i).remove();
		}	
	}
	function finalButtonActive () {
		$(".buttonVerresultados").hide();
		$(".selectButtonsInactive").hide();
		$(".selectButtons").show();
		simSubmit();
	}
	function finalButtonInactive () {
		$(".buttonVerresultados").show();
		$(".selectButtonsInactive").show();
		$(".selectButtons").hide();
	}
	
	function popular (e) {
		$("#"+e).click(function() { 
						//alert("sdf");
					//$("#selectForm div:gt("+($(this).index()+1)+")").remove(); alert
					$("#famcode").val($(this).val());
					$.get("modulos/class_lojaselect.php?p="+$(this).val(),{ },
						function(data){ 
							//alert(data);
							if( data.erro != "endoffile" ) {
								//alert(data.nivel);
								//$("#selectForm div:gt("+data.nivel+")").remove();
								//$("#selectForm").find("div :gt("+$(this).val()+")").remove();
								closeOpened(data.nivel); //alert(data.nivel);
								valorappend = "<div class='" + data.nivel  + "'>";
								valorappend += "<div class='loja_pergunta'>" + data.codpergunta.length+"º - "+ data.pergunta + "</div>";
								valorappend += "<div class='loja_respostas' id='sel" + data.codpergunta + "'>";
								valorappend += data.respostas;
								valorappend += "</div> <div style='clear:left; height:10px;'></div>";
								valorappend += "</div>";
								//alert(valorappend);
								$("#selectForm").append(valorappend);
								finalButtonInactive();
								putButton(data.nivel);
								popular("sel"+data.codpergunta+" :radio");	
								
							}else{
								var alvo = $("#"+e).parent().parent().parent().attr("class");
								alvo++; //alert(alvo);
								closeOpened(alvo); 		
								finalButtonActive();
							}
						},"json");
				
				
					//$("#selectForm").find("div:gt("+$(this).parent().attr("id")+")").remove();
			
			});
	}
	popular("mselect :input");
	
	function carregaSimulacao(id, tipo, tipousado){
	  	$.post("modulos/funcs/func_listaresultados.php",{ idartigo : id, tipo_res : tipo, tipousado : tipousado } , 
	  		function(data){
				$("#select_lista_resultados").hide();
				$("#select_op_pagamento").html(data).show();
				$('#submit_proposta input,select,radio').change(function() { 
					if($("#submit_proposta").valid()) {
						$("#dadosSubmit").parent().attr({"class" : "selectButtons"});
						$("#formErrors").hide();
					}else{
						$("#dadosSubmit").parent().attr({"class" : "selectButtonsInactive"});
					}
				});
				$("#submit_proposta").validate({
					showErrors: function(errors, errorList) {
					  },
					rules: {
						nome: { required:true},
						empresa: { required:true},
						telefone: { required:true, number:true, maxLength:9, minLength: 9},
						email: { required:true, email:true }
					},
					messages: {
						nome: "Insira o seu nome",
						empresa: "Insira o nome da empresa",
						telefone: "Insira o seu número de contacto",
						email: "Insira um endereço de email válido"
					}
				 });
				 $("#dadosSubmit").click(function(){
				 		if(!$("#submit_proposta").valid()) {
							$("#formErrors").show().html("Preencha correctamente o formulário");
						}else{
							$("#formErrors").hide();
							$("#submit_proposta").append("<input type='hidden' name='vendedor' value='"+$("#vendedor_id").val()+"'/>");
							$("#submit_proposta").ajaxSubmit({
								url: "modulos/funcs/func_op_pagamento.php",
								beforeSubmit: function() { 
									$("#select_op_pagamento").hide();
									$("#ajax-load").show();
								},
								success: function(data){
									$("#ajax-load").hide();
									$("#select_simulacao").html(data).show();
									$("#select_op_pagamento").hide();
//encomenda
									$("#op2_encomenda").click(function(){
										$.post("modulos/funcs/func_op_pagamento.php",
										   { 
										   		idArtigo : $("#idArtigo").attr("value"), 
												tipoenc: $("#tipoSimulacao").attr("value"), 
												optipo : 2,
												idVendedor : $("#vendedor_id").attr("value"),
												idCliente : $("#idCliente").attr("value"),
												pdfCatalogo : $("#pdfCatalogo").attr("value")
										   },
										   function(data) {
											   	$("#select_simulacao").hide();
												$("#select_finalsimulacao").html(data).show();
												$('#submit_encomenda input,select,radio').change(function() { 
													if($("#submit_encomenda").valid()) {
														$("#encomendaSubmit").parent().attr({"class":"selectButtons"});
														$("#formErrors2").hide();
													}else{
														$("#encomendaSubmit").parent().attr({"class":"selectButtonsInactive"});
													}
												});
												$("#submit_encomenda").validate({
													showErrors: function(errors, errorList) { },
													rules: {
														nome: { required:true},
														empresa: { required:true},
														telefone: { required:true, number:true, maxLength:9, minLength: 9},
														email: { required:true, email:true },
														nif: { required:true, number:true, maxLength:9, minLength: 9}
													},
													messages: {
														nome: "Insira o seu nome",
														empresa: "Insira o nome da empresa",
														telefone: "Insira o seu número de contacto",
														email: "Insira um endereço de email válido",
														nif: "Insira o seu numero de contribuinte"
													}
												 });
												$("#encomendaSubmit").click(function(){ 
													if(!$("#submit_encomenda").valid()) {
														$("#formErrors2").html("Preencha correctamente o formulário").show();
													}else{
														$("#submit_encomenda").ajaxSubmit({
															url: "modulos/funcs/func_op_pagamento.php",
															success: function(data){
																$("#select_finalsimulacao").hide();
																$("#select_concluido").html(data).show();
															}
														});
													}
												});
										   });
									});
//consulta comercial
									$("#op2_consulta").click(function(){
										$.post("modulos/funcs/func_op_pagamento.php",
											{ idArtigo : $("#idArtigo").attr("value"), 
											  tipoenc:   $("#tipoSimulacao").attr("value"), 
											  tipousado: $("#tipousado").attr("value"),
											  meses:     $("#meses").attr("value"),
											  nome:      $("#cl_nome").attr("value"),
											  email:     $("#cl_email").attr("value"),
											  empresa:   $("#cl_empresa").attr("value"),
											  telefone:  $("#cl_telefone").attr("value"),
											  vendedor:  $("#vendedor_id").val(),
											  idCliente : $("#idCliente").attr("value"),
											  pdfCatalogo : $("#pdfCatalogo").attr("value"),
											  optipo :   3},
										   function(data) {
											   	$("#select_simulacao").hide();
												$("#select_finalsimulacao").html(data).show();
										   });
									});
									$("#op2_demonstracao").click(function(){
										$.post("modulos/funcs/func_op_pagamento.php",
											{ idArtigo : $("#idArtigo").attr("value"), 
											  tipoenc:   $("#tipoSimulacao").attr("value"), 
											  tipousado: $("#tipousado").attr("value"),
											  meses:     $("#meses").attr("value"),
											  nome:      $("#cl_nome").attr("value"),
											  email:     $("#cl_email").attr("value"),
											  empresa:   $("#cl_empresa").attr("value"),
											  telefone:  $("#cl_telefone").attr("value"),
											  vendedor:  $("#vendedor_id").val(),
											  idCliente : $("#idCliente").attr("value"),
											  pdfCatalogo : $("#pdfCatalogo").attr("value"),
											  optipo :   7},
										   function(data) {
											   	$("#select_simulacao").hide();
												$("#select_finalsimulacao").html(data).show();
												$('#submit_demonstracao input,select,radio').change(function() { 
													if($("#submit_demonstracao").valid()) {
														$("#demonstracaoSubmit").parent().attr({"class":"selectButtons"});
														$("#formErrors2").hide();
													}else{
														$("#demonstracaoSubmit").parent().attr({"class":"selectButtonsInactive"});
													}
												});
												$("#datahora").mask("99/99/99 99:99",{placeholder:" "});
												$("#cpostal").mask("9999-999",{placeholder:" "});

												$("#submit_demonstracao").validate({
													showErrors: function(errors, errorList) { },
													rules: {
														nome: { required:true},
														morada: { required:true},
														localidade: { required:true},
														cpostal: { required:true},
														empresa: { required:true},
														telefone: { required:true, number:true, maxLength:9, minLength: 9},
														email: { required:true, email:true },
														nif: { required:true, number:true, maxLength:9, minLength: 9},
														datahora: { required:true},
														resp_nome: { required:true},
														resp_tlm: {required:true}
													},
													messages: {
														nome: "Insira o seu nome",
														empresa: "Insira o nome da empresa",
														telefone: "Insira o seu número de contacto",
														email: "Insira um endereço de email válido",
														nif: "Insira o seu numero de contribuinte"
													}
												 });
												$("#demonstracaoSubmit").click(function(){ 
													if(!$("#submit_demonstracao").valid()) {
														$("#formErrors2").html("Preencha correctamente o formulário").show();
													}else{
														$("#submit_demonstracao").ajaxSubmit({
															url: "modulos/funcs/func_op_pagamento.php",
															success: function(data){
																$("#select_finalsimulacao").hide();
																$("#select_concluido").html(data).show();
															}
														});
													}
												});
										   });
									});
//plano b (retorna os resultados para usados
									$("#op2_planob").click(function(){
										
										$.post("modulos/funcs/func_listaresultados.php",{ resp_code : $("#famcode").val(), equip_tipo : 1, tipo_res : 0 } , 
										function(data){
											$("#select_lista_resultados").html(data).show();
											$("#select_op_pagamento").hide();
											$("#select_simulacao").hide();
											
											$(".prodselect_submit").contextMenu({ menu: 'rmenu2', leftButton: true }, 
											function(action, el, pos ) { contextMenuWork2(action, el, pos, $(this).attr("alc")); });
											
											$(".prodselect_submit_alc").contextMenu({ menu: 'rmenu2_alc', leftButton: true }, 
											function(action, el, pos ) { contextMenuWork2_alc(action, el, pos, $(this).attr("alc")); });
											
											$(".sel_proposta_aquisicao").click(function() {  
												carregaSimulacao($(this).attr('val'), 1)
											});
											$(".sel_proposta_renting").click(function() {
												carregaSimulacao($(this).attr('val'), 2)
											});
											$(".sel_proposta_acd").click(function() {
												carregaSimulacao($(this).attr('val'), 3)
											});
										});
									});
// recomendar a um amigo 
									$("#op2_recomendar").click(function(){
										$.post("modulos/funcs/func_op_pagamento.php",
										   { idArtigo : $("#idArtigo").attr("value"), 
											  tipoenc:   $("#tipoSimulacao").attr("value"), 
											  tipousado: $("#tipousado").attr("value"),
											  meses:     $("#meses").attr("value"),
											  nome:      $("#cl_nome").attr("value"),
											  email:     $("#cl_email").attr("value"),
											  empresa:   $("#cl_empresa").attr("value"),
											  telefone:  $("#cl_telefone").attr("value"),
											  vendedor:  $("#vendedor_id").val(),
											  optipo :   4},
										   function(data) {
											   	$("#select_simulacao").hide();
												$("#select_finalsimulacao").html(data).show();
												$('#submit_recomenda input,select,radio').change(function() { 
													if($("#submit_recomenda").valid()) {
														$("#recomendaSubmit").parent().attr({"class":"selectButtons"});
														$("#formErrors3").hide();
													}else{
														$("#recomendaSubmit").parent().attr({"class":"selectButtonsInactive"});
													}
												});
												$("#submit_recomenda").validate({
													showErrors: function(errors, errorList) { },
													rules: {
														nome_r: { required:true},
														email_r: { required:true, email:true },
														nome_d: { required:true},
														email_d: { required:true, email:true }
													}
												});
												$("#recomendaSubmit").click(function(){ 
													if(!$("#submit_recomenda").valid()) {
														$("#formErrors3").html("Preencha correctamente o formulário").show();
													}else{
														$("#submit_recomenda").ajaxSubmit({
															url: "modulos/funcs/func_op_pagamento.php",
															success: function(data){
																$("#select_finalsimulacao").hide();
																$("#select_concluido").html(data).show();
															}
														});
													}
												});
										   });
									});
//
								}
							});	
						}
				 });
			});
	}
	function simSubmit(){
		$(".sim_submit").contextMenu({ menu: 'rmenu', leftButton: true }, 
    function(action, el, pos) { contextMenuWork(action, el.parent("ul"), pos); });
	}
	
	function contextMenuWork(action, el, pos) {
        switch (action) {
            case "listanovos":
                {
                    $.post("modulos/funcs/func_listaresultados.php",{ resp_code : $("#famcode").val(), equip_tipo : 0, tipo_res : 0 } , 
						function(data){
							$("#select_simulacao").hide();
							$("#select_op_pagamento").hide();
							$("#select_finalsimulacao").hide();
							$("#select_concluido").hide();
						
    
							$("#select_lista_resultados").html(data).show();
							$(".lresultados li").mouseover(function (){ $(this).attr({"class":"lresultados_selected"}); })
	.mouseout(function (){ $(this).attr({"class" : ""}); });
	
							$(".prodselect_submit").contextMenu({ menu: 'rmenu2', leftButton: true }, 
    						function(action, el, pos ) { contextMenuWork2(action, el, pos, $(this).attr("alc")); });
							
							$(".prodselect_submit_alc").contextMenu({ menu: 'rmenu2_alc', leftButton: true }, 
    						function(action, el, pos ) { contextMenuWork2_alc(action, el, pos, $(this).attr("alc")); });
							
							/*
							$(".prodselect_submit").contextMenu({ menu: 'rmenu2', leftButton: true }, 
    						function(action, el, pos) { contextMenuWork2(action, el, pos); });
														$(".sel_proposta_aquisicao").click(function() {  
								carregaSimulacao($(this).attr('val'), 1, $(this).attr('tipo'))
							});
							$(".sel_proposta_renting").click(function() {
								carregaSimulacao($(this).attr('val'), 2, $(this).attr('tipo'))
							});
							$(".sel_proposta_acd").click(function() {
								carregaSimulacao($(this).attr('val'), 3, $(this).attr('tipo'))
							});*/
						});
                    break;
                }
            case "listausados":
                {
                    $.post("modulos/funcs/func_listaresultados.php",{ resp_code : $("#famcode").val(), equip_tipo : 1, tipo_res : 0 } , 
						function(data){
							
							$("#select_lista_resultados").html(data).show();
							$(".lresultados li").bind("mouseOver",
								function (){ $(this).attr({"class":"lresultados_selected"}); })
							.bind("mouseOut",function (){ $(this).attr({"class" : ""}); });
							
							$(".prodselect_submit").contextMenu({ menu: 'rmenu2', leftButton: true }, 
    						function(action, el, pos ) { contextMenuWork2(action, el, pos, $(this).attr("alc")); });
							
							$(".prodselect_submit_alc").contextMenu({ menu: 'rmenu2_alc', leftButton: true }, 
    						function(action, el, pos ) { contextMenuWork2_alc(action, el, pos, $(this).attr("alc")); });
							/*
							$(".sel_proposta_aquisicao").click(function() {
								carregaSimulacao($(this).attr('val'), 1, $(this).attr('tipo'))
							});
							$(".sel_proposta_renting").click(function() {
								carregaSimulacao($(this).attr('val'), 2, $(this).attr('tipo'))
							});
							$(".sel_proposta_acd").click(function() {
								carregaSimulacao($(this).attr('val'), 3, $(this).attr('tipo'))
							});
							*/
						});
                    break;
				}
        }

   }
   function contextMenuWork2(action, el, pos) { 
   		switch(action) {
			case "simop1" :  { var tipo = 1; break; }
			case "simop2" :  { var tipo = 2; break; }
		}
		//alert(action);
   		var id = $(el).attr("val");
		var tipousado = $(el).attr("tipousado");
   		carregaSimulacao(id, tipo, tipousado);
   }
    function contextMenuWork2_alc(action, el, pos) { 
   		switch(action) {
			case "simop1" :  { var tipo = 1; break; }
			case "simop2" :  { var tipo = 2; break; }
			case "simop3" :  { var tipo = 3; break; }
		}
   		var id = $(el).attr("val");
		var tipousado = $(el).attr("tipousado");
   		carregaSimulacao(id, tipo, tipousado);
   }

	/*$(".mselect").change(function() {
		$.get("modulos/class_lojaselect.php?p="+$(this).val(),{} , 
			function(data){
				$("#selectForm").append(data);
			},"html");
	});*/
	
	
});