// JavaScript Document
var janelaPop;

function tab(cmp) {
	$(cmp).focus();
}

function desabilitarTodosCampos(formId){
	var el = $(formId).elements;
	for(var i=0;i<el.length;i++){
		el[i].setAttribute('disabled',true)
	}
}

function desabilitarEdicaoInstituicao() {
	$("razaoSocial").readOnly = true;
	$("nomeFantasia").readOnly = true;
	$("codigo").readOnly = true;
	$("cnpj").readOnly = true;
	$("telefone").readOnly = true;
	$("fax").readOnly = true;
	$("email").readOnly = true;
	$("site").readOnly = true;
	$("agencia").readOnly = true;
	$("codigoCedente").readOnly = true;
	$("logradouro").readOnly = true;
	$("complemento").readOnly = true;
	$("bairro").readOnly = true;
	$("cep").readOnly = true;
	$("cidade").readOnly = true;
	$("uf").readOnly = true;
	$("responsavel").readOnly = true;
	$("horarioFuncionamento").readOnly = true;
}

function formatarCEP(e, campo) {
	var keyCode = e.keyCode;
	if (campo.value.length==5 && keyCode!=8) campo.value += "-";
}

function formatarData(e, campo) {
	var keyCode = e.keyCode;
	if (campo.value.length==2 && keyCode!=8 && keyCode!=193) campo.value += "/";
	if (campo.value.length==5 && keyCode!=8 && keyCode!=193) campo.value += "/";
}

function formatarTelefone(e, campo) {
	var keyCode = e.keyCode;
	if (campo.value.length==0 && keyCode!=8) campo.value += "(";
	if (campo.value.length==3 && keyCode!=8) campo.value += ") ";
}

function formatarCNPJ(e, campo){
   var tecla = e.keyCode;

   var vr = new String(campo.value);
   vr = vr.replace(".", "");
   vr = vr.replace(".", "");
   vr = vr.replace("/", "");
   vr = vr.replace("-", "");

   tam = vr.length + 1 ;
   
   if (tecla != 9 && tecla != 8){
      if (tam > 2 && tam < 6)
         campo.value = vr.substr(0, 2) + '.' + vr.substr(2, tam);
      if (tam >= 6 && tam < 9)
         campo.value = vr.substr(0,2) + '.' + vr.substr(2,3) + '.' + vr.substr(5,tam-5);
      if (tam >= 9 && tam < 13)
         campo.value = vr.substr(0,2) + '.' + vr.substr(2,3) + '.' + vr.substr(5,3) + '/' + vr.substr(8,tam-8);
      if (tam >= 13 && tam < 15)
         campo.value = vr.substr(0,2) + '.' + vr.substr(2,3) + '.' + vr.substr(5,3) + '/' + vr.substr(8,4)+ '-' + vr.substr(12,tam-12);
   }
  
}

function formatarCPF(e, campo){
   var tecla = e.keyCode;

   var vr = new String(campo.value);
   vr = vr.replace(".", "");
   vr = vr.replace(".", "");
   vr = vr.replace("/", "");
   vr = vr.replace("-", "");

   tam = vr.length + 1 ;
   
   if (tecla != 9 && tecla != 8){
      if (tam > 3 && tam < 7)
         campo.value = vr.substr(0, 3) + '.' + vr.substr(3, tam);
      if (tam >= 7 && tam < 10)
         campo.value = vr.substr(0,3) + '.' + vr.substr(3,3) + '.' + vr.substr(6,tam-6);
      if (tam >= 10 && tam < 14)
         campo.value = vr.substr(0,3) + '.' + vr.substr(3,3) + '.' + vr.substr(6,3) + '-' + vr.substr(9,tam-9);		 
   }
  
}

function selecao(selObj) {
	var resultado = "";
	for (i=0; i<selObj.length; i++) {
		if (selObj[i].selected) {
			resultado += selObj[i].value;
			if ((i+1)<selObj.length)
				resultado += "|";
		}
	}
	return resultado;
}

function checado(chkObj) {
	if(chkObj.length == undefined){
		if(chkObj.checked)
			return chkObj.value;
		else
			return null;
	}
	for (i = 0; i < chkObj.length; i++) {
		if (chkObj[i].checked)
			return chkObj[i].value;
	}
	return null;
}

function toggle(divId, imgId, imgExpand, imgFoldUp) {
	var div = document.getElementById(divId);
	if (div.style.display == "none")
		div.style.display = "block";
	else
		div.style.display = "none";
	
	if (imgId != undefined) {
		if (div.style.display == "none")
			document.getElementById(imgId).src = imgFoldUp;
		else
			document.getElementById(imgId).src = imgExpand;
	}
}

function reportarErro(request) {
	var texto = new String(request.responseText);
	if (texto.replace(/<[^>]*>/gi, "")!="")
		alert(texto.replace(/<[^>]*>/gi, ""));
	//else
	//	alert("Conexão com a internet foi encerrada inesperadamente, tente novamente.");
}

function formataData(data) {
	/**
	* Formata a data  no formato yyyy-mm-dd em dd/MMM/yyyy
	**/
	var meses = new Array("Jan", "Fev", "Mar", "Abr", "Mai", "Jun", "Jul", "Ago", "Set", "Out", "Nov", "Dez");
	pars = data.split("-");
	
	//return pars[2] + "/" + meses[parseInt(pars[1])-1] + "/" + pars[0];
	return pars[2] + "/" + pars[1] + "/" + pars[0];
}

function formataDataSQL(data) {
	/**
	* Formata a data  no formato dd/MM/yyyy em yyyy-mm-dd
	**/
	if (data!="" && data != "dd/mm/yyyy" && data!="Não definido") {
		pars = data.split("/");
		if (pars.length==3&&pars[0]!=undefined&&pars[1]!=undefined&&pars[2]!=undefined) {
			return pars[2] + "-" + pars[1] + "-" + pars[0];
		}
		else
			return "0000-00-00";
	}
	else {
		return "0000-00-00";
	}
}

function changeMonth(id, month, year) {
	var url = 'Calendar';
	var pars = 'id='+id+'&month='+month+'&year='+year+'&locale=pt';
		
	var myAjax = new Ajax.Updater( "calendar_" + id, url, {method: 'post', parameters: pars, onFailure: reportarErro});
}
function novaJanela(url, name, width, height, full) {
   W = eval(screen.width)-10;
   H = eval(screen.height)-104;
   if (full == 0) {
      return window.open(url,name,"height=" + height + ",width=" + width + ",directories=no,menubar=no,personalbar=no,toolbar=no,scrollbars=yes,status=no,resizable=no");
   }
   else {
      return window.open(url,name,"toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=no,copyhistory=no,width="+W+",height="+H+",top=0,left=0"); 
   }
}

function addListener(element, event, listener, bubble) {
	if(element.addEventListener) {
		if(typeof(bubble) == "undefined") bubble = false;
		element.addEventListener(event, listener, bubble);
	}
	else if(this.attachEvent) {
		element.attachEvent("on" + event, listener);
	}
}

function removeListener(element, event, listener, bubble) {
	if(element.addEventListener) {
		if(typeof(bubble) == "undefined") bubble = false;
		element.removeEventListener(event, listener, bubble);
	}
	else if(this.attachEvent) {
		element.detachEvent("on" + event, listener);
	}
}

function aguarde(target, texto) {
	if (typeof(rte7)!="undefined")
		rte7.setSource('&nbsp;');
		
	if (typeof(texto)=="undefined")
		texto = "Aguarde ...";
		
	$(target).style.display = "block";
	$(target).innerHTML = "&nbsp;&nbsp;<img src='../images/loading.gif' align='absmiddle'>&nbsp;<font face='Arial' size='1'><b>"+texto+"</b></font>";
	
	if ($('editorGuiaDisciplina')!=null)
		$('editorGuiaDisciplina').style.visibility="hidden";

	if ($('editorGuiaCurso')!=null)
		$('editorGuiaCurso').style.visibility="hidden";
		
}

function setCookie( name, value, expiresInDays, path, domain, secure ) {
	var today = new Date();
	today.setTime( today.getTime() );
	
	if ( expiresInDays ) {
		expiresInDays = expiresInDays * 1000 * 60 * 60 * 24;
	}
	var expires_date = new Date( today.getTime() + (expiresInDays) );
	
	document.cookie = name + "=" +escape( value ) +
	( ( expiresInDays ) ? ";expires=" + expires_date.toGMTString() : "" ) + 
	( ( path ) ? ";path=" + path : "" ) + 
	( ( domain ) ? ";domain=" + domain : "" ) +
	( ( secure ) ? ";secure" : "" );
}

function getCookie( name ) {
	var start = document.cookie.indexOf( name + "=" );
	var len = start + name.length + 1;
	if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) {
		return null;
	}
	if ( start == -1 ) return null;

	var end = document.cookie.indexOf( ";", len );
	if ( end == -1 ) end = document.cookie.length;
	
	return unescape( document.cookie.substring( len, end ) );
}
	
function deleteCookie( name, path, domain ) {
	if ( getCookie( name ) ) document.cookie = name + "=" +
	( ( path ) ? ";path=" + path : "") +
	( ( domain ) ? ";domain=" + domain : "" ) +
	";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

function roundNumber(float,dec){
	return Math.round(float*Math.pow(10,dec))/Math.pow(10,dec)
}

function isValidEmail(email) {
	var regExp = new RegExp("^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*(\\.[_A-Za-z0-9-]+)");
	return regExp.test(email);
}

function formatarNumero(e, id) {
	var keyCode = e.keyCode;
	var valor = new String($F(id));
	var caracter = String.fromCharCode(keyCode);
	if(keyCode==188||keyCode==110||caracter==",")
		$(id).value = valor.replace(/\,/gi,".");
}

function somenteNumero(e, id) {
	var key;
	var keychar;
	if (window.event)
	   key = window.event.keyCode;
	else if (e)
	   key = e.which;
	else
	   return true;
	keychar = String.fromCharCode(key);

	if ((key==null) || (key==0) || (key==8) || (key==9) || (key==13) || (key==27) || (key==45))
	   return true;
	else if ((("0123456789").indexOf(keychar) > -1)) {
	   	return true;
	}
	else if (keychar == "." || keychar == ",") {
	   return true;
	}
	else if (keychar == "-") {
	   	return true;
	}
	else
	   return false;
}

function validarRG(e, id) {
	var key;
	var keychar;
	if (window.event)
	   key = window.event.keyCode;
	else if (e)
	   key = e.which;
	else
	   return true;
	keychar = String.fromCharCode(key);

	if (keychar == "." || keychar == "," || keychar == "-" || keychar == "+" || keychar == "~" || keychar == "\/" || keychar == "\\") {
	   return false;
	}
	else
	   return true;
}

function abrirSistema(strURL,strType, width, height) {
	janelaPop = null;
	var strOptions="";
	if (strType=="console") strOptions="resizable" + (width!=undefined&&height!=undefined?",width="+width+",height="+height:"");
	if (strType=="fixed") strOptions="status" + (width!=undefined&&height!=undefined?",width="+width+",height="+height:"");
	if (strType=="elastic") strOptions="menubar,scrollbars,resizable" + (width!=undefined&&height!=undefined?",width="+width+",height="+height:"");
	if (strType=="full") {
	   var W = eval(screen.width)-10;
	   var H = eval(screen.height)-90;
       strOptions = "toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=no,copyhistory=no,width="+W+",height="+H+",top=0,left=0"; 
	}
	janelaPop = window.open(strURL, 'novaJanela', strOptions);
	return janelaPop;
}

function numeroDias(dataInicio, dataFim) {
	// dataInicio e dataFim no formato: yyyy-mm-dd
	var inicio = new Date(dataInicio.split("-")[0], dataInicio.split("-")[1], dataInicio.split("-")[2]);
	var fim = new Date(dataFim.split("-")[0], dataFim.split("-")[1], dataFim.split("-")[2]);
	return parseInt((fim - inicio) / (365 * 1000 * 60 * 60 * 24));
}

function stopRKey(evt) {
	var evt = (evt) ? evt : ((event) ? event : null);
	var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
	if ((evt.keyCode == 13) && (node.type=="text"||node.type=="radio"||node.type=="checkbox"||node.type=="textarea")||node.type=="select")  {return false;}
}

function html2entities(str) {
	var keys=new Array("&", " ", "¡", "¢", "£", "¤", "¥", "¦", "§", "¨", "©", "ª", "«", "¬", "­", "®", "¯", "°", "±", "²", "³", "´", "µ", "¶", "·", "¸", "¹", "º", "»", "¼", "½", "¾", "¿", "À", "Á", "Â", "Ã", "Ä", "Å", "Æ", "Ç", "È", "É", "Ê", "Ë", "Ì", "Í", "Î", "Ï", "Ð", "Ñ", "Ò", "Ó", "Ô", "Õ", "Ö", "×", "Ø", "Ù", "Ú", "Û", "Ü", "Ý", "Þ", "ß", "à", "á", "â", "ã", "ä", "å", "æ", "ç", "è", "é", "ê", "ë", "ì", "í", "î", "ï", "ð", "ñ", "ò", "ó", "ô", "õ", "ö", "÷", "ø", "ù", "ú", "û", "ü", "ý", "þ", "ÿ", "\"", "<", ">", "", "“", "”", "‘", "’");
    var values=new Array("&amp;", "&nbsp;", "&iexcl;", "&cent;", "&pound;", "&curren;", "&yen;", "&brvbar;", "&sect;", "&uml;", "&copy;", "&ordf;", "&laquo;", "&not;", "&shy;", "&reg;", "&macr;", "&deg;", "&plusmn;", "&sup2;", "&sup3;", "&acute;", "&micro;", "&para;", "&middot;", "&cedil;", "&sup1;", "&ordm;", "&raquo;", "&frac14;", "&frac12;", "&frac34;", "&iquest;", "&Agrave;", "&Aacute;", "&Acirc;", "&Atilde;", "&Auml;", "&Aring;", "&AElig;", "&Ccedil;", "&Egrave;", "&Eacute;", "&Ecirc;", "&Euml;", "&Igrave;", "&Iacute;", "&Icirc;", "&Iuml;", "&ETH;", "&Ntilde;", "&Ograve;", "&Oacute;", "&Ocirc;", "&Otilde;", "&Ouml;", "&times;", "&Oslash;", "&Ugrave;", "&Uacute;", "&Ucirc;", "&Uuml;", "&Yacute;", "&THORN;", "&szlig;", "&agrave;", "&aacute;", "&acirc;", "&atilde;", "&auml;", "&aring;", "&aelig;", "&ccedil;", "&egrave;", "&eacute;", "&ecirc;", "&euml;", "&igrave;", "&iacute;", "&icirc;", "&iuml;", "&eth;", "&ntilde;", "&ograve;", "&oacute;", "&ocirc;", "&otilde;", "&ouml;", "&divide;", "&oslash;", "&ugrave;", "&uacute;", "&ucirc;", "&uuml;", "&yacute;", "&thorn;", "&yuml;", "&quot;", "&lt;", "&gt;", "", "&quot;", "&quot;", "&acute;", "&acute;");
    for(var i=0; i<keys.length; i++) {
		if(values[i]!="&nbsp;")
			str=str.replace(keys[i], values[i]);
	}	
    return str;
}

function disableAll(excecoes) {
	
	if(excecoes==undefined)
		excecoes = " ";
	
	inputs = document.getElementsByTagName("input");
	selects = document.getElementsByTagName("select");
	textAreas = document.getElementsByTagName("textarea");
	
	for (i = 0; i < inputs.length; i++)
		if((excecoes!="")&&(!excecoes.match(inputs[i].name)))		
			inputs[i].disabled = true;
	
	for (i = 0; i < selects.length; i++)
		if((excecoes!="")&&(!excecoes.match(selects[i].name)))		
			selects[i].disabled = true;
	
	for (i = 0; i < textAreas.length; i++)
		if((excecoes!="")&&(!excecoes.match(textAreas[i].name)))		
			textAreas[i].disabled = true;
	
}

function selecionaTodos(on){
	var inputs = document.getElementsByTagName('input');
	for(i=0; i<inputs.length; i++){
		if(inputs[i].type == 'checkbox' && inputs[i].disabled == false)
			inputs[i].checked = on;
	}
}

function validarCPF(cpf) {
	var filtro = /^\d{3}.\d{3}.\d{3}-\d{2}$/i;
	if(!filtro.test(cpf)){
		return false;
	}
   
	cpf = remove(cpf, ".");
	cpf = remove(cpf, "-");
    
	if(cpf.length != 11 || cpf == "00000000000" || cpf == "11111111111" || cpf == "22222222222" || cpf == "33333333333" || cpf == "44444444444" || cpf == "55555555555" || cpf == "66666666666" || cpf == "77777777777" || cpf == "88888888888" || cpf == "99999999999") {
		return false;
	}

	soma = 0;
	for(i = 0; i < 9; i++)
		soma += parseInt(cpf.charAt(i)) * (10 - i);
	resto = 11 - (soma % 11);
	if(resto == 10 || resto == 11)
		resto = 0;
	if(resto != parseInt(cpf.charAt(9))){
		return false;
   }
   soma = 0;
   for(i = 0; i < 10; i ++)
		soma += parseInt(cpf.charAt(i)) * (11 - i);
   resto = 11 - (soma % 11);
   if(resto == 10 || resto == 11)
		resto = 0;
   if(resto != parseInt(cpf.charAt(10))){
		return false;
   }
   return true;
}
 
function remove(str, sub) {
   i = str.indexOf(sub);
   r = "";
   if (i == -1) return str;
   r += str.substring(0,i) + remove(str.substring(i + sub.length), sub);
   return r;
}

function marcarCampos(lista) {
	for (i=0; i<lista.split(",").length; i++) {
		$(lista.split(",")[i]).className = "campoMarcado";
	}
}
