/*************** accordiom simples ***************/

$(document).ready(function() {

/*************** div com scroll ***************/
	$('.scroll-pane-arrows').jScrollPane({
				showArrows: true,
				horizontalGutter: 10
	});
	
	
	//ACCORDION BUTTON ACTION (ON CLICK DO THE FOLLOWING)
	$('.accordionButton').click(function() {

		//REMOVE THE ON CLASS FROM ALL BUTTONS
		$('.accordionButton').removeClass('on');
		  
		//NO MATTER WHAT WE CLOSE ALL OPEN SLIDES
	 	$('.accordionContent').slideUp('normal');
   
		//IF THE NEXT SLIDE WASN'T OPEN THEN OPEN IT
		if($(this).next().is(':hidden') == true) {
			
			//ADD THE ON CLASS TO THE BUTTON
			$(this).addClass('on');
			  
			//OPEN THE SLIDE
			$(this).next().slideDown('normal');
		 } 
		  
	 });
	  
	
	/*** REMOVE IF MOUSEOVER IS NOT REQUIRED ***/
	
	//ADDS THE .OVER CLASS FROM THE STYLESHEET ON MOUSEOVER 
	$('.accordionButton').mouseover(function() {
		$(this).addClass('over');
		
	//ON MOUSEOUT REMOVE THE OVER CLASS
	}).mouseout(function() {
		$(this).removeClass('over');										
	});
	
	/*** END REMOVE IF MOUSEOVER IS NOT REQUIRED ***/
	
	
	/********************************************************************************************************************
	CLOSES ALL S ON PAGE LOAD
	********************************************************************************************************************/	
	$('.accordionContent').hide();

});
/******** Inicia Função JQUERY ********/
$(document).ready( function(){
	

			
/*************** banner rotativo ***************/
	$("#slider").easySlider({
			prevId: 'prevBtn',
			prevText: 'Previous',
			nextId: 'nextBtn',	
			nextText: 'Next',
			controlsShow: true,
			controlsBefore: '',
			controlsAfter: '',	
			controlsFade: true,
			firstId: 'firstBtn',
			firstText: 'First',
			firstShow: false,
			lastId: 'lastBtn',	
			lastText: 'Last',
			lastShow: false,				
			vertical: false,
			speed: 800,
			auto: true,
			pause:5000,
			continuous: true
			});
	

	$(".validation").validate({
		rules: {
			"data[User][realname]": {
				required: true,
				minlength: 6
			},
			"data[User][username]": {
				required: true,
				minlength: 4
			},
			"data[User][password]": {
				required: true,
				minlength: 5
			},
			"data[User][password_confirm]": {
				required: true,
				minlength: 5,
				equalTo: "#UserPassword"
			},
			"data[User][email]": {
				required: true,
				email: true
			},
		},
		messages: {
			"data[User][realname]": {
				required: "Por favor, digite seu nome completo",
				minlength: "Seu nome deve ter no mínimo 6 caracteres"
			},
			"data[User][username]": {
				required: "Por favor, digite seu login",
				minlength: "Seu login deve ter no mínimo 4 caracteres"
			},
			"data[User][password]": {
				required: "Por favor, digite sua senha",
				minlength: "Sua senha deve ter no mínimo 5 caracteres"
			},
			"data[User][password_confirm]": {
				required: "Por favor, re-digite a sua senha",
				minlength: "Sua senha deve ter no mínimo 5 caracteres",
				equalTo: "Os valores devem coincidir"
			},
			"data[User][email]": "Por favor, digite um email válido"
		}
	});	



$(".constr").click(function (e) { 
	e.preventDefault(); 
	alert('Em construção');
});


/******** Ativa ColorBox ********/
$("a[rel='colorbox']").colorbox({returnFocus:true, scrolling:false, slideshow:false});


		
/******** Mascara dos campos ********/
		
		$('input:text').setMask();
		
  
/******** SuperFish  ********/
	
	//Inicializa menu
        $("ul.sf-menu").superfish(); 

        
/******** JQUERY TABS ********/
		
		$( "#tabs" ).tabs();
	
   
/******** JQUERY CORNERS ********/
	
	//Barra requerimentos
	
 	//DIV message
  		$('.message').corner("5px");


	
 

/******** JQUERY Calendar ********/

	//classe padrão calendario
		$(".datePicker").datepicker({ dateFormat: 'dd/mm/yy',  autoSize: true, changeMonth:true, changeYear:true, yearRange: '1840', maxDate: 0 }, $.datepicker.regional['pt-BR']);
	
	//ALTFIELD date	
		$("#dateBR").datepicker({ dateFormat: 'dd/mm/yy', autoSize: true, changeMonth:true, changeYear:true, yearRange: '1840', altField: '#date', altFormat: 'yy-mm-dd'}, $.datepicker.regional['pt-BR']);
	
	//ALTFIELD created	
		$("#createdUS").datepicker({ dateFormat: 'dd/mm/yy', autoSize: true, changeMonth:true, changeYear:true, yearRange: '1840', altField: '#created', altFormat: 'yy-mm-dd'}, $.datepicker.regional['pt-BR']);
		
	//ALTFIELD modified
		$("#modifiedUS").datepicker({ dateFormat: 'dd/mm/yy', autoSize: true, changeMonth:true, changeYear:true, yearRange: '1840', altField: '#modified', altFormat: 'yy-mm-dd'}, $.datepicker.regional['pt-BR']);
	
/******** JQUERY Buttons ********/	
	
	//Classe dos Buttons personalizados
		$("button, input:submit, a", ".curso_action").button();
		$("button, input:submit, a", ".actions").button();		
		$("button, input:submit, a", ".login").button();
		$("button, input:submit, a", ".form").button();
		$("button, input:submit, a", ".paging").button();
		
/******** JQUERY UNIFORM ********/
		
	//Uniform estilos de input, checkbox.
		$("input:checkbox, input:radio, input:file").uniform();

/******** Finaliza função JQUERY *******/
});

/******** PRELOADER da pagina ******/

//tela do carregador
function __loadMostra(){
		    $("#msgloader").dialog({height:150, modal:true, resizable:false, title:'Carregando... Aguarde!'});
		}
		
/******* FUNÇÃO AUTO TAB ********/

var isNN = (navigator.appName.indexOf("Netscape")!=-1);
function autoTab(input,len, e) {
var keyCode = (isNN) ? e.which : e.keyCode;
var filter = (isNN) ? [0,8,9] : [0,8,9,16,17,18,37,38,39,40,46];
if(input.value.length >= len && !containsElement(filter,keyCode)) {
input.value = input.value.slice(0, len);
input.form[(getIndex(input)+1) % input.form.length].focus();
}
function containsElement(arr, ele) {
var found = false, index = 0;
while(!found && index < arr.length)
if(arr[index] == ele)
found = true;
else
index++;
return found;
}
function getIndex(input) {
var index = -1, i = 0, found = false;
while (i < input.form.length && index == -1)
if (input.form[i] == input)index = i;
else i++;
return index;
}
return true;
}

/******** FUNÇÃO PARA BUSCA CEP *******/

function getEndereco() {
		
		if($.trim($("#cep").val()) != ""){
				$('#error').css({display:'none'});
				$('#loading').css({display:''});
				$.getScript("http://webservice.kinghost.net/web_cep.php?auth=b6cbf5a1df0a1d4594b7c617521d2af8&formato=javascript&cep="+$("#cep").val(), function(){
		
		if(resultadoCEP["resultado"]==1){	
				$("#endereco").val(unescape(resultadoCEP["tipo_logradouro"])+": "+unescape(resultadoCEP["logradouro"]));
				$("#bairro").val(unescape(resultadoCEP["bairro"]));	
				$("#cidade").val(unescape(resultadoCEP["cidade"]));	
				$("#estado").val(unescape(resultadoCEP["uf"]));	
				$('#loading').css({display:'none'});
			}else{
				$('#loading').css({display:'none'});
				$('#error').css({display:''});
			}
		});
	}
}
	
/******** Função Para detectar CAPS LOOCK ligado ********/

//desliga capslock 
function capsDetect( e ) {
  // se o navegador não passou informações sobre o evento para o manipulador,
  // verifica em window.event
  if( !e ) { e = window.event; } if( !e ) { return; }
  //what (case sensitive in good browsers) key was pressed
  //this uses all three techniques for checking, just in case
  var theKey = 0;
  if( e.which ) { theKey = e.which; } //Netscape 4+, etc.
  else if( e.keyCode ) { theKey = e.keyCode; } //Internet Explorer, etc.
  else if( e.charCode ) { theKey = e.charCode } //Gecko - probably not needed
  //was the shift key was pressed
  var theShift = false;
  if( e.shiftKey ) { theShift = e.shiftKey; } //Internet Explorer, etc.
  else if( e.modifiers ) { //Netscape 4
    //check the third bit of the modifiers value (says if SHIFT is pressed)
    if( e.modifiers & 4 ) { //bitwise AND
      theShift = true;
    }
  }
  //if upper case, check if shift is not pressed
  if( theKey > 64 && theKey < 91 && !theShift ) {
    alert( 'Caps Lock esta ativo. Favor desliga-lo' );
  }
  //if lower case, check if shift is pressed
  else if( theKey > 96 && theKey < 123 && theShift ) {
    alert( 'Caps Lock esta ativo. Favor desliga-lo' );
  }
}

/******** Fução para validar CPF e CNPJ ********/
function cpfcnpj(){
	if(document.a.b.value.length == 3){
		document.a.b.value = document.a.b.value + '.';
		return false;
	}
	if(document.a.b.value.length == 7){
		document.a.b.value = document.a.b.value + '.';
		return false;
	}
	if(document.a.b.value.length == 11){
		document.a.b.value = document.a.b.value + '-';
		return false;
	}
	if(document.a.b.value.length == 15){
		p0=document.a.b.value.charAt(0);
		p1=document.a.b.value.charAt(1);
		p2=document.a.b.value.charAt(2);
		p3=document.a.b.value.charAt(4);
		p4=document.a.b.value.charAt(5);
		p5=document.a.b.value.charAt(6);
		p6=document.a.b.value.charAt(8);
		p7=document.a.b.value.charAt(9);
		p8=document.a.b.value.charAt(10);
		p9=document.a.b.value.charAt(12);
		p10=document.a.b.value.charAt(13);
		p11=document.a.b.value.charAt(14);
		document.a.b.value = '';
		document.a.b.value = p0 + p1 + '.' + p2 + p3 + p4 + '.' + p5 + p6 + p7 + '/' + p8 + p9 + p10 + p11 + '-';
		p0='';
		p1='';
		p2='';
		p3='';
		p4='';
		p5='';
		p6='';
		p7='';
		p8='';
		p9='';
		p10='';
		p11='';
		return false;
	}
}


// JavaScript Document
/*	********************************************************************	
	####################################################################
	Assunto = Validação de CPF e CNPJ
	Autor = Marcos Regis
	Data = 24/01/2006
	Versão = 1.0
	Compatibilidade = Todos os navegadores.
	Pode ser usado e distribuído desde que esta linhas sejam mantidas
	====------------------------------------------------------------====
	
	Funcionamento = O script recebe como parâmetro um objeto por isso 
	deve ser chamado da seguinte forma:
	E.: no evento onBlur de um campo texto
	<input name="cpf_cnpj" type="text" size="40" maxlength="18" 
	onBlur="validar(this);">
	Ao deixar o campo o evento é disparado e chama validar() com o 
	argumento "this" que representa o próprio objeto com todas as 
	propriedades.
	A partir daí a função validar() trata a entrada removendo tudo que
	não for caracter numérico e deixando apenas números, portanto
	valores escritos só com números ou com separadores como '.' ou mesmo
	espaços são aceitos
	ex.: 111222333/44, 111.222.333-44, 111 222 333 44 serão tratadoc como
	11122233344 (para CPFs)
	De certa forma até mesmo valores como 111A222B333C44 será aceito mas
	aconselho a usar a função soNums() que encotra-se aqui mesmo para
	que o campo só aceite caracteres numéricos.
	Para usar a função soNums() chame-a no evento onKeyPress desta forma
	onKeyPress="return soNums(event);"
	Após limpar o valor verificamos seu tamanho que deve ser ou 11 ou 14
	Se o tamanho não for aceito a função retorna false e [opcional] 
	mostra uma mensagem de erro.
	Sugestões e comentários marcos_regis@hotmail.com
	####################################################################
	********************************************************************	*/

// a função principal de validação
function validar(obj) { // recebe um objeto
	var s = (obj.value).replace(/\D/g,'');
	var tam=(s).length; // removendo os caracteres não numéricos
	if (!(tam==11 || tam==14)){ // validando o tamanho
		$("#CPFinvalido").dialog({height:70, modal:true, resizable:false, title:'Aten&ccedil;&atilde;o!'}); // se quiser mostrar o erro
		return false;
	}
	
// se for CPF
	if (tam==11 ){
		if (!validaCPF(s)){ // chama a função que valida o CPF
			$("#CPFinvalido").dialog({height:70, modal:true, resizable:false, title:'Aten&ccedil;&atilde;o!'}); // se quiser mostrar o erro
			obj.select();  // se quiser selecionar o campo em questão
			return false;
		}
		obj.value=maskCPF(s);	// se validou o CPF mascaramos corretamente
		return true;
	}
	
// se for CNPJ			
	if (tam==14){
		if(!validaCNPJ(s)){ // chama a função que valida o CNPJ
			$("#CNPJinvalido").dialog({height:70, modal:true, resizable:false, title:'Aten&ccedil;&atilde;o!'}); // se quiser mostrar o erro
			obj.select();	// se quiser selecionar o campo enviado
			return false;			
		}
		obj.value=maskCNPJ(s);	// se validou o CNPJ mascaramos corretamente
		return true;
	}
}
// fim da funcao validar()

// função que valida CPF
// O algorítimo de validação de CPF é baseado em cálculos
// para o dígito verificador (os dois últimos)
// Não entrarei em detalhes de como funciona
function validaCPF(s) {
	var c = s.substr(0,9);
	var dv = s.substr(9,2);
	var d1 = 0;
	for (var i=0; i<9; i++) {
		d1 += c.charAt(i)*(10-i);
 	}
	if (d1 == 0) return false;
	d1 = 11 - (d1 % 11);
	if (d1 > 9) d1 = 0;
	if (dv.charAt(0) != d1){
		return false;
	}
	d1 *= 2;
	for (var i = 0; i < 9; i++)	{
 		d1 += c.charAt(i)*(11-i);
	}
	d1 = 11 - (d1 % 11);
	if (d1 > 9) d1 = 0;
	if (dv.charAt(1) != d1){
		return false;
	}
    return true;
}

// Função que valida CNPJ
// O algorítimo de validação de CNPJ é baseado em cálculos
// para o dígito verificador (os dois últimos)
// Não entrarei em detalhes de como funciona
function validaCNPJ(CNPJ) {
	var a = new Array();
	var b = new Number;
	var c = [6,5,4,3,2,9,8,7,6,5,4,3,2];
	for (i=0; i<12; i++){
		a[i] = CNPJ.charAt(i);
		b += a[i] * c[i+1];
	}
	if ((x = b % 11) < 2) { a[12] = 0 } else { a[12] = 11-x }
	b = 0;
	for (y=0; y<13; y++) {
		b += (a[y] * c[y]);
	}
	if ((x = b % 11) < 2) { a[13] = 0; } else { a[13] = 11-x; }
	if ((CNPJ.charAt(12) != a[12]) || (CNPJ.charAt(13) != a[13])){
		return false;
	}
	return true;
}


	// Função que permite apenas teclas numéricas
	// Deve ser chamada no evento onKeyPress desta forma
	// return (soNums(event));
function soNums(e)
{
	if (document.all){var evt=event.keyCode;}
	else{var evt = e.charCode;}
	if (evt <20 || (evt >47 && evt<58)){return true;}
	return false;
}

//	função que mascara o CPF
function maskCPF(CPF){
	return CPF.substring(0,3)+"."+CPF.substring(3,6)+"."+CPF.substring(6,9)+"-"+CPF.substring(9,11);
}

//	função que mascara o CNPJ
function maskCNPJ(CNPJ){
	return CNPJ.substring(0,2)+"."+CNPJ.substring(2,5)+"."+CNPJ.substring(5,8)+"/"+CNPJ.substring(8,12)+"-"+CNPJ.substring(12,14);	
}
//-->

/******** Função para Exibir Relógio Dinâmico *******/

function startclock()
{
var thetime=new Date();
var nhours=thetime.getHours();
var nmins=thetime.getMinutes();
var nsecn=thetime.getSeconds();

if (nsecn<10)
 nsecn="0"+nsecn;
if (nmins<10)
 nmins="0"+nmins;
document.getElementById("clockspot").value=nhours+":"+nmins+":"+nsecn;
setTimeout('startclock()',1000);
}

/******** Busca dentro de um ComboBox *******/

MyUtil = new Object();
MyUtil.selectFilterData = new Object();
MyUtil.selectFilter = function(selectId, filter) {
	var list = document.getElementById(selectId);
	if(!MyUtil.selectFilterData[selectId]) { //if we don't have a list of all the options, cache them now'
		MyUtil.selectFilterData[selectId] = new Object();
		for(var i = 0; i < list.options.length; i++) MyUtil.selectFilterData[selectId][list.options[i].value] = list.options[i];
	}
	
	//go through all the options in the current list and set the selection status to the cached options
	for(var i = 0; i < list.options.length; i++) MyUtil.selectFilterData[selectId][list.options[i].value]  = list.options[i];
	
	list.options.length = 0;   //remove all elements from the list
	for(var id in MyUtil.selectFilterData[selectId]) { //add elements from cache if they match filter
		var o = MyUtil.selectFilterData[selectId][id];
		if(o.text.toLowerCase().indexOf(filter.toLowerCase()) >= 0) list.add(o, null);
	}
}

/********* AUTO FOCUS *********/

function formfocus() {
if(document.forms.length > 0)
{
var formElements = ["text", "checkbox", "radio", "select-one", "select-multiple", "textarea"];
var form = document.forms[document.forms.length-1];
for (var j = 0; j < form.elements.length; j++)
{
var field = form.elements[j];
for(var x = 0; x < formElements.length; x++)
{
if (field.getAttribute("type") == formElements[x])
{
field.focus();
return false;
}
}
}
}
}

/******** Preenche valor *********/


function apostilaValor(item){
	for(var i=0;i<item.form.elements.length;i++){
		if(item==item.form.elements[i]){
			item.form.elements[i+2].value = item.options[item.selectedIndex].id;
			item.form.elements[i+3].value = item.options[item.selectedIndex].title;
		}
	}
	apostilaTotal();
}

function apostilaTotal(){ 
	var aVista = document.getElementById("qt").value*document.getElementById("valorv").value;
	var aPrazo = document.getElementById("qt").value*document.getElementById("valorp").value;
	document.getElementById("totalv").value = aVista.toFixed(2);
	document.getElementById("totalp").value = aPrazo.toFixed(2);
}
/**** valida ano *******/

function validaAno(){
	var nascimento = document.getElementById("nascimento").value;
	data = new Date();
    var ano = data.getFullYear();
	if( nascimento.substring(6,10) >= ano){
		alert('ATENÇÃO: Você não nasceu no ano: '+nascimento.substring(6, 10));
		document.getElementById("nascimento").value = "";
		//$("#NascimentoInvalido").dialog({height:70, modal:true, resizable:false, title:'Aten&ccedil;&atilde;o!'});
		
	}
}
