var enquete = '';
$(document).ready(function(){
						   
	// carrega os box de ultimos trabalhos, monografia e trabalho premiado
	$("#ultimosTrabalhos").load("/ajax/ultimos_trabalhos.asp");
	$("#comoFazerMenu").load("/ajax/como_fazer_2.asp");
	$("#trabalhoPremiado").load("/ajax/trabalho_premiado.asp", function() { tb_init('#trabalhoPremiado a.thickbox, #trabalhoPremiado area.thickbox, #trabalhoPremiado input.thickbox'); });		
	$("#monografiaDoMes").load("/ajax/monografia_do_mes.asp", function() { tb_init('#monografiaDoMes a.thickbox, #monografiaDoMes area.thickbox, #monografiaDoMes input.thickbox'); });
	
	// carrega os box de envio trabalho, comunidades e como fazer
	
	$("#envieTrabalhos").load("/ajax/envie_trabalhos.asp");
	$("#comunidades").load("/ajax/comunidades.asp");
	$("#comoFazer").load("/ajax/como_fazer.asp");
	
	// carrega o box indique um amigo
	
	//$("#indiqueAmigo").load("/ajax/indique/indique_inicio.asp");
	
	// show hide da faq
	
	$(".listaFAQ .pergunta").css("cursor","pointer");
	$(".listaFAQ").bind("click",function() {
		$(this).find(".resposta").slideToggle();
	});


	$('ul.menu_body').bgiframe();			   
	
	
	
	$('#theMenu').accordion({
		active: 'h3.selected',
		header: 'h3.head',
		alwaysOpen: false,
		autoHeight: false,
		animated: 'linear',
		showSpeed: 400,
		hideSpeed: 800
	});
	
	$(function () {
		var tabContainers = $('div.tabs > div');
		tabContainers.hide().filter(':first').show();
		
		$('div.tabs ul.tabNavigation a').click(function () {
			tabContainers.hide();
			tabContainers.filter(this.hash).show();
			$('div.tabs ul.tabNavigation a').removeClass('selected');
			$(this).addClass('selected');
			return false;
		}).filter(':first').click();
	});
	
	$('#imgMenuClick').click(function () {
		$('ul.menu_body').slideToggle('medium');
	});
	
	$("#slider").easySlider();
	
	// inicio mask input
	function setMask(textoBusca, campo) {
		$(campo).val(textoBusca);
		$(campo).focus(function() {
			if ($(this).val() == textoBusca)
				$(this).val('');
			});
		
		$(campo).blur(function() {
			if ($(this).val() == '')
				$(this).val(textoBusca);
			});
	}
	setMask('Busque aqui o seu trabalho, monografia, resenha, resumo, tcc...','.campoBusca');
	setMask('Informe seu email','#txtNewsEmail');
	
	GeraEnquete();
	
	
	var options = { 
		success:       showResponse,
		resetForm: true
	}; 
 
	// bind form using 'ajaxForm' 
	$('#frmNews').ajaxForm(options); 
	function showResponse(responseText, statusText)  { 
		alert(responseText); 
		$('#txtNewsEmail').focus();
	}
	
	//Indique um amigo
	
	$("#indiqueAmigoForm #addOptionList").click(function(){
		
		if($("#indiqueAmigoForm #addEmail").val()!='' && $("#indiqueAmigoForm #addEmail").val() !=''){
			$("#indiqueAmigoForm #emailList").addOption("" + $("#indiqueAmigoForm #addEmail").val() + ";" + $("#indiqueAmigoForm #addNome").val() +  "", ""+ $("#indiqueAmigoForm #addNome").val() + "<" + $("#indiqueAmigoForm #addEmail").val() +">")
			$("#indiqueAmigoForm #addEmail").val('') 
			$("#indiqueAmigoForm #addNome").val('')
		}
		else {
			alert("Para adicionar na lista de e-mails para enviar informe o nome e o e-mail de seu amigo!");
		}		
	});
	
	$("#indiqueAmigoForm #submitContatos").click(function() {
	
		var text = "<p align=\"center\">Aguarde carregando contatos...</p>";
		$("#indiqueAmigoForm #contatos").html(text);
		
		$("#indiqueAmigoForm #submitContatos").attr("disabled","disabled");
		$("#indiqueAmigoForm #submitContatos").attr("value","carregando...");
	
		var usuario = $("#indiqueAmigoForm #usuario").val();
		var senha = $("#indiqueAmigoForm #senha").val();
		$("#indiqueAmigoForm #txtUserEnd").val(usuario);
		$("#indiqueAmigoForm #txtPassEnd").val(senha);		
		
		$('#callContacts').ajaxSubmit({ 
			target:        '#indiqueAmigoForm #contatos',   // target element(s) to be updated with server response 
			
	 
			// other available options: 
			url:       	'/ajax/indique/contatos_processa.asp',        // override for form's 'action' attribute 
			type:      	'post',       // 'get' or 'post', override for form's 'method' attribute 
			dataType:  	'xml',        // 'xml', 'script', or 'json' (expected server response type) 
			success:   	processXml
		});
		
	});
	
	
	$("#indiqueAmigoForm #contatoAlpha").change(function() {
		if(this.checked){
			$("#indiqueAmigoForm #login").css("display","block");
		}
		else{
			$("#indiqueAmigoForm #login").css("display","none");
		}	
	});
	
	
	
	$("#indiqueAmigoForm #contatoRowAll").change(function() {
		var checked_status = this.checked; 
        $("#indiqueAmigoForm input[name=contatoRow]").each(function(){ 
        	this.checked = checked_status; 
        }); 
    });
	
	// E-commerce
	
	$("#continuarComprando").click(function(){
		window.location.href = '/ecommerce';
	});
	
	$("#calcularFrete").click(function(){
		
		areaId = $("input[name='area']:checked").val();
		estadoId = $("#codEstado").val()
		freteTipo = $("#tipo_frete").val()
		
		var valid = true;
		
		$("div.maisInfo5").hide();
		
		if($("input[name='area']:checked").length < 1) {
			$("div.maisInfo5").show();
			$("div.maisInfo5 li.erroMsg").html("Você precisa definir uma área de entrega capital ou interior");
			valid = false;
		}
		
		if($("#codEstado").val().length < 1){
			$("div.maisInfo5").show();
			$("div.maisInfo5 li.erroMsg").html("Você precisa selecionar um estado");
			valid = false;
		}
		
		if($("#tipo_frete").val().length < 1){
			$("div.maisInfo5").show();
			$("div.maisInfo5 li.erroMsg").html("Você precisa escolher um tipo de frete");
			valid = false;
		}
		
		if(valid==true){
			$.getJSON("/ajax/frete.asp?area=" + areaId +"&uf_entrega="+ estadoId + "&tipo_frete=" + freteTipo + "", {}, function(j){
				$("#frete_id").val(j.frete_id)
				$("#valorFrete").html("Frete: " + j.valor +"")
				$("#valorTotal").html("Total: " + j.total +"")
			});
		}
	});
	
	$('#frmCheckout').submit(function(){
		
		$("div.maisInfo5").hide();
		
		
		var valid = true;
		if ($("#frmCheckout").length > 0 && $("#codEstado").length > 0) {
			if ($("#frete_id").val() == '') {
				if($("input[name='area']:checked").length < 1) 
					valid = false;
				
				if($("#codEstado").val().length < 1)
					valid = false;
				
				if($("#tipo_frete").val().length < 1)
					valid = false;
			}
		}
		if(!valid) {
			$("div.maisInfo5").show();
			$("div.maisInfo5 li.erroMsg").html("Você precisa definir as informações para o cálculo do Frete!");	
		} else {
			if($("#frete_id").val().length < 1){
				
				$("div.maisInfo5").show();
				$("div.maisInfo5 li.erroMsg").html("Você precisa fazer o cálculo do Frete!");
				valid = false;
			}
			
			if($("#logged").val() != "true"){
				$("div.maisInfo5").show();
				$("div.maisInfo5 li.erroMsg").html("Você precisa se logar para concluir o processo de compra!");
				$("#frmLoginEcommerce #email").focus()
				valid = false;
			}
		}
		
		return valid;
	
	});
	
	$("#frmDelivery #getUserData").change(function(){
		switch ($(this).val()){
		
			case 'true':
			
				$.getJSON("/ajax/dados_usuarios.asp", {}, function(j){
					$("#frmDelivery #cep_entrega").val(j.cep);
					$("#frmDelivery #endereco_entrega").val(j.endereco);
					$("#frmDelivery #numero_entrega").val(j.numero);
					$("#frmDelivery #complemento_entrega").val(j.complemento);
					$("#frmDelivery #bairro_entrega").val(j.bairro);
					$("#frmDelivery #uf_entrega").val(j.codEstado);
					selectState(j.pais,j.codEstado,$("#uf_entrega"));
					selectCity(j.codEstado, j.cidade ,$("#cidade_entrega"));
					
				});
				
			break;
			
			default:
				$("#frmDelivery #cep_entrega").val('');
				$("#frmDelivery #endereco_entrega").val('');
				$("#frmDelivery #numero_entrega").val('');
				$("#frmDelivery #complemento_entrega").val('');
				$("#frmDelivery #uf_entrega").val('');
		
		}
	});
	
	// campo uf_entrega do e-commerce
	$("#frmDelivery  select#uf_entrega").change(function(){
		$.getJSON("/getCidade.asp?codEstado=" + $(this).val(), {}, function(j){
			var options = [] // use array for speed
			options.push('<option value="">Selecione</option>')
			var iter = j.length //cache for speed
			for (var i = 0; i < iter; i++) {
				options.push('<option value="' + j[i].id + '">' + j[i].nome + '</option>')
			}
			$("#cidade_entrega").html(options.join('\n'));
		});
	});
	
	// campo tipo_produto do e-commerce
	$("#tipo_produto_id").change(function(){
		$.getJSON("/ajax/subCategorias.asp?tipo_produto_id=" + $(this).val(), {}, function(k){
			var options = [] // use array for speed
			options.push('<option value="">Selecione</option>')
			var iter = k.length //cache for speed
			for (var i = 0; i < iter; i++) {
				options.push('<option value="/ecommerce/vitrine.asp?tipo_produto_id=' + k[i].tipo + '&sub_tipo_produto_id=' + k[i].id + '">' + k[i].nome + '</option>')
			}
			$("#sub_tipo_produto_id").html(options.join('\n'));
		});
	});
	
	$("#sub_tipo_produto_id").change(function(){
		window.location = $(this).val();										  
	});
	

	//formulário de entrega
	
	$("#frmDelivery #btnVoltar").click(function(){
		history.back();
	})
	
	$("#frmDelivery").submit(function(){
									   
		//zera todas as validações
		$("#frmDelivery .CEP").hide();
		$("#frmDelivery .Endereco").hide();
		$("#frmDelivery .Numero").hide();
		$("#frmDelivery .Bairro").hide();
		$("#frmDelivery .Cidade").hide();
		$("#frmDelivery .Estado").hide();

		var valid = true;
		if($("#frmDelivery #cep_entrega").val().length < 1) {
			$("#frmDelivery .CEP").show();
			valid = false;
		}
		
		if($("#frmDelivery #endereco_entrega").val().length < 1) {
			$("#frmDelivery .en").show();
			valid = false;
		}
		
		if($("#frmDelivery #numero_entrega").val().length < 1) {
			$("#frmDelivery .en").show();
			valid = false;
		}
		
		if($("#frmDelivery #bairro_entrega").val().length < 1) {
			$("#frmDelivery .bec").show();
			valid = false;
		}
		
		if ($("#frmDelivery #cidade_entrega").val() == "") {
			$("#frmDelivery .bec").show();
			valid = false;
		}
		
		if ($("#frmDelivery #uf_entrega").val() == "") {
			$("#frmDelivery .bec").show();
			valid = false;
		}
		
		return valid;
	});
	
	$("#cep_entrega").bind("blur",function(){
		$.getJSON("/getCep.asp",{cep: $(this).val()}, function(j)
		{
			$("#frmDelivery #endereco_entrega").val(j.endereco);
			$("#frmDelivery #bairro_entrega").val(j.bairro);
			selectState("30", j.codEstado, $("#uf_entrega"))
			selectCity(j.codEstado, j.codCidade, $("#cidade_entrega"))
		});
	});
	
	
	//validação do pagamento e-commerce
	
	// define o campo hidden da forma de pagamento de acordo com a seleção pelo usuário
	$("#frmCompraEcommerce input[name='TipoCartao']").click(function(){
		$("#frmCompraEcommerce #FormaPag").val("C");
		$("input[name='TipoDebito']").each(function(){this.checked = false});
		$("input[name='TipoBoleto']").each(function(){this.checked = false});
	});
	
	$("#frmCompraEcommerce #boleto").click(function(){
		$("#FormaPag").val("B");
		$("input[name='TipoDebito']").each(function(){this.checked = false});
		$("input[name='TipoCartao']").each(function(){this.checked = false});
	});
	
	$("#frmCompraEcommerce").bind("submit",validaCompraEcommerce);
	
	
	function validaCompraEcommerce(){
		
		$("#frmCompraEcommerce .maisInfo4").hide();
		
		var valid = true;
		
		if ($("#frmCompraEcommerce #FormaPag").val() =='') {
			$("#frmCompraEcommerce .maisInfo4").show();
			$("#frmCompraEcommerce .FormaPag").show();
			window.location=window.location+'#erro';
			valid = false;
		}
		else {
			$("#frmCompraEcommerce .FormaPag").hide();
			
		}
		
		if (valid) {
			// valida as formas de pagamento (boleto n valida)
			switch($("#frmCompraEcommerce #FormaPag").val())
			{
				
				case 'C':
					if ($("#frmCompraEcommerce input[name='TipoCartao']:checked").length <= 0) {
						$("#frmCompraEcommerce .TipoCartao").show();
						valid = false;
					} else {
						$("#frmCompraEcommerce .TipoCartao").hide();
					}
					if ($("#frmCompraEcommerce input[name='NumeroCartao']").val().length < 12 || $("#frmCompraEcommerce input[name='CodigoSeguranca']").val().length < 3) {
						$("#frmCompraEcommerce .cn").show();
						valid = false;
					} else {
						$("#frmCompraEcommerce .cn").hide();
					}
					if ($("#frmCompraEcommerce #MesValidade").val().length < 2 || $("#frmCompraEcommerce #AnoValidade").val().length < 2)
					{
						$("#frmCompraEcommerce .data").show();
						valid = false;
					} else {
						$("#frmCompraEcommerce .data").hide();
					}
				break;
			}
		}
		
		return valid;
	}
	if ($("#frmCheckout").length > 0) {
		if ($("#codEstado").length > 0) {
			testaFG();
			$("#tipo_frete").bind('change',function() { $("#frete_id").val('');});
			$("#codEstado").bind('change',function() { $("#frete_id").val('');});
			$("input[name='area']").bind('click',function() { $("#frete_id").val('');});
		}
	}
});

function GeraEnquete() {
	$('#frmEnquete').bind('submit', function() {
			enquete = $("#enqLocation").html();
			$(this).ajaxSubmit({
				target: '#enqLocation'
			});
			return false;
		});
	
	$('#btnResultadoEnq').click(function() {
			 enquete = $("#enqLocation").html();
			$("#enqLocation").load("/enquete_resultado.asp?codPergunta=" + $('#codPergunta').val() +"");
	});
		
	$('#btnVotarEnq').click(function() {
			enquete = $("#enqLocation").html();
			$("#enqLocation").load("/enquete_votar.asp?codCarreira=" + $('#codCarreira').val() + "");
		});	
}

function selectCity(state,city,field){
	field.removeOption(/./);
	field.addOption("", "Carregando...");
	$.getJSON("/getCidade.asp?codEstado=" + state, {}, function(j){
		field.removeOption(/./);
		field.addOption("", "Selecione",false);
		var iter = j.length //cache for speed
		for (var i = 0; i < iter; i++) {
			field.addOption(j[i].id, j[i].nome,city == j[i].id);
		}
	});
}
	
function selectState(country, state, field){
	field.removeOption(/./);
	field.addOption("", "Carregando...");
	$.getJSON("/getEstado.asp?codPais=" + country, {}, function(j){
		field.removeOption(/./);
		field.addOption("", "Selecione",false);
		var iter = j.length //cache for speed
		for (var i = 0; i < iter; i++) {
			field.addOption(j[i].codEstado, j[i].Estado,state == j[i].codEstado);
		}
	});
}

function processXml(responseXML){ 
    	
	var text = "<table width=\"367\" border=\"0\" align=\"center\" cellpadding=\"0\" cellspacing=\"2\">";
	var i = 0;
		
	$('contato', responseXML).each(function(){ 
   			
		if($("email", this).text()!='' && $("nome", this).text()!='' ){
			
			text += "<tr>";
			text += "<td width=\"30\" align=\"center\"><input type=\"checkbox\" name=\"contatoRow\" id=\"contatoRow\" value=\"" + $("email", this).text()+ ";" + $("nome", this).text() + "" + "\" checked></td>";
			if($("email", this).text() != $("nome", this).text()){
				text += "<td width=\"301\"><span class=\"txt01\">" + $("nome", this).text() + "&nbsp;&#8249;" + $("email", this).text() + "&#8250;</span></td>";
			}
			else {
				text += "<td width=\"301\"><span class=\"txt01\">" + $("email", this).text() + "</span></td>";
			}
			text += "</tr>";
		}
			
		i = i + 1;
			
	});
		
	text += "</table>"; 
		
	if(i==0){
		alert("Usuário inválido ou senha incorreta!");
	}
	else{
			$("#indiqueAmigoForm #contatos").html(text);
			$("#indiqueAmigoForm #contatos").css("display","block");
	}
		
	$("#indiqueAmigoForm #usuario").val('');
	$("#indiqueAmigoForm #senha").val('');
	$("#indiqueAmigoForm #submitContatos").removeAttr("disabled");
	$("#indiqueAmigoForm #submitContatos").attr("value","OK");
		
}

var tgs = new Array( 'trabalho');
var szs = new Array( 'xx-small','x-small','small','medium','large','x-large','xx-large' );
var startSz = 2;

function ts( trgt,inc ) {
	if (!document.getElementById) return
	var d = document,cEl = null,sz = startSz,i,j,cTags;
	sz += inc;
	if ( sz < 0 ) sz = 0;
	if ( sz > 6 ) sz = 6;
	startSz = sz;
	if ( !( cEl = d.getElementById( trgt ) ) ) cEl = d.getElementsByTagName( trgt )[ 0 ];
	cEl.style.fontSize = szs[ sz ];
	for ( i = 0 ; i < tgs.length ; i++ ) {
		cTags = cEl.getElementsByTagName( tgs[ i ] );
		for ( j = 0 ; j < cTags.length ; j++ ) cTags[ j ].style.fontSize = szs[ sz ];
	}
}

function testaFG() {
	selFG = $("#codEstado");
	if (selFG.val() == '') {
		$("#showFreteG").hide();
		$("#showCalcFrete").hide();
		$("#showFrete").hide();
		$("#frete_id").val('');
	} else {
		if (selFG.attr('freteGratisEstados').indexOf(','+selFG.val()+',') != -1) {
			$("#showFreteG").show();
			$("#showCalcFrete").hide();
			$("#showFrete").hide();
			$.getJSON("/ajax/frete.asp?area=1&uf_entrega="+ selFG.val() + "&tipo_frete=4", {}, function(j){
				$("#frete_id").val(j.frete_id)
				$("#valorFrete").html("Frete: " + j.valor +"")
				$("#valorTotal").html("Total: " + j.total +"")
			});
		} else {
			$("#showFreteG").hide();
			$("#showCalcFrete").show();
			$("#showFrete").show();
			areaId = $("input[name='area']:checked").val();
			estadoId = $("#codEstado").val()
			freteTipo = $("#tipo_frete").val()
			
			var valid = true;
			
			$("div.maisInfo5").hide();
			
			if($("input[name='area']:checked").length < 1) 
				valid = false;
			
			if($("#codEstado").val().length < 1)
				valid = false;
			
			if($("#tipo_frete").val().length < 1)
				valid = false;
			
			if(valid==true){
				$.getJSON("/ajax/frete.asp?area=" + areaId +"&uf_entrega="+ estadoId + "&tipo_frete=" + freteTipo + "", {}, function(j){
					$("#frete_id").val(j.frete_id)
					$("#valorFrete").html("Frete: " + j.valor +"")
					$("#valorTotal").html("Total: " + j.total +"")
				});
			} else {
				$("#frete_id").val('');	
			}
	
		}
	}
}