/* **********************************************************************************
*
* @Resumo: Documento de DHTML - Sumare
* @Autor: Victor Oreliana F. Faria
* @Agencia: Made in Web - www.madeinweb.com.br
* @Site: www.sumare.edu.br
* @Criacao: 28/07/2011
* @Ultima Atualizacao: 13/02/2011
*
*************************************************************************************/

/*************************************************************************************
****************    ESTE ARQUIVO CONTEM FUNCIONALIDADES GLOBAIS E DA HOME    *********
**************************************************************************************/

// VARIAVEIS GLOBAIS
var
	cssPrincipalSelected	= {'color':'#0085b6 !important'},
	cssNavLaretal			= {'background-image':'url(/imagens/bg_itemList.jpg)','background-position':'left center','background-repeat':'no-repeat','padding':'2px 20px','color':'#fff'},
	cssContatoSelected		= {'background-color':'#0085b6'},
	cssSelectedHotLI		= {'background-image':'url(/imagens/bg_navBonus.jpg)', 'background-repeat':'repeat-x', 'background-position':'top'},
	cssSelectedHotA			= {'background-image':'url(/imagens/bg_navBonusDetalhe.jpg)', 'background-repeat':'no-repeat', 'background-position':'center top', 'color':'#fff'},
	cssTextInput			= {'color':'#848484'},
	cssTextInputActive		= {'color':'#0085b6'},
	aMeses 					= ['Janeiro','Fevereiro','Março','Abril','Maio','Junho','Julho','Agosto','Setembro','Outubro','Novembro','Dezembro'],
	aDiasSemana 			= ['Domingo','Segunda','Terça','Quarta','Quinta','Sexta','Sábado'],
	erEmail					= /^([0-9a-zA-Z]+([_.-]?[0-9a-zA-Z]+)*@[0-9a-zA-Z]+[0-9,a-z,A-Z,.,-]*(.){1}[a-zA-Z]{2,4})+$/;


// [END] VARIAVEIS GLOBAIS

/**
 * Funcao responsavel pelo efeito Accordion do menu expansivo (#menuExpansivo)
 */
$.fn.alternarExpansivo = function()
{
	var 
	$e = $(this),
	sFechar = '- fechar menu',
	sAbrir = '+ abrir menu';

	return $e.live('click',function(){

				$('#menuExpansivo').slideToggle();
				$e.text() == sFechar ? $e.text(sAbrir) : $e.text(sFechar);
			});
}
// [END] alternarExpansivo()

/**
 * Funcao responsavel pela exibicao dos videos do youtube em uma janela modal
 * Parametros:
 *	@options [Fanybox Object]
 */
$.fn.youtubebox = function(options){
	$(this).click(function(){
		var settings = {
				'transitionIn'	:	'elastic',
				'transitionOut'	:	'elastic',
				'speedIn'		:	600, 
				'speedOut'		:	200, 
				'padding'		:	0,
				'autoScale'		: 	false,
				'title'			: 	this.title,
				'width'			: 	680,
				'height'		: 	495,
				'href'			: 	this.href.replace(new RegExp("watch\\?v=", "i"), 'v/'),
				'type'			: 	'swf',
				'swf'			: 	{'wmode':'transparent','allowfullscreen':'true'},
				'centerOnScroll': 	true
			}
		$.extend(settings,options);
		$.fancybox(settings);	
		return false;
	});	
}
// [END] youtubebox()

/**
 * Corrige os erros de escape de aspas duplas em uma String que sera um objeto JSON. Escapa os futuros valores do Objeto
 * Parametros:
 *	@str [string]
 */
function clearJson(str)
{
	var cleaned = '';
		
	str = $.trim(str.replace(/\n/g, '').replace(/\t/g, ''));
	
	for(i=0;i<=str.length;i++)
	{
		if	((str.charAt(i) == '"')	 && 
			(str.charAt(i-1) != '{') && 
			(str.charAt(i+1) != ',') && 
			(str.charAt(i-1) != ',') && 
			(str.charAt(i+1) != ':') && 
			(str.charAt(i-1) != ':') && 
			(str.charAt(i+1) != '}'))
		{
			cleaned += '\\"';
		}
		else
		{
			cleaned += str.charAt(i);
		}
	}
	return cleaned;
}
// [END] clearJson()

/**
 * Monta listas de links do menu expansivo
 */	
function montaMenuExpasivo()
{
	var 
	aSecao =  $.makeArray($('#menuPrincipal > li')), 
	$menuExpansivo = $('#itensExpansivo'),
	ul = '';
	
	aSecao.shift(); //TIRA HOME
	
	$.each(aSecao,function(i,e){
		$.ajax({
			url:'/ajax/Secao-Json.asp?IdSecao='+$('a',e).attr('id').split('expansivo')[1]
			,dataType:'JSON'
			,async : false
			,complete:function(oJson)
			{
					
				var jsonComplete = $.parseJSON(clearJson(oJson.responseText));
										
				ul = '<ul class="itemSite"><li><h1>'+ jsonComplete.items[0].getFatherName +'</h1></li>';

				for(obj in jsonComplete.items)
				{
					 ul += '<li>'+ jsonComplete.items[obj].getTitle +'</li>';
				}
				
				ul += '</ul>';
				 
				$menuExpansivo.html( $menuExpansivo.html() + ul ); 
				$menuExpansivo.find('ul').eq(  $('#menuPrincipal > li').size() -2  ).css('border','none');
			}
		});
	});	
}
// [END] montaMenuExpasivo()

/**
 * Recebe numero de um mes e retorna o nome dele por extenso
 * Parametros:
 *	@n [int]
 */	
function whichMonth(n)
{
	return aMeses[parseFloat(n)-1];
}
//[END] whichMonth()

/**
 * Recebe numero de um dia da semana e retorna o nome dele por extenso
 * Parametros:
 *	@aText [string]
 */	
function getTheDay(aText)
{
	//console.log(aText);
	return aDiasSemana[new Date(eval('"'+aText+'"')).getDay()];
}
// [END] getTheDay()

/**
 * Converte <#getPulishDate(month)#> das noticias da home no nome do mes retornado pela funcao do HP(formato numerico)
 */	
function convertNoticiasMonth()
{
	$.each($('.textNoticiasHome h4 > mes > span'),function(){
		
		$(this).text( whichMonth( $(this).text() ).toUpperCase() );
	});
}
//[END] convertNoticiasMonth()

/**
 * Função responsavel por indicar o dia da semana na data das noticias da home
 */	
function getWeekDayHome(){
	$.each($('.diaSemana'),function(){
		var
			dia = $(this).parent().find('.dia').text(),
			mes = $(this).parent().find('.mes').text(),
			ano = $(this).parent().find('.ano').text(),
			data = mes+'/'+dia+'/'+ano;
		;
		
		//console.log(dia);
		try
		{	
			$(this).text(getTheDay(data).substr(0,3));	
		}
		catch(ex)
		{
			//throw console.log(ex);
		}
	});
}
// [END] getWeekDayHome()

/**
 * Funcao responsavel por selecionar o item do menu principal corresponente a pagina corrente
 * Parametros:
 *	@id [string]
 */	
function marcaMenuPrincipal(id)
{
	$('#menuPrincipal > li > a[id="expansivo'+id+'"]').css(cssPrincipalSelected);
}
//[END] convertNoticiasMonth()

/**
 * Funcao responsavel por verificar se uma string e nula
 * Parametros:
 *	@str [string]
 */
function isNullOrEmpty(str)
{
	return ($.trim(str) == null || $.trim(str) == '');
}
//[END] isNullOrEmpty()

/**
 * Recoloca valor padrao do input nele mesmo
 */	
function texted()
{
	var $e = $(this);

	if(isNullOrEmpty( $e.attr('value') ))
	{
		 $e.attr('value', $e.attr('defaultValue'));
		 $e.css(cssTextInput);
	}
}
//[END] texted()

/**
 * Limpa input quando ele tem seu valor padrao. Usado em inputs que possuem label na propriedade Value
 */	
function clearInput()
{
	var $e = $(this);

	if($e.attr('value') == $e.attr('defaultValue'))
	{
		 $e.attr('value','');
		 $e.css(cssTextInputActive);
	}		
}
//[END] texted()

/**
 * Funcao responsavel por aumentar e diminuir tamanho das fontes para usabilidade
 * Parametros:
 *	@s [string]
 *	@mySettings [object]
 */
function resizeFont(s,mySettings)
{
	var //PUBLIC
		settings = {'fontMax': 18, 'fontMin': 12,'increment': 1,'element':$('.resizeable p, .resizeable td, .resizeable li ')};
	
	$.extend(settings,mySettings);
	
	var //PRIVATE 
		$e = settings.element,		
		fontSize = parseInt($e.css('font-size'));
	
	if(s=='+' && fontSize < settings.fontMax)
	{
		$e.css('font-size',(fontSize+settings.increment)+'px');
	}
	else if(s=='-' && fontSize > settings.fontMin)
	{
		$e.css('font-size',(fontSize-settings.increment)+'px');
	}
	
	return false;
}
//[END] resizeFont()

/** 
* Retorna a extensão de um arquivo
* Parametros:
*	@str [string]
*/
function getExt(str)
{
	return str.substr(str.lastIndexOf('.'),str.length); 	
}
// [END] getExt()

/** 
* Retorna o nome de um de um arquivo
* Parametros:
*	@str [string]
*/
function getB4Ext(str)
{
	return str.substr(0,str.lastIndexOf('.'));
}
// [END] getB4Ext()

/** 
* Funcao responsavel pela validacao de formularios do Site. 
* Envia dados do form serializados via ajax. Method e Action definidos no proprio form.
*/
function enviar()
{
	
	var $e = $(this), envie = true;
	
	$e.append('<input type="reset" style="display:none;" id="reset" />');
		
	$.each($e.find('input.requerido'),function(i,e){
				
		if( isNullOrEmpty(e.value) )
		{
			$(e).parent().attr('class','bigInvalido');
			envie = false;
		}
		else
		{
			$(e).parent().attr('class','bigValido');
		}
	});
	
	$.each($e.find('textarea.requerido'),function(i,e){
		
		if( isNullOrEmpty(e.value) )
		{
			$(e).parent().attr('class','textAreaInvalido');
			envie = false;
		}
		else
		{
			$(e).parent().attr('class','textAreaValido');
		}
	});
			
	$.each($e.find('.email'),function(i,e){
				
		if( erEmail.exec(e.value) == null )
		{
			$(e).parent().attr('class', 'bigInvalido');
			envie = false;
		}
		else
		{
			$(e).parent().attr('class','bigValido');
		}
	});
				
	$.each($e.find('select'),function(i,e){
				
		if( e.value == '[selecione]' )
		{
			$(e).parent().attr('class', 'comboInvalido');
			envie = false;
		}
		else
		{
			$(e).parent().attr('class','comboValido');
		}
	});
		
	$.each($e.find('input.medrequerido'),function(i,e){
				
		if( isNullOrEmpty(e.value) )
		{
			$(e).parent().attr('class','medInvalido');
			envie = false;
		}
		else
		{
			$(e).parent().attr('class','medValido');
		}
	});
		
	$.each($e.find('input.peqrequerido'),function(i,e){
				
		if( isNullOrEmpty(e.value) )
		{
			$(e).parent().attr('class','peqInvalido');
			envie = false;
		}
		else
		{
			$(e).parent().attr('class','peqValido');
		}
	});

		
	if(envie)
	{		
		$.ajax({
			url			:	$e.attr('action'),
			type		:	$e.attr('method'),
			datatype	:	'html',
			data		:	$e.serialize(),
			success		: 	function(data)
							{
								$('#sucesso').text(data);
								$('#reset').click();
								$('.bigValido').removeClass('bigValido').addClass('big');
								$('.medValido').removeClass('medValido').addClass('med');
								$('.peqValido').removeClass('peqValido').addClass('peq');
								$('.comboValido').removeClass('comboValido').addClass('combo');
								$('.textAreaValido').removeClass('textAreaValido').addClass('textArea');
								
							},
			error		:	function(data)
							{
								$('#sucesso').text(data);	
							}
		});		
		$(this).find('.avisoErro').hide();
		
	}
	else
	{
		$(this).find('.avisoErro').show();
	}		
	return false;
}
// [END] enviar()

/** 
* Pega o valor de uma varíavel na URL
*/
function getParameterByName(name)
{
  name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
  
  var 
  	regexS = "[\\?&]" + name + "=([^&#]*)",
  	regex = new RegExp(regexS),
  	results = regex.exec(window.location.href);

	if(results == null)
	{  
		return "";
	}
	else
	{
		return decodeURIComponent(results[1].replace(/\+/g, " "));
	}
}
// [END] getParameterByName()


/** 
* Altera aba selecionada nas paginas que contem login do NES
*/
function toggleClassNES(selector,classe,$e)
{
	if(!$e) $e = $(this);
	 
	$(selector).removeClass(classe);
	$e.addClass(classe);
	
	var $tipo =  $('input[name="tipo"]');
	
	$tipo.attr('value') == '1' ? $tipo.attr('value','2') : $tipo.attr('value','1');
	
}
// [END] toggleClassNES()

/** 
* Substitui caracteres de @text com acento por seu correnspondente sem acento
* Parametros:
*	@text [string]
*/
function removeAcento(text)
{
	text = text.replace(new RegExp('[ÁÀÂÃ]','gi'), 'A');
	text = text.replace(new RegExp('[ÉÈÊ]','gi'), 'E');
	text = text.replace(new RegExp('[ÍÌÎ]','gi'), 'I');
	text = text.replace(new RegExp('[ÓÒÔÕ]','gi'), 'O');
	text = text.replace(new RegExp('[ÚÙÛ]','gi'), 'U');
	text = text.replace(new RegExp('[Ç]','gi'), 'C');
	text = text.toLowerCase();
	text = text.replace(new RegExp('[^ abcdefghijklmnopqrstuvxzwy0123456789\,\:\-]','gi'), '');

	return text;
}

function avaliacaoCursos()
{
	if($('.avaliacaoCursos').length > 0)
	{
		/*var arrow = '<span class="arrow">aberto</span>';
		$('.avaliacaoCursos .content h3').prepend(arrow);
		
		$('.avaliacaoCursos .content a').click(function()
		{
			var display = $(this).parents('.content').find('.description').css('display');
			if(display == 'none')
			{
				console.log('aberto');
				console.log($(this).parents('.content').find('.description').css('display'));
			}else{
				console.log('fechado');
				console.log($(this).parents('.content').find('.description').css('display'));
			}
		});
		
		$('.avaliacaoCursos .content a').bind({
			click: function()
			{
				alert('hey');	
			}
		});*/
	}
}

(function( $ ){
	$.extend( {
		jTwitter: function( username, numPosts, fnk ) {
			var info = {};
			
			// If no arguments are sent or only username is set
			if( username == 'undefined' || numPosts == 'undefined' ) {
				return;
			} else if( $.isFunction( numPosts ) ) {
				// If only username and callback function is set
				fnk = numPosts;
				numPosts = 5;
			}
			
			var url = "http://twitter.com/status/user_timeline/"
				+ username + ".json?count="+numPosts+"&callback=?";

			$.getJSON( url, function( data ){
				if( $.isFunction( fnk ) ) {
					fnk.call( this, data );
				}
			});
		}
	});
})( jQuery );

$(function(){
	
	//ELEMENTOS DE FORMULARIO COM VALOR PADRAO [ INPUT | TEXTAREA ]
	$('.texted').click(clearInput).blur(texted);
	
	/*$('.fontAjust li').click(function(){
		console.log($(this).find('a'));
		return $(this).find('a').click();
	});*/
		
	//MENU EXPANSIVO
	montaMenuExpasivo();
	$('#toggle').alternarExpansivo();
	
	//NOTICIAS HOME [FORMATACAO]
	getWeekDayHome();
	convertNoticiasMonth();

	//JANELA MODAL PARA VIDEOS DO YOUTUBE
	$('.youtubeBox').youtubebox();
	
	
	//FONT RESIZE PARA TODOS
	$('ul.fontAjust > li').eq('0').find('a').addClass('resizeMenos');
	$('ul.fontAjust > li').eq('1').find('a').addClass('resizeMais');
	$('div.corpoMateria').addClass('resizeable');
	
	//IMPRIMIR PARA TODOS
	$('ul.fontAjust > li').eq('2').find('a').click(function()
	{
		window.print();
	});
	
	//AREA DE CLICK
	$('ul.fontAjust > li').css('cursor', 'pointer').click(function()
	{
		$(this).prev().find('a').click();
	});
	
	//USABILIDADE TAMANHO FONTES
	$('a.resizeMenos').click(function(){
		return resizeFont('-');
	});
	
	$('a.resizeMais').click(function(){ 	
		return resizeFont('+');
	});
	
	//AREA LINKS LISTA CORPO MATERIA
	/*$('div.corpoMateria ul li').css('cursor', 'pointer').click(function()
	{
		window.location = $(this).find('a').attr('href');
	});*/
	$('div.fontAjust ul li').css('cursor', 'pointer').click(function()
	{
		window.location = $(this).find('a').attr('href');
	});
	
	
	//twitters..
	$.jTwitter('sumareoficial', 10, function(data){
        //$('#twitter').empty();
        $.each(data, function(i, post){
		
			if(i < 3)
			{
				var str = post.text;
				var result = str.match(/http\:\/\/([^ ]*)?/gi);
				str = str.replace(result, '<a href="'+result+'" class="tweetLink" target="_blank" style="color:#848484;">'+result+'</a>')
				
				if(i == 0)
					$('#twitter').append(
						 '<span class="tweetNew" style="margin-top:0px;"><p style="padding:20px 0px; border-bottom:1px solid #DCE4E7; border-top:1px solid #DCE4E7;">'+ str +'</p></span><div class="clear"></div><br />'
					);
				else
					$('#twitter').append(
						'<span class="tweetNew" style="margin-top:0px;"><p style="border-bottom:1px solid #DCE4E7; padding-bottom:20px;">'+ str +'</p></span><div class="clear"></div><br />'
					);
			}
        });
    });
	
});
