ie7 = $.browser.msie&&($.browser.version <= "7.0");
ie6 = $.browser.msie&&($.browser.version <= "6.0");
ie  = $.browser.msie;

var addthis_config = {
	services_compact: 'twitter,orkut,linkedin,facebook, delicious, google, digg, stumbleupon, technorati, wordpress, googlebuzz, googlereader, hotmail, gmail, more',
	services_exclude: 'print,email',
	data_track_linkback: true
}

$.fn.sombra = function(opt) {
	var options = $.extend(opt);
	return this.each(function(){
		var obj = $(this);
		removeSombra(obj);
		$("<span />").text(obj.text()).addClass("sec").appendTo(obj);
		obj.css({ position: "relative", zIndex: "1" });
	});
	function removeSombra(objeto){
		objeto.find($(".sec")).remove();
	}
}

function sendForm(formObj,passo){
	$.ajax({
		url: "quiz.php?passo="+passo,
		type: $(formObj).attr("method"),
		data: $(formObj).formSerialize(),
		success: function(html){
			var larguraVP = $(window).width();
			$("#content-inner").css({ height: $("#col-dir [id^=passo]").outerHeight() });
			
			if(!ie) {			
				$("#col-dir [id^=passo]").css({ 
					  position: "absolute",
					  width: $("#col-dir [id^=passo]").outerWidth()
				  }).animate({
						  right: larguraVP+700,
						  opacity: "0"
					  }, 400, function(){
						$("#col-dir").css("opacity","0").html(html);
						var novaAltura = $("#col-dir [id^=passo]").outerHeight();
						if (passo==2) var novaAltura = novaAltura-36;
						$("#col-dir [id^=passo]").css({ 
							position: "absolute", 
							bottom: $(window).height()+novaAltura 
						});
						$("#content-inner").animate(
							{ height: novaAltura }, 
							200, 
							function(){
								$("#col-dir").animate(
									{ opacity: "1" },
									100,
									function(){
										if(ie) $("#col-dir").css("filter","");
										$("#col-dir [id^=passo]").animate(
											{ top: "10px" }, 
											200, 
											function(){ 
												$(this).removeAttr("style");
											});
									});
								acoes(passo);
							});
					  });
			
			} else {
				$("#col-dir").html(html);
				$("#content-inner").animate({ height: $("#col-dir [id^=passo]").outerHeight() }, 200, function(){ acoes(passo); });
			}
			
		}
	});
}

function acoes(passo) {
	switch(passo) {
		case 1:
			$("#passo_1 li").click(function(){
					var rd = $("input[type='radio']",this);
					$("#passo_1 input[type='radio']").removeAttr("checked");
					rd.attr("checked",true);
					sendForm($("#passo_1 form"),2);
				});
			if(ie6) {
				$("#passo_1 li").hover(function(){
					$(this).addClass("over");
				}, function(){
					$(this).removeClass("over");				
				});
			}
		break;
		case 2:
			$("#passo_2 a.voltar").click(function(){ sendForm($(this).parents('form'),1); });
			$("#passo_2 a.avancar").click(function(){ 
				if ($("#passo_2 input:checkbox:checked").length == 0) {
					criaAlerta("semchecks");
				} else {
					sendForm($(this).parents('form'),3); 
				};
			});
			var texto 		= $("#passo_2 label");
			var tipoempresa = $("#passo_2 input[name='tipoEmpresa']").attr("value");
			texto.each(function(i){
				if ( i%4 < 2 ) { $(this).parent("li").addClass("cb2"); };
				if (!ie) {
					Cufon.replace(this, {
						hover: { color: '#00a783' },
						hoverables: { label: true },
						fontSize: "16px",
						letterSpacing: "-1px"
					});
				} else {
					$(this).hover(function(){ $(this).addClass("hover") }, function(){ $(this).removeClass("hover"); });	
				};
				$(this).parent("li").click(function(){
					selecionaChecks($(this),tipoempresa);
				});
			});
			if (ie6) {
				$("#passo_2 div.botoes a").hover(function(){
					$(this).addClass("over");
				}, function(){
					$(this).removeClass("over");
				});
			}
		break;
		case 3:
			$("#passo_3 a.rein").click(function(){ sendForm($(this).parents('form'),1); });
			$("#passo_3 a.demo").click(function(){ modal("demo"); });
								
			$("#passo_3 a.envi").click(function(){ modal("envie"); });
		break;
	}
}

function selecionaChecks(elemento,tipoempresa){
	var pai = $(elemento);
	if(tipoempresa=="micropequena") {
		var maxiIni = 3;
	} else {
		var maxiIni = 6;	
	};

	var maxiFim = parseInt($("#passo_2 input:checkbox:checked").length)+1;
	if (maxiFim <= maxiIni) {
		if(pai.find("input:checkbox").is(":checked")){
			pai.removeClass("checked").find("input:checkbox").removeAttr("checked");
		} else {
			pai.addClass("checked").find("input:checkbox").attr("checked",true);
			if(maxiFim == maxiIni) criaAlerta("altern");
		};
	} else {
		if(pai.find("input:checkbox").is(":checked")){
			pai.removeClass("checked").find("input:checkbox").removeAttr("checked");
			fechaAlerta(".altern");
		} else {
			criaAlerta("altern");
		}
	};
}

function criaAlerta(alerta,timeOut) {
	switch(alerta){
		case "altern":
			var html = "Clique em <b>Avançar</b> para ver seu resultado ou desselecione algumas alternativas para continuar.";
		break;
		case "semchecks":
			var html = "Você deve selecionar ao menos uma alternativa para ver o resultado";
		break;
	};	
	if ($("div#col-dir div:eq(0)").attr("id") != "aviso") {
		$("<div />")
			//.attr({id: "aviso", class: alerta})
			.attr("id","aviso")
			.addClass(alerta)
			.html(html)
			.prependTo("#col-dir")
			.css({
				top: $(window).scrollTop() + (($(window).height()-$("#aviso."+alerta).outerHeight()) / 2)+"px",
				marginLeft: ($("#col-dir").width()-$("#aviso."+alerta).outerWidth())/2+"px"/*,
				opacity: "0"*/
			 })
			.click(function(){ fechaAlerta("."+alerta); });
			if (!ie) $("div#aviso."+alerta).css("opacity","0").animate({ opacity: "1" }, 200);
	};
	if (timeOut != false) setTimeout(function(){fechaAlerta("."+alerta)},5000);
}

function modal(tipo,div) {
	altura  = $(window).height();
	largura = $(window).width();
	middle = $(window).scrollTop() + ($(window).height() / 2);
	
	$("<div />").attr("id","over").css({
		width: $(document).width()+"px",
		height: $(document).height()+"px",
		opacity: "0"
					 }).prependTo($("#content")).animate({
						 opacity: "0.5"
					 },400, function(){
						if(div) {
							$("<div />")
								.attr("id","modal")
								.addClass(tipo)
								.html("<div id=\"cabecalhoM\"><h2>Entre em contato</h2><a title=\"Fechar\">Fechar</a></div><p>"+$("#"+tipo).html()+"</p>")
								.insertBefore("#over")
								.css({ opacity: "0" });
								
							var alturaM = $("#modal").outerHeight();
							var larguraM = $("#modal").outerWidth();
							
							$("#modal").css({ 
								top: $(window).scrollTop() + (($(window).height()-$("#modal").outerHeight()) / 2)+"px",
								left: (largura - larguraM)/2
							}).animate({
								opacity: "1"
							}, 200);
							$("a[title='Fechar']").click(function() { fechaAlerta(); });
							
							
						} else {
							$.ajax({
								url: "contato.php?tipo="+tipo,
								success: function(html){
									$("<div />")
										.attr("id","modal")
										.html(html)
										.insertBefore("#over")
										.css({ opacity: "0" });
									var alturaM = $("#modal").outerHeight();
									var larguraM = $("#modal").outerWidth();
									$("#modal").css({ 
										top: $(window).scrollTop() + (($(window).height()-$("#modal").outerHeight()) / 2)+"px",
										left: (largura - larguraM)/2
									}).animate({
										opacity: "1"
									}, 200);
									$("a[title='Fechar']").click(function() { fechaAlerta(); });
									
									$("form fieldset input, form fieldset textarea").focus(function(){
										$("~ i",this).css("visibility","visible");
									}).blur(function(){
										$("~ i",this).css("visibility","hidden");
									});

									$("input[type='submit']").click(function(){ 
										var form = $(this).parents('form');
										var erro = '';
										
										$("input[type='text'],textarea",form).each(function(){
											$(this).removeClass("erro");
											$("fieldset h3",form).slideUp(200);
											if ($(this).val() == '') {
												$(this).addClass("erro");
												erro = true;
											};
										});
										if(erro) {
											criaH3(form,"erroTit","Houve um erro em sua solicitação.<br />Verifique os campos marcados e tente novamente.");
										} else {
											$.ajax({
												url: "contato.php?tipo="+tipo,
												type: form.attr("method"),
												data: form.formSerialize()+"&"+$("form#relatorio").formSerialize(),
												dataType: 'json',
												beforeSend: function(){
													criaH3(form,"aguardeTit","Aguarde...");
													form.find(".s").attr("disabled",true);
												},
												success: function(json){
													form.find(".s").attr("disabled",false);
													if(json.erro) {
														criaH3(form,"erroTit","Houve um erro em sua solicitação. Tente novamente.");
													} else {
														criaH3(form,"sucessoTit","Mensagem enviada com sucesso!");
													};
												}
											});
										}
										return false; 
									});
								}
							});
						};
					 }).click(function(){ fechaAlerta(); });

	criaH3 = function(form,classe,cont) {
		$("fieldset h3",form).slideUp(200);
		$("<h3 />")
			.css("display","none")
			.addClass(classe)
			.html(cont)
			.prependTo("fieldset",form)
			.slideDown(200)
			.attr("title","Clique para esconder esse alerta")
			.click(function(){ $(this).slideUp(200); });
	};

};

function fechaAlerta(alerta) {
	if(!alerta) { 
	$("#modal")
		.animate(
			{ opacity: "0"}
			, 200
			, function(){ 
				$(this).remove(); 
				$("#over").animate({ opacity: "0" }, 500, function(){ $(this).remove(); });
			}
		); 
	} else {
		if (!ie) {
			$(alerta).animate({ opacity: "0" }, 200, function(){ $(this).remove(); });
		} else {
			$(alerta).remove();
		}
	};
}

function mostra(){
	$("<div />")
		.attr("id","preload")
		.append($("<span />"))
		.append($("<h3 />"))
		.append($("<a />").text("Demorou muito tempo? Clique aqui para acessar o site").click(function(){ tiraH(); }))
		.appendTo("body");
	$("<div />").attr("id","imgs").css("display","none").appendTo("#content");
	var imgs = ["bg_addthis","bg_content-inner","bg_t","pg1_bg","pg1_sprite","pg2_bg","pg2_sprite","pg3_bg_y","pg3_sprite","sprite"];
	var pronto = 0
	var imgsle = imgs.length;	
	
	for (i=imgsle;i--;) {
		$("<img />")
			.load(function(){
				pronto++;
				$("#preload h3").html("Carregando! Aguarde. ("+pronto+"0%)");
				if(pronto == imgsle) {
					//$("<h1 />").text("PRONTO!").appendTo("#preload");
					$("#preload").animate({
						opacity: "0"
					}, 500, function(){
						$("#preload").remove();
						tiraH();
					});
				};
			})
			.attr("src","http://www.doquesuaempresaprecisa.com.br/css/img/"+imgs[i]+".png")
			.appendTo("#imgs");
	};

	tiraH = function(){
		$("#content,#footer").css("opacity","0").removeClass("h").animate({ opacity: "1" }, 500);
	};
	
}

$(window).load(function(){

	if(!ie6) { 
		mostra();
	} else {
		$("#content,#footer").removeClass("h");
	};

	$("body").css("overflowX","hidden");
	if(!ie7) $("#col-esq h1, #col-esq h3, #col-esq a").sombra();
	acoes(1);
	$("#col-esq a:eq(0)").click(function(){ modal("indique"); });	
	$("#col-esq a:eq(1)").click(function(){ modal("contato"); });
	$("#col-esq div.t h1").attr("title","Clique para retornar ao passo 1").click(function(){ 
		if($("#col-dir div:eq(0)").attr("id") != "passo_1") sendForm($(this).parents('form'),1); 
	});
	
});
