var root_portal;

$(document).ready(function() {

    root_portal = $('#root_portal').val();

	// input focus
	/*$('input').focus(function() {
		var value=$(this).val();
		$(this).val("");
	});
	$('input').blur(function() {
		if($(this).val()=="") {
			$(this).val(value);
		}
	});
	*/

	// Tabs
    $('.tab-default').tabs();

    if ($("#frmComentario")) {
        $(".form_comentario").validate({
          errorPlacement: function(error, element) { error.insertBefore(element); }
        });
    }

    if ($(".carousel_container").length > 0) {
        if ($(".carousel_container ul li").length > 4) {
            $(".carousel_container").jCarouselLite({
                btnPrev: 'a.btn_anterior_cima',
                btnNext: 'a.btn_proxima_baixo',
                circular: false,
                vertical: true,
                visible: 4,
                scroll: 1,
                speed: 500
            });
        }
    }

/* *******************************************************

			 PROXIMO EVENTOS

*********************************************************/

    if($("#formProxEventos")) {
        $("#formProxEventos .mes-ano").change(function(){
            var mes_ano = $("#formProxEventos .mes-ano").val().split('-');
            var categoria = $("#formProxEventos .categoria").val();
            var mes = mes_ano[0];
            var ano = mes_ano[1];
            $("#proxEventos").htmlLoader("padding-top:20px;");

            $.get($("#formProxEventos").attr('action'), {mes: mes, ano:ano, categoria:categoria}, function(data){
                $('#proxEventos').html(data);
            }, 'html');
        });
    }

/* *******************************************************

			 NEWSLETTER

*********************************************************/

    if($("#frm_news")) {
        $("#frm_news").validate({
          errorPlacement: function(error, element) { error.insertBefore(element); },
          submitHandler: function(form) {
            var email = $('#txtnews').val();
            $('#txtnews').val('');
            $.post( $(form).attr('action'), {email: email}, function(data){
                $('#frm_news .result').html(data);
            }, 'html');
           	return false;
          }
        });
    }

/* *******************************************************

			 BUSCA

*********************************************************/

    if ($("#buscar-ptl").length > 0) {
        $('.paginacao a').live('click',function(e){
            $.stopEvent(e);
            var href = $(this).attr('href');
            var tab = $(this).closest('.ui-tabs-panel');
            var tipo = tab.attr('id').replace('busc-','');
            tab.htmlLoader("padding-top:40px;");
            $.get(href, {tipo:tipo} , function(data){
                tab.html(data);
            } ,'html')
        });
    }

/* *******************************************************

			GB > PERFIL

*********************************************************/

	if ($("#gb-perfil").length > 0) {
		
		$('#pop-perfil-completo').dialog({
			minWidth: 700,
			autoOpen: false,
			modal: true
		});
		
		$('#pop-medalhas').dialog({
			minWidth: 990,
			minHeight: 850,
			autoOpen: false,
			modal: true,
			dialogOpts: true,
			dialogClass: "a-medalhas",
			draggable: false,
			resizable: false,
			position: ['center',10]
		});

		$('#openpop').click(function(e) {
		    $.stopEvent(e);
			$('#pop-medalhas').dialog('open');
		});
		
		$('#openpop-perfil').click(function(e){
		    $.stopEvent(e);
			$('#pop-perfil-completo').dialog('open');
		});
		
	}
	
	
/* *******************************************************

			GB > PROJETOS

*********************************************************/
	
	if ($("#gb-projetos").length > 0) {
	
		$('.pop-proj').dialog({
			minWidth: 700,
			autoOpen: false,
			modal: true
		});
		
		$('.pop-proj2').dialog({
			minWidth: 718,
			height: 600,
			autoOpen: false,
			modal: true
		});
		
		$('#openpop1').click(function(e){
		    $.stopEvent(e);
			$('#pop-proj1').dialog('open');
		});
		$('#openpop2').click(function(e){
		    $.stopEvent(e);
			$('#pop-proj2').dialog('open');
		});
	}
	

/* *******************************************************

			MGB > PÁGINA FIQUE POR DENTRO

*********************************************************/

    if ($('#mgb-fpd').length > 0) {

		function fctShowDesc(el)
		{
			var descricao = $(el).find('input').val();
			$('#cltDesc').html(descricao);
		}

		var object = $('#lst-fotos li').eq(0);
		fctShowDesc(object);

		$('#lst-fotos li a').click(function(){
			$('#lst-fotos li').removeClass('sel');
			$(this).addClass('sel');
			fctShowDesc(this);
		});

	}


/* *******************************************************

			MGB > PÁGINA HOME

*********************************************************/

    if ($('#mgb-home').length > 0) {
	    $('#slider1').anythingSlider({
		    width 		: 671,
		    height		: 300,
		    autoPlay 	: true,
		    easing: 	'easeInOutExpo',
		    auto : 		true
	    });
	    
	    if( $('.parceiros li').length > 5 )
	    {
    	    $('.parceiros').jCarouselLite({
                auto: 1000,
                circular: true,
                vertical: false,
                visible: 5,
                scroll: 1,
                speed: 1500
            });
	    }
	}

/* *******************************************************

			POPUP HISTÓRIA, MISSÃO

*********************************************************/

	if ($("#popHistoria").length > 0) {

		$('#popHistoria').dialog({
			minWidth: 736,
			autoOpen: false,
			modal: true
		});

		$('#openHistoria').click(function() {
			$('#popHistoria').dialog('open');
			return false;
		});
	}

/* *******************************************************

			MGB > PÁGINA A METODOLOGIA

*********************************************************/

	if ($("#mgb-amgb").length > 0) {
        //** Niveis
		$('#niveis-mgb li a').mouseover(function(){
			$('#niveis-mgb li').removeClass('on');
			$(this).parent().addClass('on');
		});

		//** Materiais
		$('#materiais-mgb li').mouseover(function(){
			$('#materiais-mgb li').removeClass('on');
			$(this).addClass('on');
		});

	    $('#niveis-mgb li a, #materiais-mgb li a').click(function(e){
            $.stopEvent(e);
		})

		//** Popup Todas as campanhas
		$('#popCampanha').dialog({
			minWidth: 802,
			autoOpen: false,
			modal: true
		});

		$('#openCampanha').click(function() {
			$('#popCampanha').dialog('open');
			return false;
		});

		$('#popCampanha #cboAno').change(function(e){
            $('#list_campanha').htmlLoader("padding-top:40px;");
            var href = $(this).closest('form').attr('action') + $(this).val() + "/";
            $.post(href, null, function(data) {
                $("#list_campanha").html(data);
            } , 'html');
		});
	}


/* *******************************************************

			GB > PÁGINA PRODUTOS

*********************************************************/

    if ($("#gb-produtos").length > 0) {

		$('.pop-prod').dialog({
			minWidth: 400,
			autoOpen: false,
			modal: true
		});

		$('#openpop1').click(function() {
			$('#pop-prod1').dialog('open');
			return false;
		});
		$('#openpop2').click(function() {
			$('#pop-prod2').dialog('open');
			return false;
		});
		$('#openpop3').click(function() {
			$('#pop-prod3').dialog('open');
			return false;
		});
		$('#openpop4').click(function() {
			$('#pop-prod4').dialog('open');
			return false;
		});
		$('#openpop5').click(function() {
			$('#pop-prod5').dialog('open');
			return false;
		});
	}

/* *******************************************************

			PALESTRA > PÁGINA CLIENTES

*********************************************************/

	if ($("#pl-clientes").length > 0) {

	    function fctShowCliente(el)
	    {
		    var descricao = $(el).find('input').eq(0).val();
		    var autor = $(el).find('input').eq(1).val();
		    $('#cltDesc').html(descricao);
		    $('#cltAutor').html(autor);
	    }

	    var object = $('#listaClientes li a').eq(0);
		$(object).parent().addClass('sel');
		fctShowCliente(object);

		$('#listaClientes li a').mouseover(function(){
			$('#listaClientes li').removeClass('sel');
			$(this).parent().addClass('sel');
			fctShowCliente(this);
		});

		$('.proximo').click(function(e){
		    $.stopEvent(e);
			var objectAux =  $('.sel');
			var index = $('#listaClientes li').index(objectAux);
			var total = $('#listaClientes li').length;

			if (index < (total-1)) {
				var object = $('.sel').next().children('a');
				$('#listaClientes li').removeClass('sel');
				$(object).parent().addClass('sel');
				fctShowCliente(object);
			}
		});

		$('.anterior').click(function(e){
		    $.stopEvent(e);
			var objectAux =  $('.sel');
			var index = $('#listaClientes li').index(objectAux);
			if (index > 0) {
				var object = $('.sel').prev().children('a');
				$('#listaClientes li').removeClass('sel');
				$(object).parent().addClass('sel');
				fctShowCliente(object);
			}
		});
	}

/* *******************************************************

			GB > PÁGINA EVENTOS

*********************************************************/

    if ($("#gb-eventos, #fpd-eventos").length > 0) {
        $("#tabs.eventos").tabs({
            select: function(event, ui) {
                var thisTabId = ui.tab.href.substring(ui.tab.href.lastIndexOf('#'));
                getEventosFromTab(thisTabId);
            }
        });

        $("#evento_ano").bind('change', function(e) {
            clearEventosTabs();
        });

        $(".ev_item h3 a").live("click", function(e){
			e.stopPropagation();

			$(this).closest(".ev_item").slideToggle(400, function(){
				$(this).find(".ev_fechar").show();
				$(this).find("h3.titulo").hide();
				$(this).find(".ev_integra").show();
				$(this).slideToggle();
			});

		});

		$(".ev_fechar").live("click", function(e){
			e.stopPropagation();

			$(this).closest(".ev_item").slideToggle(400, function(){
				$(this).find(".ev_fechar").hide();
				$(this).find("h3.titulo").show();
				$(this).find(".ev_integra").hide();
				$(this).slideToggle();
			});
		})
    }

/* *******************************************************

			GB > PÁGINA DICAS

*********************************************************/

    if ($("#gb-dicas").length > 0) {
        $("#tabs").tabs({
            select: function(event, ui) {
                var thisTabId = ui.tab.href.substring(ui.tab.href.lastIndexOf('#'));
                getDicasFromTab(thisTabId, '');
            }
        });

        $('#dicas_filter').submit(function(e){
            $.stopEvent(e);
            $('#busca_dica').val($('#txtbuscadicas').val());
            clearDicasTabs();
        });

        $('.maisdicas a').live('click', function(e){
            $.stopEvent(e);
            getDica(this.href);
        });

        $('.paginacao a').live('click', function(e){
            $.stopEvent(e);
            var href = this.href.substring(this.href.lastIndexOf('?'));;

            $(this).closest('.list_dicas').html('');
            var tab = getTabSelected();
	        getDicasFromTab(tab, href);
        });
    }

    if ($(".other_captcha").length > 0) {
        $(".other_captcha").live('click', function(e){
            $.stopEvent(e);
            $('.input_captcha').htmlLoader("padding-top:40px;");

            $.get(this.href, null, function(data){
                $(".input_captcha").html(data);
            },'html');
        })
    }

/* *******************************************************

			PALESTRA > PÁGINA ATITUDE

*********************************************************/

    if( $('#pl-home').length > 0 ){
        $('.empresas-motivadas').jCarouselLite({
            auto: 4000,
            circular: true,
            vertical: false,
            visible: 3,
            scroll: 3,
            speed: 1500
        });
    }

/* *******************************************************

			PALESTRA > PÁGINA ATITUDE

*********************************************************/

    if ( $("#pl-atitude").length > 0 ) {
        $("#depoimento .paginacao a").live('click', function(e){
            $.stopEvent(e);
            $.get(this.href, null, function(data){
                $("#depoimento").html(data);
            },'html');
        })
		
		
		$('#pop-base').dialog({
			minWidth: 700,
			autoOpen: false,
			modal: true
		});
		$('#openpop-base').click(function(){
			$('#pop-base').dialog('open');
			return false;
		});
		
    }

    if ($(".imagem_ampliada").length > 0) {
        $(".imagem_ampliada ul li a").live('click', function(e) {
            $.stopEvent(e);
            var new_src = $(this).attr("href");
            $(".imagem_ampliada .ampliada").attr("src", new_src);
        });
    }

/* *******************************************************

			MGB > PÁGINA BENEFICIOS, PÁGINA SEJA-ALUNO

*********************************************************/

    if($("#mgb-benficios, #mgb-seja-aluno").length > 0){
        $('#mgb-benficios .slider, #mgb-seja-aluno .slider').anythingSlider({
		    width : 650,
		    height: 150,
		    autoPlay            : false,
		    easing: 'easeInOutExpo',
		    auto : false
	    });
    }

/* *******************************************************

			CONTATO

*********************************************************/

    if ($("#frmFaleConosco").length > 0) {
        $("#frmFaleConosco select option[value='']").html('Selecione');
        $("#frmFaleConosco").validate({
          errorPlacement: function(error, element) { error.insertBefore(element); }
        });
    }
    
/* *******************************************************

			BUSCA DE IMPRENSAS E NOTICIAS

*********************************************************/

    $('#form_noticias select, #form_imprensa select').change(function(e){
        $(this).closest('form').submit();
    });
    

/* *******************************************************

			PISCINA

*********************************************************/

    if ($(".frm-search-piscina").length > 0){

		objEstados = $(".search-estado");
        objEstados.change(function(){
            objEstado = $(this);
            objCidade = $(this).next(".search-cidade");

            var objEstado_id = objEstado.val();

            objCidade.attr("disabled", true);
            objCidade.empty();
            objCidade.append('<option value="">Carregando ... </option>');

            if(objEstado_id)
            {
                var url = root_portal + 'ajax/piscina/cidades/' + objEstado_id + '/';
                $.ajax({
                    type: "POST",
                    url: url,
                    dataType: "json",
                    success: function(data){
                        fillSelectOptions(objCidade, data, 'Selecione o estado')
                    }
                });
            }
            else
            {
                fillSelectOptions(objCidade, '', 'Selecione o estado')
            }
        });
    }

    if ($("#mgb-pisc-cred").length > 0){
        
        $('#piscinas').jCarouselLite({
            btnPrev: 'a.anterior',
            btnNext: 'a.proximo',
            circular: false,
            vertical: false,
            visible: 4,
            scroll: 4,
            speed: 500,
            ulClass: 'nav',
            liClass: 'nav'
        });
        
        $('#piscinas li a').click(function(e){
            $.stopEvent(e);
            selecionaPiscina($(this).closest('.item'));
        });
        inicializa(14);
        
        $('.popup_content .images .ant').live('click', function(e){
            $.stopEvent(e);
            
            var parent = $(this).closest('.images');
            
            var obj = parent.find('li.selected')
            var obj_prev = obj.prev();

            if(obj_prev.length == 0)
                obj_prev = parent.find('li')[parent.find('li').length - 1];

            $(obj).fadeOut(1000).removeClass('selected');
            $(obj_prev).fadeIn(1000).addClass('selected');
        })
        
        $('.popup_content .images .prox').live('click', function(e){
            $.stopEvent(e);
            
            var parent = $(this).closest('.images');
            
            var obj = parent.find('li.selected')
            var obj_next = obj.next();

            if(obj_next.length == 0)
                obj_next = parent.find('li')[0];

            $(obj).fadeOut(1000).removeClass('selected');
            $(obj_next).fadeIn(1000).addClass('selected');
        })
    }

});

var selecionaPiscina = function(obj){
    $('#piscinas li a').removeClass('sel');
    obj.find('a.address').addClass('sel');
    
    var markerpos = obj.find('.markerpos').val();
    var marker = markers[markerpos];
    
    var info = obj.find('.info').html();
    var fotos = obj.find('.fotos').html();
    $('#mgb-pisc-cred .popup-maps .info').html(info);
    $('#mgb-pisc-cred .popup-maps .fotos').html(fotos);
    
    if(infowindowopen)
        infowindowopen.close();
    
    setMapPosition(marker.getPosition(), null);
    infowindows[markerpos].open(mapaobj, marker);
    infowindowopen = infowindows[markerpos];
}

function getTabSelected()
{
    var tab = $("#tabs .ui-tabs-selected a").attr('href')
    return tab.substring(tab.lastIndexOf('#'));
}

function getDica(href)
{
    var tab = getTabSelected();
    $(tab + " .integra").htmlLoader("padding-top:25px;");
    $.post(href, null, function(data) {
	    $(tab + " .integra").html(data);
	} , 'html');
}

function clearDicasTabs()
{
	$("#tabs .ui-tabs-panel .list_dicas").html('');
	var tab = getTabSelected();
	getDicasFromTab(tab, '');
}

function getDicasFromTab(tabId, options)
{
    tabId = tabId.toLowerCase();
	if($(tabId + " .list_dicas").html() == "")
	{
		$(tabId + " .list_dicas").htmlLoader("padding-top:65px;");
		var categoria = tabId.replace("#","");
		var query = $('#busca_dica').val();
		if(!query.isEmpty()) query = query + "/";
		var href = $('#dicas_filter').attr('action') + categoria + "/" + query + options;

		$.post(href, null, function(data) {
			$(tabId + " .list_dicas").html(data);
		} , 'html');
	}
}

function clearEventosTabs()
{
	$("#tabs .ui-tabs-panel").html('');
	var tab = getTabSelected();
	getEventosFromTab(tab);
}


function getEventosFromTab(tabId)
{
    tabId = tabId.toLowerCase();
	if($(tabId).html() == "")
	{
		$(tabId).htmlLoader("padding-top:65px;");

		var ano = $("#evento_ano").val();
		var mes = tabId.replace("#","");

		var href = $('#eventos_filter').attr('action') + ano + '/' + mes;

		$.post(href, null, function(data) {
			$(tabId).html(data);
		} , 'html');
	}
}

var fillSelectOptions =
        function(obj, data, msg)
        {
            obj.attr("disabled", true);
            obj.empty();

            if(data != "")
            {
                obj.attr("disabled", false);
                var objOption = '<option value="">Selecione</option>';
                obj.append(objOption);
                jQuery.each(data, function(i, val) {
                    var selecionado = '';
                    if(val.fields.selected){
                        selecionado = 'selected="selected"';
                    }
                    var objOption = '<option value="'+val.value+'" '+selecionado+'>'+val.fields.nome+'</option>';
                    obj.append(objOption);
                });
            }
            else
            {
                var objOption = '<option value="">'+msg+'</option>';
                obj.append(objOption);
            }
        };


