$(document).ready(function(){

	
	$("object param").each(function(index, value) {
		var $element = $(this);
		if($element.attr('name') == 'FlashVars'){
			
		}
	});
	
	//Vídeos da Home
	jQuery("#list_videos li a").click(function(e){
		
		//Pego os dados do video GRANDE (current) e do elemento que foi clicado (clicked);
		var currentTitle = jQuery('#current-name', '#video-home').val();
			currentCode  = jQuery('#current-code', '#video-home').val();
			clickedCode   = jQuery(this).attr('name'),
			clickedTitle  = jQuery(this).attr('title');
	
		//crio o object para preecher a div $('#video-home');
		var html = [ '<object width="370" height="308" data="http://s.videos.globo.com/p2/player.swf" type="application/x-shockwave-flash">',
		             	'<param value="true" name="allowFullScreen">',
						'<param value="http://s.videos.globo.com/p2/player.swf" name="movie" />',
						'<param value="high" name="quality" />',
						'<param value="midiaId='+ clickedCode +'&autoStart=false&width=370&height=308" name="FlashVars" />',
					  '</object>',
					  '<input type="hidden" value="'+ clickedTitle +'" id="current-name" />',
					  '<input type="hidden" value="'+ clickedCode  +'" id="current-code" />'
		           ]; 		
		
		
		//Substituindo os valores
		//Colocando o video principal no lugar do video que foi clicado.
		jQuery(this).attr('title', currentTitle );
		jQuery(this).attr('name', currentCode );
		jQuery(this).children('img').attr('src', 'http://img.video.globo.com/GMC/foto/0,,'+ currentCode +',00.jpg').attr('alt', currentTitle);
				
		//Colocando o video clicado no lugar do principal.
		$('#video-home').html( html.join('') );

		return false;
	});
	
	//Esqueci minha senha
	if(jQuery('#a-esqueci-senha').length) {
		jQuery('#a-esqueci-senha').click(function(){
			jQuery(this).toggleClass('ativo');
			jQuery('#form-esqueci-senha').toggleClass('hide');
			return false;
		});
	}	

	//Validação do form de inscrição
	if(jQuery("#inscricao-escola").length > 0){
		jQuery("#inscricao-escola").validationEngine();
		
		jQuery('.limite-7 .checkbox, .limite-7 label').click(function(){
			if( $('.limite-7 .checkbox:checked').length > 7 ) {
				
				//Verifica se está desmarcando.
				if( $(this).is(':checked') ){
					alert('Máximo 7 escolhas');
					return false;
				}else{
					return true;
				}
			}
		});
	}
	
	//Mascara dos inputs
	/*
	if(jQuery('#inscricao-escola').length > 0){
		jQuery("#responsavel_telefone").mask("(99) 9999-9999");
		jQuery("#responsavel_celular").mask("(99) 9999-9999");
		jQuery("#responsavel_cpf").mask("999.999.999-99");
		jQuery("#escola_telefone").mask("(99) 9999-9999");
		jQuery("#escola_cep").mask("99999-999");
	}
	*/
	
	//Fecha feedback de sucess do envio de form
	fechar($('.success .fechar'));
	
	//Carrega twits
	if(jQuery("#twitter").length > 0){
		jQuery("#twitter").getTwitter({
			userName: "intercolegial",
			numTweets: 1,
			loaderText: "Carregando...",
			slideIn: false,
			slideDuration: 750,
			showHeading: false,
			showProfileLink: false,
			showTimestamp: false
		});
	}	
		
	//Posiciona Legenda
	if(jQuery('#legenda-fichas').length) {	
		
		var $el = jQuery('#legenda-fichas'),
			$footer = jQuery('.footer'),
			maxPos = $el.offset().top - 20 /* + 20px de respiro */,
			elHeight = $el.height(),
			footerHeight = $footer.height() + parseInt($footer.css('margin-bottom')) + 20,
			footerOffset = $footer.offset().top,
			maxBottom = jQuery(document).height() - elHeight - footerHeight - 20 /* + 20px do padding do body */;
			
		jQuery(window).scroll(function () {
				
			var topPos = jQuery(window).scrollTop(),
				windowHeight = jQuery(window).height();
			
			if(windowHeight > elHeight) {
			
				if(topPos > maxPos) {
					$el.css({
						position: 'fixed',
						top: 20,
						bottom: 'auto'
					});
				}
				else if(topPos < maxPos) {
					$el.css({
						position: 'static'
					});
				}
				
				if(topPos > maxBottom) {
					$el.css({
						/* position: 'absolute', */
						top: 'auto',
						bottom: footerHeight
					});
				}
			} 
			else {
				$el.css({
					position: 'static'
				});
			}
			
		});
	}
	
	//limpa os valores default dos campos 
	//apenas pra nome da escola 
	jQuery("#escola_razao_social").each(function() {
		if ($(this).parent().hasClass('clean-default')){
			var default_value = this.value;
			$(this).focus(function() {
				if(this.value == default_value) {
					this.value = '';
				}
			});
			$(this).blur(function() {
				if(this.value == '') {
					this.value = default_value;
				}
			});
		}
    });
	
	//Desabilita menu
	jQuery('li.disable a').attr({
		href : '#',
		title : 'Área desabilitada'
	});
	
	//Tira marem da última noticia da coluna
	jQuery('.noticias-categoria dl:odd').css('margin-right','0');
	
	//Link Topo
	jQuery('#topo').bind('click', function(){
    	scrollTo('html,body');
    	return false;
	});
	
	//Carrega Lightbox (prettyPhoto)
	if($("#fotos-videos a[rel^='prettyPhoto']").length > 0) {
		$("#fotos-videos a[rel^='prettyPhoto']").prettyPhoto({theme:'facebook'});
	}
	
	//Carrega Lightbox (prettyPhoto)
	if($("img", ".entry").length > 0) {
		$("img", ".entry").addClass('edges imask0').parent().prettyPhoto({theme:'facebook'});
	}
	
	//feature de adicionar/remover pontuacao extra no admin.
	bindRemoveMedalha();
	jQuery('#medalha-table a.add-medalha-extra').unbind().bind('click', function(e){
		var target = e.target; 
		var $target = jQuery(target);
		
		$append = jQuery('#medalha-clone').clone();
		
		$clone = $append.children().children();
		//pega o <select>
		jQuery.each($clone, function(index, value) {
			if (0===index){
				$clone = $(this);
			}
		});
		
		//monta o name para model EscolasEsportesModalidades
		var eemId = $target.parent().parent().parent().attr('id');
		var name = eemId.substring(4);
		$clone.attr('name', 'extra[' + eemId.substring(4) + '][medalha_extra_tipo_id][]');
		$clone.next().attr('name', 'extra[' + eemId.substring(4) + '][medalha_extra_valor][]');
		
		$target.after($append.html());
		
		//remove o node
		bindRemoveMedalha();
		
		return false;
	});
	
	//tooltip de cada dia do calendario
	if(jQuery('#tooltip-parent td.vermelho').length > 0) {
		jQuery('#tooltip-parent td.vermelho').tooltip({ 
		    bodyHandler: function() { 
		        return $($(this).children(":first").html()); 
		    }, 
		    showURL: false,
		    track: true,
		    top: 10,
		    left: -55
		});
	}
	
	//binda o link de evento na div geral pai eventos
	var $eventLink = jQuery('dl a', '#proximos-eventos');
	$eventLink.parent().parent().parent().unbind().bind('click', function(){
		window.location = $eventLink.attr('href');
	});
	
});

function verDetalhes(com,grid){
	if (jQuery('.trSelected').length > 0) {
        var itemSelected = jQuery('.trSelected').attr('id').substr(3);
        var url = '/admin/escola/detalhe/id/' + itemSelected;
        window.location = url;
    }
}

function scrollTo(selector, callback){
    var targetOffset = jQuery(selector).offset().top;
    if (typeof callback == 'function') {
        jQuery('html,body').animate({
            scrollTop: targetOffset
        }, 1000, callback(jQuery(selector)));
    }
    else {
        jQuery('html,body').animate({
            scrollTop: targetOffset
        }, 1000);
    }
}

function bindRemoveMedalha()
{
	jQuery('#medalha-table a.remove-medalha-extra').unbind().bind('click', function(e){
		var answer = confirm("Você tem certeza que deseja remover?");
		if (answer){
			var target = e.target;
			var $target = jQuery(target);
			$target.parent().remove();
		}
		
		return false;
	});
}

function fechar(e){
	e.click(function(){
		$(this).parent().fadeOut();
	});
}
