/*
Name: Javascript Functions
Version: 1.0
Description: BJavascript Functions para o site
Author: Alex Koti
Author URI: http://alexkoti.com
 */


jQuery(document).ready(function($){
	
	
	
	/**
	 * TROCA DE VERSÃO DE VÍDEO
	 * Aplica a mudança de versão de vídeo
	 * Reescreve a tag original modificando apenas as urls de video
	 * 
	 */
	$('.video_version_btn').click(function(){
		// parar todos os players ativados pelo medialement
		$('video').not('.skip_load').each(function() {
			$(this)[0].player.pause();		  
		});
		
		// ativar estilo css
		$(this).addClass('active').siblings().removeClass('active');;
		
		// mudar a posição do strip para o video desejado
		var video_version = $(this).attr('rel');
		var $media_parent = $(this).closest('.video_media');
		var video_version_pos = $media_parent.find('.' + video_version).position();
		
		// ativar o video caso seja 'skip_load'
		$media_parent.find('video.skip_load').mediaelementplayer({
			success: function(player, node) {
				$('#' + node.id + '-mode').html('mode: ' + player.pluginType);
			}
		}).removeClass('skip_load').addClass('loaded');
		
		
		//alert( video_version_pos.left );
		//$media_parent.find('.multi_videos_strip').css('left', '-' + video_version_pos.left);
		$media_parent.find('.multi_videos_strip').animate({left: '-'+video_version_pos.left}, 'fast');

		
		return false;
	});
	
	
	
	/**
	 * VIDEOS EDUCATIVOS HOME - TABS
	 * Box com abas dos vídeos educativos na home.
	 * Carrega todos os vídeos em lista simples, depois monsta a 'pilha' de vídeos. As miniaturas do slider logo abaixo
	 * mudam a ordem de empilhamento para mostrar o box do vídeo escolhido.
	 * 
	 */
	if( $('.video_list_educativos_home').length ){
		$('.video_list_educativos_home ul.video_boxes').addClass('active');
		
		var zindex = 100;
		$('.video_list_educativos_home ul.video_boxes li').each(function(){
			$(this).css('z-index', zindex);
			$(this).attr('rel', zindex);
			zindex--;
		});
		
		$('.video_list_educativos_home .boros_slider_holder .slide a').click(function(){
			//"pausar" video da tab anterior, se estiver tocando - na realidade irá fazer um reload do mediaelement, cortando também a requisição de dados do vídeo antigo :)
			$('.video_list_educativos_home .video_item[rel=100] .video_version a:first').removeClass('active').trigger('click');
			
			//video_box requerido
			$('.video_list_educativos_home ul.video_boxes li').css('z-index', 99);
			$('.video_list_educativos_home ul.video_boxes li').attr('rel', 99);
			var video_target = $(this).attr('rel');
			$('#' + video_target).css('z-index', 100);
			$('#' + video_target).attr('rel', 100);
			return false;
		});
	}
	
	
	
	
	/**
	 * MEDIA ELEMENT JS
	 * Aplicado às tags <video> nativas onload
	 * Precisar rodar depois das tabs da home
	 * 
	 */
	// enfileirar as versões dos videos no holder
	$('.multi_videos_holder').addClass('multi_videos_active');
	$('video').not('.skip_load').mediaelementplayer({
		success: function(player, node) {
			$('#' + node.id + '-mode').html('mode: ' + player.pluginType);
		}
	});
	
	
	
	/**
	 * Esconder links de acessibilidade para navegadores com javascript
	 * 
	 */
	$('.access_nav').hide();
	// adicionar flag de javascript habilitado
	$('html').addClass('js');
	
	
	
	/**
	 * Ativar sliders na home
	 * Acionar plugin boros_slider
	 */
	$('.boros_slider').borosSlider({
		loop: false,
		slideshow: false,
		easing: 'boros',
		offset: 4
	});
	
	
	/**
	 * BOX FLEXÍVEL
	 * Open/Close do box
	 */
	function flex_box( btn, box ){
		
		if( box.holder.height() < box.inner.height() ){
			btn.text('fechar');
			box.obj.addClass('opened');
			box.holder.animate({height: box.inner.height()}, 500);
		}
		else{
			btn.text(box.default_text);
			box.obj.removeClass('opened');
			box.holder.animate({height: box.folded_h}, 500);
		}
	}
	$('.flex_box').each(function(){
		var box 		= new Object;
		box.obj 		= $(this);
		box.holder 		= $(this).find('.flex_box_holder');
		box.inner 		= $(this).find('.flex_box_inner');
		box.folded_h	= $(box.holder).height();
		//box.holder_h 	= $(box.holder).height();
		//box.inner_h 	= $(box.inner).height();
		
		if( box.holder.height() < box.inner.height() ){
			box.obj.addClass('folded');
		}
		// texto padrão
		box.default_text = $(box.obj).find('.flex_box_btn span').text();
		
		$(box.obj).find('.flex_box_btn span').click(function(){
			flex_box( $(this), box );
		});
	});
	
	
	/**
	 * MENU PRINCIPAL SIDEBAR
	 * 
	 * 
	 */
	$('.menu_principal').each(function(){
		$(this).addClass('slide_active');
		
		$(this).find(':not(.active) > ul').hide();
		
		$(this).find('> li').each(function(){
			var indicator = ( $(this).is('.active') ) ? 'control_menu_open' : '';
			$(this).prepend('<span class="control_menu '+indicator+'"></span>');
		});
		
		
		$('.control_menu').click(function(){
			if( $(this).is('.control_menu_open') ){
				$(this).next().next().slideUp();
				$(this).removeClass('control_menu_open');
			}
			else{
				$(this).next().next().slideDown();
				$(this).addClass('control_menu_open');
			}
			return false;
		});
	});
	
	
	
	/**
	 * FAQ
	 * 
	 * 
	 */
	$('.faq dd').hide();
	$('.faq dt').toggle(
		function(){
			$(this).next('dd').slideDown();
			$(this).addClass('active');
		},
		function(){
			$(this).next('dd').slideUp();
			$(this).removeClass('active');
		}
	);
	
	
	
	/**
	 * CADASTRO NEWSLETTER
	 * 
	 */
	var validatenews = {
		init : function() {
			if (this.check()) this.core();
		},
		check : function() {
			return ( _exists('#news')) ? true : false;
		},
		core : function() {
			$('#news').validate({
				rules:{
					email :{
						email 	: true,
						remote 	: '/check-email-news/'
					}
				},
				messages:{
					email :{
						email	: 'E-mail inválido.',
						remote	: jQuery.format('O e-mail {0} já está cadastrado.')
					}
				},
				onkeyup : false,
				submitHandler : function(form) {
					$(form).ajaxSubmit({
						dataType 	: 'json',
						success 	: validatenews.result
					});
				},
				errorPlacement: function(label, element) {
					// label - elemento <label> gerado pelo validator
					// element - input validado
					// pegar o id do elmento e assim desconbrir o <label> como 'for' correspondente
					$(label).insertAfter( element.parent() ).wrap('<p></p>');
				}
			});
		},
		result  : function(data) {
			var status  = data.claro.status;
			var html 	= '<div id="error"><ol>';
			if (status == 0) {
				$.each(data.claro.error, function(i, item) {
					html += '<li>' + item + '</li>\n';
				});
				html += '</ol></div>';
				$('ol.submit').after(html);
			} else {
				$.get('/news_sucesso/', function(data) {
					$('#news-success').fadeOut( function() {
						$(this).html(data).fadeIn('slow');
					});
				});
			}
		}
	};
	var _exists  = function(obj) {
		return ( $(obj).length  > 0 ) ? true : false;
	};
	//iniciar o script de newsletter
	validatenews.init();
	
	
	/**
	 * STYLE SWITCHER
	 * 
	 */
	$('.font_btn').click(function (){
		// pegar a variÃ¡vel do link
		var valor = gup('font_size', $(this).attr('href') );
		if( $(this).is('#font_control_increase') ){
			var mode = 'plus';
		}
		else{
			var mode = 'minus';
		}
		change_font_size(valor, mode);
		
		return false;
	});
	
	function change_font_size(size, mode){
		// tamanho atual do font-size
		var body_size = Number( $('body').css('font-size').replace('px','') );
		var max_size = 24;
		var min_size = 8;
		var new_plus, new_minus, new_size, body_size;
		
		if( mode == 'plus' ){
			if( body_size < max_size ){
				new_size 	= (body_size + 1);
				new_plus 	= (body_size + 2);
				new_minus 	= (body_size - 1);
			}
			else{
				return false;
			}
		}
		else{
			if( body_size > min_size ){
				new_size 	= (body_size - 1);
				new_plus 	= body_size;
				new_minus 	= (body_size - 2);
			}
			else{
				return false;
			}
		}
		
		// alterar o url dos links
		$('#font_control_decrease').attr('href', $('#font_control_decrease').attr('href').split('font_size=')[0] + 'font_size=' + new_minus);
		$('#font_control_increase').attr('href', $('#font_control_increase').attr('href').split('font_size=')[0] + 'font_size=' + new_plus);
		
		// mudar o font-size, atravÃ©s da class do html
		$('body').css('font-size', new_size);
		
		// gravar cookie
		createCookie('font_size', new_size, 365);
	}
});



/**
 * GET URL PARAMETERS
 * 
 * http://www.netlobo.com/url_query_string_javascript.html
 */
function gup( name, url ){
	name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	var regexS = "[\\?&]"+name+"=([^&#]*)";
	var regex = new RegExp( regexS );
	if( url == undefined ) url = window.location.href;
	var results = regex.exec( url );
	if( results == null )
		return "";
	else
		return results[1];
}



/**
 * COOKIE FUNCTIONS
 * 
 * cookie functions http://www.quirksmode.org/js/cookies.html
 */
function createCookie(name,value,days){
	if (days){
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name){
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++){
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name){
	createCookie(name,"",-1);
}
