$(document).ready(function() {
	if($.browser.msie && ($.browser.version < 7)){ $("body").addClass("ie") } //Adiciona uma classe para o IE6.
	$(".box267").click(function(){
		window.location = $(this).find("a").attr("href");
		return false;
	});
	
	$("div.conteudoParceiros a.btnVerTodos").click(function(){
				if($(this).parent().find(".txtEsconde").is(":visible")){
					//alert("sim");
					$(this).removeClass("hover").parent().find(".txtUltimos").show();
					$(this).parent().find(".txtEsconde").hide();
					//$(this).next().slideUp("slow");
				}else{
					//alert("nao");
					$("div.conteudoParceiros .txtEsconde").hide().parent().find(".txtUltimos").show().parent().find("a.btnVerTodos").removeClass("hover");
					$(this).addClass("hover").parent().find(".txtUltimos").hide();
					$(this).parent().find(".txtEsconde").show();
					//$(this).next().slideDown("slow");
				}
				//$("div.conteudoParceiros .txtEsconde").hide();
				return false;
			});

		

	$('#formLogin').validate({ errorLabelContainer: $('.msgError'),
        submitHandler: function() {
            $.ajax({
                type: 'POST',
                data: $('#formLogin').serialize(),
                dataType: 'json',
                url: '/wp-content/themes/endeavor/validaLogin.php',
                success: function(json) {
                    if (json.msg == 'ok') {
                        //window.location = 'home.php';
                        //$(".msgSucesso").fadeIn().animate({opacity: 1.0}, 8000).fadeOut('slow');
						alert("Seu cadastro no evento foi realizado com sucesso!");
						window.location = '/?p=' + json.id;
						//window.location = '/eventos';
                    }else if (json.msg == 'eventoCadastrado'){
						alert("Você já estava cadastrado neste evento!");
					}else if (json.msg == 'erroLogin'){
                        alert("E-mail e/ou senha inválido(s)!");
                    }else if (json.msg == 'ocupado'){
                        alert("Desculpe-nos o evento encontra-se lotado.");
                    }else {
                        alert("Erro ao registrar!");
                    }
					
                }
            });
        }
    });

	$("#flashConteudo .flashInner").flash({ src: '/wp-content/themes/endeavor/swf/tvflash.swf', width: 620, height: 374, wmode: 'opaque', flashvars: { xmlPath: ['geraxmlflashhome'].join(' ') }}, {version: '8'});
	
	$("#flashGlobal").flash({ src: '/wp-content/themes/endeavor/swf/endeavorGlobal.swf', width: 1000, height: 404, wmode: 'opaque' }, {version: '8'});
	$("#flashSemana").each(function(){
		$urlSite = $(this).find("a").attr("href");
		$(this).flash({ src: '/wp-content/themes/endeavor/swf/semana.swf', width: 1000, height: 342, wmode: 'opaque', flashvars: { urlSite: [$urlSite].join(' ') }}, { version: 8 });
	});


	$("#video267x170").each(function(){
		$flv = $(this).attr("rel");
		$(this).flash({ src: '/wp-content/themes/endeavor/swf/playerEndeavorGlobal.swf', width: 267, height: 173, wmode: 'transparent', flashvars: { flvPath: [$flv].join(' ') }}, { version: 8 });
	});

	
	$("#boxCalendario").flash({ src: '/wp-content/themes/endeavor/swf/calendario.swf', width: 255, height: 200, wmode: 'opaque', flashvars: { xmlPath: ['geraxmleventos'].join(' ') }}, { version: 8 });
	
	$("#flashBotaPraFazer").flash({ src: '/wp-content/themes/endeavor/swf/campanha.swf', width: 766, height: 670, wmode: 'transparent', flashvars: { xmlPath: ['/wp-content/themes/endeavor/swf/xml/campanha.xml'].join(' ') }}, { version: 8 });/* 683x769 */
	$("#flashBotaPraFazerRedondo").flash({ src: '/wp-content/themes/endeavor/swf/campanha_redondo.swf', width: 766, height: 670, wmode: 'transparent', flashvars: { xmlPath: ['/wp-content/themes/endeavor/swf/xml/campanha.xml'].join(' ') }}, { version: 8 });/* 683x769 */

	$("#flashCases").each(function(){
		$flv = $(this).attr("rel");
		$(this).flash({ src: '/wp-content/themes/endeavor/swf/playerEndeavorBrasil.swf', width: 383, height: 230, wmode: 'transparent', flashvars: { flvPath: [$flv].join(' ') }}, { version: 8 });
	});

	$("#containerVideo").each(function(){
		$flv = $(this).attr("rel");
		$(this).flash({ src: '/wp-content/themes/endeavor/swf/playerCases.swf', width: 514, height: 327, wmode: 'transparent', flashvars: { flvPath: ['/wp-content/themes/endeavor/swf/flv/' + $flv].join(' ') }}, { version: 8 });
	});

	/*	CASES */
	$("#boxCarouselCases").jcarousel({ scroll: 4, easing: 'easeout', animation: 'slow' });
	$("#boxCarouselCases li").click(function(){
		$id = $(this).attr("id");
		$.getJSON("/json-cases.php?id=" + $id, function(data){
			cases = data;
			casesView($id);
			$("#boxVideo").slideDown("slow", function(){
				$("#boxVideo #containerVideo, #boxVideo .content").hide().fadeIn();
			});
		});
		return false;
	});
	//$case = setTimeout('$("#boxCarouselCases li:first").trigger("click")', 500);
	$("#boxVideo").slideDown("slow", function(){
		$("#boxVideo #containerVideo, #boxVideo .content").hide().fadeIn();
	});
	$("#boxCarouselCases li .item").hoverIntent(function(){
		$(this).find("h3,h4").fadeIn("slow");
	}, function(){
		$(this).find("h3,h4").fadeOut("slow");
	});
	$("a.btnFecharBoxVideo").live("click", function(){
		$("#boxVideo #containerVideo, #boxVideo .content").fadeOut("fast", function(){
			$("#boxVideo").slideUp("slow");
		});
		return false;
	});
	/*	CASES */

	$("#flashTwitter").flash({ src: 'http://static.twitter.com/flash/widgets/profile/TwitterWidget.swf', width: 263, height: 209, wmode: 'transparent', allowScriptAccess: 'always', flashvars: { userID: ['52048386'].join(' '), styleURL: ['http://static.twitter.com/flash/widgets/profile/smooth.xml'].join(' ') }}, { version: 8 });
	
	$("ul.listEventos li .ilustracao, .boxSejaEmpreendedor .img, .boxEventosDetalhe .left .img, .boxGray .img, ul#carouselCases li .item, .listArtigosPalestras .item .left .img, .box250 .img, .boxPressKit .img").append("<span></span>");
	$(".boxValores .item:eq(0) .content").append("<span class='seta1'></span>");
	$(".boxValores .item:eq(1) .content").append("<span class='seta2'></span>");
	$(".boxValores .item:eq(2) .content").append("<span class='seta3'></span>");
	$(".boxValores .item:eq(3) .content").append("<span class='seta4'></span>");
	$(".boxValores .item:eq(4) .content").append("<span class='seta5'></span>");
	$("#boxParceiros .item a, .containerLine .item a, .containerLine .desc").append('<span class="fix"></span>');

	$(".listArtigosPalestras .item:last").css("border-bottom","none");
	$("ul.listMaisLidos li:last").css("background","none");

	$(".boxAccordion h3").append('<span></span>');
	$(".boxAccordion .accor").append('<a class="btnEncolher" href="#">Encolher</a>');
	$(".boxAccordion h3").click(function(){
		$(".boxAccordion h3").removeClass("hover");
		$(".boxAccordion .accor").slideUp();
		if($(this).next().is(":visible")){
			$(this).removeClass("hover").next().slideUp();
		}else{
			$(this).addClass("hover").next().slideDown();
		}
	});
	$(".boxAccordion h3:first").trigger("click");
	$(".boxAccordion .accor a.btnEncolher").click(function(){
		$(this).parent().prev().trigger("click");
		return false;
	});

	$("a.btnNavConselho").live("click", function(){
		$itens = $(this).attr("href").split("#")[1];
		$active = $("ul.listConselho").find(".hide").size();
		
		if($(this).hasClass("active")){
			$(this).removeClass("active");
			$("a.btnNavConselho").removeClass("hover");
			$("ul.listConselho li").removeClass("hide").show();
		}else{
			
			$("a.btnNavConselho").removeClass("active").addClass("hover");
			$(this).removeClass("hover").addClass("active");
			$("ul.listConselho li").hide();
		}
		$("ul.listConselho li."+ $itens +"").addClass("hide").show();
		return false;
	});

    $("input + label").click(function() {
		if ($(this).prev().attr("type") == 'checkbox') {
			if ($(this).prev().is(":checked")) {
				$(this).prev().attr("checked", false);
			} else {
				$(this).prev().attr("checked", true);
			}
		} else {
			$(this).prev().attr("checked", true);
		}
    });

	$(".boxSidebar h2").click(function(){
		if($(this).next().is(":visible")){
			$(this).addClass("hover").next().slideUp("slow").next().css("margin-top", "-1px");
			$(this).parent().find("a.saibaMais").fadeOut("fast");
		}else{
			$(this).removeClass("hover").next().slideDown("slow").next().css("margin-top", "-12px");
			$(this).parent().find("a.saibaMais").fadeIn("slow");
		}
	});


    $("select#pais").change(function() {
		$idPais = $(this).val();
		$.ajax({
			dataType: "html",
			url: '/ajaxEstados.php?pais=' + $idPais,
			success: function(html) {
				$("select#estado, select#cidade").html('<option value="">Selecione<option>');
				$("select#estado").html("").html(html);
			}
		});
    });

    $("select#estado").change(function() {
        $idEstado = $(this).val();
		$.ajax({
			dataType: "html",
			url: '/ajaxCidades.php?estado=' + $idEstado,
			success: function(html) {
				$("select#cidade").html('<option value="">Selecione<option>').html(html);
			}
		});
    });


	$("table#guiaJuniores tbody tr:even td:even").addClass("evenEven");
	$("table#guiaJuniores tbody tr:even td:odd").addClass("evenOdd");
	$("table#guiaJuniores tbody tr:odd td:even").addClass("oddEven")
	$("table#guiaJuniores tbody tr:odd td:odd").addClass("oddOdd")
	$("table.formHistorico tr td:even").addClass("even");
	$("table.formHistorico tr  td:odd").addClass("odd");

	$(".videosArtigosLeft .boxTitle").append("<span></span>");

	$("ul.listParceiros li a img").each(function(){
		$(this).fadeTo("slow", 0.5);
		$(this).hoverIntent(function(){
			$(this).fadeTo("slow", 1.0); // This sets the opacity to 100% on hover
		},function(){
			$(this).fadeTo("slow", 0.5); // This sets the opacity back to 50% on mouseout
		});
	});
	
	/* tagCloud 
	$links = '';
	$(".tagcloud a").each(function(){
		$tamanho = $(this).css('font-size');
		$(this).attr({ style: 'font-size:' + $tamanho }).removeAttr('class');
		//$links += $(this).html();
	});
	$val = '<tags>' + $(".tagcloud").html() + '</tags>';
	$val = $val.toLowerCase();
	$(".tagcloud").each(function(){
		$w = $(this).width();
		$h = $(this).height();
		$color = $(this).find("a").css("color");
		if($.browser.msie == false){
			$color = rgb2hex($color);
		}else{
			$color = $color.split("#")[1];
		}
		$(this).flash({ src: '/wp-content/themes/endeavor/swf/tagcloud.swf', width: $w, height: $h, wmode: 'transparent',  flashvars: { tagcloud: $val, distr: "true", mode: "both", tcolor: "0x" + $color, tcolor2: "0x" + $color, hicolor: "0x000000", tspeed: "200" } });
	});
	*/
	/* tagCloud */

	$("ul#tabMais").idTabs();
	$("input.cpf").mask("999.999.999-99");
	$("input.data").mask("99/99/9999");
	$("input.cep").mask("99999-999");
	$("input.cnpj").mask("99.999.999/9999-99");
	$(".fix, .subTit").ifixpng();

	$(".formValidate").each(function(){
		$(this).validate({ errorLabelContainer: $(this).find(".msgError") });	
	});

	$("#formCadastro").validate({ errorContainer: $(".msgErroEvento"), errorLabelContainer: $(".msgError"),
		submitHandler: function() {
			$.ajax({
				type: 'POST',
				data: $("#formCadastro").serialize(),  
				dataType: "json",
				url:'/cadastro_insert.php',
				success: function(json) {
					if(json.success == 'ok'){
						//$(".msgSucesso").fadeIn().animate({opacity: 1.0}, 4000).fadeOut('slow');
						alert("Seu cadastro foi enviado com sucesso!")	;
						window.location = '/?p=' + json.id;
					}else if (json.success == 'duplicado')
					{
							alert("CPF já cadastrado!");
					}else if (json.success == 'invalido')
					{
							alert("CPF inválido!");
					}else if (json.success == 'naoconfere')
					{
							alert("Senha e Confirmação não são iguais!");
					}else if (json.success == 'senhapequena')
					{
							alert("A senha deve ter no mínimo 6 dígitos!");
					}else if (json.success == 'faltadado')
					{
							alert("Por favor preencha todos os campos marcados como obrigatórios!");
					}else if (json.success == 'ocupado')
					{
							alert("Cadastro completado porém o evento já encontra-se lotado.");
					}else 
					{
							alert("Erro ao tentar salvar dados!");
					}			
					
				}  
			});
		}
	});

	$("#formFaleconosco").validate({ errorContainer: $(".msgError"),
		submitHandler: function() {
			$.ajax({
				type: 'POST',
				data: $("#formFaleconosco").serialize(),  
				dataType: "json",
				url: $("#formFaleconosco").attr("action"),
				success: function(json) {
					if(json.msg == 'true'){
						$(".boxFaleconosco .msgSucesso").fadeIn().animate({opacity: 1.0}, 4000).fadeOut('slow');
						$(".boxFaleconosco").find("textarea, select").val("");
					}else{
						alert("Erro!");
					}
				}  
			});
		}
	});

	$("a.btnMandeAmigo").click(function() {
		$("#formIndiqueAmigo .sucesso, #formIndiqueAmigo .erro").hide();
		$("#formIndiqueAmigo .contentForm").show();
		tb_show('', '#TB_inline?width=700&height=333&inlineId=lightboxAmigo', false);
		return false;
	});

	$("#formIndiqueAmigo").validate({ errorContainer: $(".msgError"),
		submitHandler: function() {
			$url = $("#formIndiqueAmigo").attr("action");
			$.ajax({
				type: 'POST',
				data: $("#formIndiqueAmigo").serialize(),  
				dataType: "json",
				url: $url,
				success: function(json) {
					$("#formIndiqueAmigo .contentForm").hide();
					if(json.msg == 'success'){
						$("#formIndiqueAmigo .sucesso").fadeIn();
					}else{
						$("#formIndiqueAmigo .erro").fadeIn();
					}
				}  
			});
		}
	});
	$("#boxComent a.btnFechar").click(function() {
		tb_remove();
		return false;
	});


});

function casesView(idPost){
	html = '';
	pos = 0;
	for(x = 0; x < cases.length; x++){
		if(cases[x]['id'] == idPost){
			pos = x;
			html += '<a class="btnFecharBoxVideo" href="#">Fechar</a>';
			html += '<div class="boxFicha">';
				html += '<label>Empreendedor:</label> '+cases[x]['empreendedor']+'<br />';
				html += '<label>Setor:</label> '+cases[x]['setor']+'<br />';
				html += '<label>Ano de sele&ccedil;&atilde;o na Endeavor:</label> '+cases[x]['anoSelecao']+'<br />';
				html += '<label>Ano de funda&ccedil;&atilde;o:</label> '+cases[x]['anoFundacao']+'<br />';
				html += '<label>N&uacute;mero de funcion&aacute;rios:</label> '+cases[x]['funcionarios']+'<br />';
				//html += '<label>Website:</label> '+cases[x]['site'];
				html += '<label>Website:</label> <a href="'+cases[x]['site']+'" target="_blank">'+cases[x]['site']+'</a>';
			html += '</div>';
			html += '<div class="boxTags">';
				if(cases[x]['tags'] != ""){
				html += '<p><strong>Tags:</strong>'+cases[x]['tags']+'</p>';
				}else{
				html += '<p> </p>';
				}
			html += '</div>';
			html += '<div class="boxTags">';
				html += '<p><strong>Compartilhe:</strong>';
				html += 'EMBED: <input type="text" name="inputCompartilhe" id="inputCompartilhe" value="'+cases[x]['site']+'" readonly="readonly" /></p>';
			html += '</div>';
			html += '<br clear="all" />';
			html += '<div class="boxDescVideo">';
				html += cases[x]['sobreEmpreendedor'];
			html += '</div>';
		}
		if(cases[pos]['video'] == "#"){
			$("#containerVideo").html("").css("background", " #FFF url("+ cases[pos]['imagem'] +") center no-repeat");
		}else{
			$("#containerVideo").css("background", "none").flash({ src: '/wp-content/themes/endeavor/swf/playerCases.swf', width: 514, height: 327, wmode: 'transparent', flashvars: { flvPath: ['/wp-content/themes/endeavor/swf/flv/'+cases[pos]['video']].join(' ') }}, { version: 8 });
		}
	}
	$("#casesView").html(html);	
	//$("#containerVideo").flash({ src: 'wp-content/themes/endeavor/swf/playerCases.swf', width: 514, height: 327, wmode: 'transparent', flashvars: { flvPath: ['/wp-content/themes/endeavor/swf/flv/' + cases[pos]['video']].join(' ') }}, { version: 8 });
}


/*
function rgb2hex(rgb) {
	rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
	function hex(x) {
		hexDigits = new Array("0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f");
		return isNaN(x) ? "00" : hexDigits[(x - x % 16) / 16] + hexDigits[x % 16];
	}
	return hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
}
*/

/**
* hoverIntent r5 // 2007.03.27 // jQuery 1.1.2+
* http://cherne.net/brian/resources/jquery.hoverIntent.html
* 
* @author    Brian Cherne <brian@cherne.net>
*/
(function($){$.fn.hoverIntent=function(f,g){var cfg={sensitivity:7,interval:100,timeout:0};cfg=$.extend(cfg,g?{over:f,out:g}:f);var cX,cY,pX,pY;var track=function(ev){cX=ev.pageX;cY=ev.pageY;};var compare=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);if((Math.abs(pX-cX)+Math.abs(pY-cY))<cfg.sensitivity){$(ob).unbind("mousemove",track);ob.hoverIntent_s=1;return cfg.over.apply(ob,[ev]);}else{pX=cX;pY=cY;ob.hoverIntent_t=setTimeout(function(){compare(ev,ob);},cfg.interval);}};var delay=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);ob.hoverIntent_s=0;return cfg.out.apply(ob,[ev]);};var handleHover=function(e){var p=(e.type=="mouseover"?e.fromElement:e.toElement)||e.relatedTarget;while(p&&p!=this){try{p=p.parentNode;}catch(e){p=this;}}if(p==this){return false;}var ev=jQuery.extend({},e);var ob=this;if(ob.hoverIntent_t){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);}if(e.type=="mouseover"){pX=ev.pageX;pY=ev.pageY;$(ob).bind("mousemove",track);if(ob.hoverIntent_s!=1){ob.hoverIntent_t=setTimeout(function(){compare(ev,ob);},cfg.interval);}}else{$(ob).unbind("mousemove",track);if(ob.hoverIntent_s==1){ob.hoverIntent_t=setTimeout(function(){delay(ev,ob);},cfg.timeout);}}};return this.mouseover(handleHover).mouseout(handleHover);};})(jQuery);
