function get(id)
{
	return document.getElementById(id);
}

function getTag(tag)
{
	return document.getElementsByTagName(tag);
}

function getFormObjById(id)
{
	if(typeof form!="object")
		var form = document.form;
	else return null;
	
	var qtd = form.length;
	
	for(var i=0; i < qtd; i++)
	{
		if (form[i].id == id)
			return get(form[i].id);
	}
	return null;
}

function empty(obj)
{
	var type = typeof obj;
	var er = /^\s{0,}$/;
	var retorno = false;

	if(type=="string")
	{
		if(obj.match(er))
			return true;
	}
	if(type!="undefined")
	{
		if(type == "object")
		{
			retorno  = obj.value.match(er);
		}
		else if(get(obj))
		{
			retorno = get(obj).value.match(er);
		}
	}	
	
	return retorno;
}

function exclui(texto_adicional)
{
	var texto = "Deseja realmente excluir este registro?";
	if (texto_adicional)
		texto+= " " + texto_adicional;
	
	if(!empty(get('codigo').value))
		return conf = confirm(texto);
	else
		return false;
}

function contirma(texto)
{
	return confirm(texto);
}

function evidencia(obj)
{
	var cor = arguments[1] ? arguments[1] : '#A5ACB2';
	
	if(typeof obj != "object")
	{
		obj = get(obj);
	}
	obj.style.border = '1px solid '+cor;
}

function evidenciaOff(obj)
{
	if(!empty(obj))
		evidencia(obj);
}

function validaBusca()
{
	if(empty('busca'))	
	{
		alert("Informe um dado para busca!");
		get('busca').focus();
		return false;
	}
	else
	{
		return true;
	}
}

function validaFORM(form)
{
	if(typeof form!="object")
		var form = document.form;

	var qtd = form.length;
	var type, id, label, obj, obr, rel, tipoVal, senha, lbSenha, cSenha, lbCSenha, email, lbEmail, cEmail, lbCEmail;
	var msg = "";
	var erType = /^(submit|button|hidden)$/;
	var headMsg = "";
	var $cnpj = null;
	var $cpf = null;
	
	for(var i=0; i < qtd; i++)
	{
		obj = get(form[i].id);
		
		if(!obj.type.match(erType))
		{
			rel = obj.getAttribute('rel')
			
			if(typeof rel !="object")
			{
				obr = rel.match(/^true/) ? true : false;
			}
			else
			{
				obr = false;
			}
			
			if(obr)
			{
				label = get("lb_"+obj.id).innerHTML;
				
				if(empty(obj))
				{
					if((obj.type=="text") || (obj.type=="password"))
					{
						msg+="\n O campo '"+label+"' deve ser preenchido.\n";
					}
					else if(type="select-one")
					{
						msg+="\n O campo '"+label+"' deve ser selecionado.\n";
					}
					evidencia(obj, '#09B6E8');
				}
				else if(typeof rel!='object' && obj.id!="senha"  && obj.id!="csenha")
				{
					tipoVal = rel.split("_");
				
					if(tipoVal.length == 2 && !empty(tipoVal[1]))
					{
						if(tipoVal[1]=='cpfcnpj')
						{
							$cpf = eval('validaCPF(\''+obj.value+'\')');
							$cnpj = eval('validaCNPJ(\''+obj.value+'\')');
							
							if($cpf == false && $cnpj == false)
							{
								msg+="\n O campo "+label+' deve ser preenchido com um CPF ou CNPJ válido.\n';
								evidencia(obj, '#09B6E8')
							}
						}
						else 
						{
							if(!eval('valida'+tipoVal[1].toUpperCase()+'(\''+obj.value+'\')'))
							{
								msg+="\n O campo "+label+' deve ser preenchido com um '+tipoVal[1].toUpperCase()+' válido.\n';
								evidencia(obj, '#09B6E8');
							}
						}
					}
				}
				if(obj.id == "senha" && rel == 'true_')
				{
					Senha = obj;
					lbSenha = label;
				}
				else if(obj.id == "csenha" && rel == 'true_')
				{
					cSenha = obj;
					lbCSenha = label;
				}
				else if(obj.id == "cEmail" && rel == 'true_')
				{
					cEmail = obj;
					lbCEmail = label;
				}
				else if(obj.id == "email")
				{
					email = obj;
					lbEmail = label;
				}
			}
			else
			{
				if(!empty(obj) && typeof rel!='object' && obj.id!="senha"  && obj.id!="csenha")
				{
					label = get("lb_"+obj.id).innerHTML;
					tipoVal = rel.split("_");
				
					if(tipoVal.length == 2 && !empty(tipoVal[1]))
					{
						if(tipoVal[1]=='cpfcnpj')
						{
							$cpf = eval('validaCPF(\''+obj.value+'\')');
							$cnpj = eval('validaCNPJ(\''+obj.value+'\')');
							
							if($cpf == false && $cnpj == false)
							{
								msg+="\n O campo "+label+' deve ser preenchido com um CPF ou CNPJ válido.\n';
								evidencia(obj, '#09B6E8')
							}
						}
						else 
						{
							if(!eval('valida'+tipoVal[1].toUpperCase()+'(\''+obj.value+'\')'))
							{
								msg+="\n O campo "+label+' deve ser preenchido com um(a) '+tipoVal[1].toUpperCase()+' válido.\n';
								evidencia(obj, '#09B6E8');
							}
						}
					}					
				}
			}
		}
	}
	
	if(typeof(Senha)!='undefined' && typeof(cSenha)!='undefined')
	{
		if (!empty(Senha) && !empty(cSenha))
		{
			if(Senha.value != cSenha.value)
			{
				msg+="\n O campo '"+lbSenha+"' e o campo '"+lbCSenha+"' devem ser iguais.\n";
				evidencia(Senha, '#09B6E8');
				evidencia(cSenha, '#09B6E8');
			}
			else if(Senha.value.length < 6)
			{
				msg+="\n O campo '"+lbSenha+"' deve ter no mínimo 6 (seis) caracteres.\n";
				evidencia(Senha, '#09B6E8');
				evidencia(cSenha, '#09B6E8');
			}
		}
	}
	
	if(cEmail)
	{
		if(cEmail.value != email.value)
		{
			msg+="\n O campo '"+lbEmail+"' e o campo '"+lbCEmail+"' devem ser iguais.\n";
			evidencia(email, '#09B6E8');
			evidencia(cEmail, '#09B6E8');
		}
	}
	
	if(!empty(msg))
	{
		msg = "Foram encontrados os seguintes erros no preenchimento do formulario:\n"+msg;
		alert(msg);
		return false;
	}	
	return true;
}

function mascara(campo, mask, e)
{
    campo.maxLength=mask.length;
    var src=campo.value.length;
    var mask=mask.substr(src,1);
    
    var code;
    if (!e) var e = window.event; // set var e for ie
    if (e.keycode) code = e.keycode; // ie and mozilla/gecko
    else if (e.which) code = e.which; // ns4 and opera

    if(code!=13 && (code > 47 && code < 58))
    {
    	if(mask!='#' && src>=0)
    	{	
        	campo.value+=mask;
    	}
    }
    else if( (code > 31 && code < 48 ) || (code > 57 && code < 65 ) || (code > 64 && code < 91 ) ||  code > 90 )
    {
        if ('function' == typeof e.preventDefault)
        	e.preventDefault();
        else e.returnValue = false;
    }    
}

function isNumeric(expression) 
{
	var nums = "0123456789";
	
	if (expression.length==0)
		return false;

	for (n=0; n < expression.length; n++)
	{
		if (nums.indexOf(expression.charAt(n))==-1)
			return false;
	}

	return true;
}

function Numero(campo)
{  
	var valor = campo.value;
	
	if(valor.length>15)
	{
		valor=valor.substr(0,15);
	}
	valor=valor.replace(/\D/g,"")  
	valor=valor.replace(/(\d{1})(\d{9})$/,"$1.$2")
	valor=valor.replace(/(\d{1})(\d{6})$/,"$1.$2")
	valor=valor.replace(/(\d{1})(\d{3})$/,"$1.$2")
	campo.value = valor;
}

function validaCEP(cep)
{
	var er = /^\d{5}\-\d{3}/;
	
	return cep.match(er);
		
}

function validaNUMERO(mumero)
{
	var er = /^\d+/;
	
	return mumero.match(er);
		
}

function validaEMAIL(email)
{
//	var er = /^[a-z0-9-_.]+@+[a-z0-9-_.]+\.[a-z]{2,4}((\.)[a-z]{2})?$/;
	var er = /^[\w-]+(\.[\w-]+)*@(([A-Za-z\d][A-Za-z\d-]{0,61}[A-Za-z\d]\.)+[A-Za-z]{2,6}|\[\d{1,3}(\.\d{1,3}){3}\])$/;
	
	return email.match(er);
}

function validaDOMINIO(dominio)
{
	var er = /^(([A-Za-z\d][A-Za-z\d-]{0,61}[A-Za-z\d]\.)+[A-Za-z]{2,6}|\[\d{1,3}(\.\d{1,3}){3}\])$/;
	
	return dominio.match(er);
}

function validaANO(ano)
{
	if(ano%4==0)
	{
		if(ano%100!=0 || ano%400 == 0)
		{
			return true;
		}
	}
	
	return false;
}


function validaDATA(data)
{
	var er = /^(0[1-9]|[12][0-9]|3[01])\/(0[1-9]|1[012])\/[12][0-9]{3}$/;
	var erMes = /^(0[13578]|1[02])$/;
	
	if(!data.match(er))
		return false;
		
	var dt = data.split("/");
	var dia = dt[0];
	var mes = dt[1];
	var ano = dt[2];
	
	var bissexto = validaANO(ano);
	
	if(mes==2)
		maxDia = bissexto ? 29 : 28;
	else if(mes.match(erMes))
		maxDia = 31;
	else
		maxDia = 30;

	if(dia > maxDia)
		return false;
		
	return true;
}

function validaMOEDA(valor)
{
	if (valor != '')
	{
		var v = valor.replace(',', "");
		var v2 = v.replace('.', "");
		if (isNumeric(v2))
			return true;
		else return false;
	}
	else return false;
}

function validaMOEDA3(valor)
{
	return validaMOEDA(valor);
}

function validaMOEDA4(valor)
{
	return validaMOEDA(valor);	
}

function validaCPF(cpf) 
{
	var cpf = new String(cpf);
    var aux_cpf = "";
    var erro = true;

	// retirar caracteres não numéricos
	aux_cpf = removeMask(cpf);

	if(aux_cpf.length!=11)
	{
		return false;
	}
    else 
    {
    	var sub = aux_cpf.substr(0,1);
    
    	if(aux_cpf.match(sub+'{11}'))
    		return false;
    		
    	var cpf1 = String(aux_cpf);
    	var cpf2 = cpf.substr(cpf.length-2,2);
      	var controle = "";
      	var start = 2;
      	var end = 10;

      	for(var i=1;i<=2;i++) 
      	{
      		var soma = 0;
      		
      		for(j=start;j<=end;j++)
      		{
      			soma += cpf1.substr((j-i-1),1)*(end+1+i-j);
      		}
        	if(i==2)
        	{
          		soma += digito * 2;
        	}
        	
        	digito = (soma * 10) % 11;
        	
        	if(digito==10)
        	{
          		digito = 0;
        	}
        	
        	controle += digito;
        	start = 3;
        	end = 11;
      	}
      	if(controle!=cpf2)
      	{
        	erro = false;
      	}
    }
  
	return erro;
}

function validaCNPJ(cnpj) 
{
	
	var erro = true; 
	var aux_cnpj = "";	
	var cnpj1=0 , cnpj2=0;
	var fator, controle;

	// retirar caracteres não numéricos

	aux_cnpj = removeMask(cnpj);
	
	if(aux_cnpj.length!=14)
	{
		return false;
	}
	else 
	{
		var sub = aux_cnpj.substr(0,1);
		
		if(aux_cnpj.match(sub+'{14}'))
			return false;
		
		cnpj1 = aux_cnpj.substr(0,12);
		cnpj2 = aux_cnpj.substr(aux_cnpj.length-2,2);
		fator = "543298765432";
		controle = "";
		
		for(j=0; j<2; j++) 
		{
			soma = 0;
			for(i=0; i<12; i++)
			{
				soma += cnpj1.substr(i,1) * fator.substr(i,1);
			}
			if(j==1)
			{
				soma += digito * 2;
			}
			
			digito = (soma * 10) % 11;
			
			if(digito==10)
			{
				digito = 0;
			}
			
			controle += digito;
			
			fator = "654329876543";
		} 
		if(controle != cnpj2)
		{
			erro = false;
		}
	} 
	return erro;
}

function _toFixed(valor)
{
	if(typeof valor == "object")
		return valor.value.Math.round(valor * 100) / 100;
	else if( typeof valor == "string" || typeof valor == 'number')
		return valor.Math.round(valor * 100) / 100;
}

function valorMoeda(campo)
{  
	var valor = campo.value;
	
	if(valor.length>14)
	{
		valor=valor.substr(0,14);
	}
	
	valor=valor.replace(/\D/g,"")
	valor=valor.replace(/(\d{1})(\d{8})$/,"$1.$2")
	valor=valor.replace(/(\d{1})(\d{5})$/,"$1.$2")
	valor=valor.replace(/(\d{1})(\d{1,2})$/,"$1,$2")
	campo.value = valor;
} 
// com 3 casas decimais
function valorMoeda3(campo)
{  
	var valor = campo.value;
	
	if(valor.length>14)
	{
		valor=valor.substr(0,14);
	}
	
	valor=valor.replace(/\D/g,"")
	valor=valor.replace(/(\d{1})(\d{12})$/,"$1.$2")
	valor=valor.replace(/(\d{1})(\d{9})$/,"$1.$2")
	valor=valor.replace(/(\d{1})(\d{6})$/,"$1.$2")
	valor=valor.replace(/(\d{1})(\d{3})$/,"$1,$2")
	campo.value = valor;
} 

// com 4 casas decimais
function valorMoeda4(campo)
{  
	var valor = campo.value;
	
	if(valor.length>14)
	{
		valor=valor.substr(0,14);
	}
	
	valor=valor.replace(/\D/g,"")
	valor=valor.replace(/(\d{1})(\d{10})$/,"$1.$2")
	valor=valor.replace(/(\d{1})(\d{7})$/,"$1.$2")
	valor=valor.replace(/(\d{1})(\d{4})$/,"$1,$2")
	campo.value = valor;
} 


function valorMoeda_antigo(campo)
{
	if (typeof campo == 'object') 
	{
		var objeto = true;
		var value = removeMask(campo.value);
	}
	else if (typeof campo == 'string' || typeof campo == 'number') 
	{
		var objeto = false;
		var campo = campo.toString();
		var value = removeMask(campo);
	}
	
	
	if(value.length > 17)
		value = value.substr(0, 17);
		
	var tam = value.length;
	
	if (tam <= 2)
		value = value;
	else if (tam > 2 && tam <=5)
		value = value.substr(0, tam-2) + ',' + value.substr(tam-2, tam);
	else if (tam >= 6 && tam <=8)
		value = value.substr(0, tam-5) + '.' + value.substr(tam-5, 3) + ',' + value.substr(tam-2, tam);
 	else if (tam >= 9 && tam <= 11)
 		value = value.substr(0, tam-8) + '.' + value.substr(tam-8, 3) + '.' + value.substr(tam-5, 3) + ',' + value.substr(tam-2, tam);
 	else if (tam >= 12 && tam <= 14)
 		value = value.substr(0, tam-11) + '.' + value.substr(tam-11, 3) + '.' + value.substr(tam-8, 3) + '.' + value.substr(tam-5, 3) + ',' + value.substr(tam-2, tam); 
 	else if (tam >= 15 && tam < 18) 
 		value = value.substr(0, tam-14) + '.' + value.substr(tam-14, 3) + '.' + value.substr(tam-11, 3) + '.' + value.substr(tam-8, 3) + '.' + value.substr(tam-5, 3) + ',' + value.substr(tam-2, tam);
		
	if(objeto)
		campo.value = value;
	else
		return value;
	
}

function removeMask(value)
{
	var valueLimpo='';
	var er = /[0-9]{1,1}/;	
	
	for(i=0; i < value.length; i++)
	{
		tmp = value.substring(i, i+1);
			
		//if(!isNaN(tmp))
		if(tmp.match(er))
		{
			valueLimpo+=tmp;
		}
	}
	
	return valueLimpo;
}

function reseta(form)
{
	if(typeof form != "object")
	{
		form = document.form;
	}
	
	for(i=0; i<form.length; i++)
	{
		if(form[i].type.match(/text|textarea|password|hidden|select/))
		{
			form[i].value = '';
			
			if(form[i].style.borderColor.match(/red/))
				evidencia(form[i]);
		}
	}
}

function pdf(page, form)
{
	var args = "";
	
	for(i=0; i<form.length; i++)
	{
		args+= "&"+form[i].name+"="+form[i].value;
	}
	
	window.open(page+args);
}

function pdf(page, form)
{
	var args = "";
	
	for(i=0; i<form.length; i++)
	{
		args+= "&"+form[i].name+"="+form[i].value;
	}
	
	window.open(page+args);
}

/**
 * Função para adicionar mascara ao campo CPF / CNPJ
 */

function addMask(obj)
{
	var value = obj.value;
	var nValue='';
	var valueLimpo='';
	var tmp;
	var cpf;
	var cnpj;
	var erro = false;
	
	/** retira a mascara se houver */
	value = removeMask(value);
	/**
	 * Se for um CPF
	 */
	if(value.length == 11)
	{
		for(i=0; i < value.length; i++)
		{
			nValue+= value.substring(i, i+1);
			if(i==2 || i==5)
			{
				nValue+="."
			}
			else if(i==8)
			{
				nValue+="-";
			}
		}
	}
	/**
	 * Se for um CNPJ
	 */
	else if(value.length == 14)
	{
		for(i=0; i< value.length; i++)
		{
			nValue+= value.substring(i, i+1);
			if(i==1 || i==4)
			{
				nValue+=".";
			}
			else if(i==11)
			{
				nValue+="-";
			}
			else if(i==7)
			{
				nValue+="/";
			}
		}
	}
	else
	{
		nValue = obj.value;
	}

	obj.value = nValue;
}

function addValidacao(obj)
{
	var valor = removeMask(obj.value)
	
	var tipo = valor.length == 14 ? 'cnpj' : 'cpf';
	obj.removeAttribute('rel');
	obj.setAttribute('rel', 'true_'+tipo);	
}

function findLabel(inputElementID) 
{
	arrLabels = document.getElementsByTagName('label');

	searchLoop:
	for (var i=0; i<arrLabels.length; i++) {
		if (arrLabels[i].getAttributeNode('for') && arrLabels[i].getAttributeNode('for').value == inputElementID) {				
			return arrLabels[i];
			break searchLoop;				
		}
	}		

}
	
	
/*
 * Função que muda a imagem ao lado do label dos inputs do tipo checkbox.
 * Adicionar a função no onclick
 * Parametros:
 * - Elemento: usar sempre "this"
 */
function changeChkBoxLabel(Element)  // passar Elemento = this
{
	labelElement = findLabel(Element.getAttributeNode('id').value);
	
	if(labelElement.className == 'CHECKBOX_CHECKED') {
		labelElement.className = "CHECKBOX_UNCHECKED";
	}
	else {
		labelElement.className = "CHECKBOX_CHECKED";
	}
}

/*
 * Função que muda a imagem ao lado do label dos inputs do tipo radio.
 * Adicionar a função no onclick
 * Parametros:
 * - Elemento: usar sempre "this"
 * - GrupoNome: nome do grupo de campos do tipo radio
 * - NroElementos: número de elementos do grupo
 */
function changeRadioLabel(Elemento, GrupoNome, NroElementos) 
{			 
		clicadoLabelElemento = findLabel(Elemento.getAttributeNode('id').value);
		clicadoInputElemento = Elemento;
		
		// desmarca todos os elementos do mesmo grupo deste Radio
		for (var i=1; i<=NroElementos; i++) {
			labelElemento = findLabel(GrupoNome+i);
			labelElemento.className = 'RADIO_UNCHECKED';
			get(GrupoNome+i).checked = false;
		}

		// marca o elemento selecionado
		clicadoLabelElemento.className = 'RADIO_CHECKED';
		// atribui o valor do radio selecionado para a variavel de retorno
		get(GrupoNome).value = clicadoInputElemento.value;

}

/* 
 * Função que detecta o nome a versao do navegador
 * Retorno uma array de duas posições
 * - Posição "nome": nome do navegador
 * - Posição "versao": versão do navegador
 */
function navegador()
{
	var ret = new Array(2);
	var nav = "";
	var ver = "";
	var app = navigator.appName;
	var age = navigator.userAgent;
	if (app == "Microsoft Internet Explorer")
	{
		nav = "ie";
		ver = age.substr(age.indexOf("MSIE")+5);
		ver = ver.substr(0,ver.indexOf("."));
	}
	if (app == "Opera")
	{
		nav = "opera";
		ver = age.substr(age.indexOf("Opera")+6);
		ver = ver.substr(0,ver.indexOf("."));
	}
	if (app == "Netscape")
	{
		if (age.indexOf("Navigator") >0)
		{
			nav = "netscape";
			ver = age.substr(age.indexOf("Navigator")+10);
			ver = ver.substr(0,ver.indexOf("."));
		}
		else if (age.indexOf("Firefox") >0)
		{
			nav = "firefox";
			ver = age.substr(age.indexOf("Firefox")+8);
			ver = ver.substr(0,ver.indexOf("."));
		}
		
		if (age.indexOf("Safari") >0)
		{
			nav = "safari";
			ver = age.substr(age.indexOf("Version")+8);
			ver = ver.substr(0,ver.indexOf("."));
		}
	}
	
	ret["nome"] = nav;
	ret["versao"] = ver;
	return ret;
}


function mudaAba(el, qtd)
{
	for(i=1; i <= qtd ; i++)
	{
		if (get('_li'+i).className != 'disable__')
			get('_li'+i).className = '';
		get('__ABA'+i).style.display = 'none';
	}
	
	el.className = 'active__';
	get('__ABA'+el.id.substr(3)).style.display = 'block';
}

function capsLock(el, e)
{
	kc = e.keyCode?e.keyCode:e.which;
	sk = e.shiftKey?e.shiftKey:((kc == 16)?true:false);
	
	if(((kc >= 65 && kc <= 90) && !sk)||((kc >= 97 && kc <= 122) && sk))
		get(el).style.display = 'block';
	else
		get(el).style.display = 'none';
}

function timeStamp()
{
	return parseInt(new Date().getTime().toString().substring(0, 10));
}

function flash(arquivo, id, width, height)
{
	var swf = '';
	var li = get(id);
	
		swf = "<object classid='clsid:d27cdb6e-ae6d-11cf-96b8-444553540000' codebase='http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0' width='"+width+"' height='"+height+"' id=''>";
		swf+= "<param name='allowScriptAccess' value='sameDomain' />";
		swf+= "<param name='movie' value='"+arquivo+"' />";
		swf+= "<param name='quality' value='high' />";
		swf+= "<param name='wmode' value='transparent' />";
		swf+= "<param name='scale' value='noscale' />";
		swf+= "<embed src='"+arquivo+"' quality='high' wmode='transparent' width='"+width+"' height='"+height+"'name='menu_topo' allowScriptAccess='sameDomain' type='application/x-shockwave-flash' pluginspage='http://www.macromedia.com/go/getflashplayer' />";
		swf+= "</object>";
	
		li.innerHTML = swf;
}

function addFavoritos(url, title)
{
	if (window.sidebar)
	{
		window.sidebar.addPanel(title, url,"");
	}
	else if (window.external)
	{
		window.external.AddFavorite(url, title);
	}
	else if (window.opera && window.print)
	{
		return true;
	}
}

function mostraObjetoPropriedades(obj) {
  var output = "" ;
  for (var prop in obj) {
    output += prop + " = " + obj[prop] + "<br />" ;
  }
  return output ;
}

function trim(str, chars) {
    return ltrim(rtrim(str, chars), chars);
}

function ltrim(str, chars) {
    chars = chars || "\\s";
    return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}

function rtrim(str, chars) {
    chars = chars || "\\s";
    return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}

/* Returns the class name of the argument or undefined if 
   it's not a valid JavaScript object. 
*/  
function getObjectClass(obj) {  
    if (obj && obj.constructor && obj.constructor.toString) {  
        var arr = obj.constructor.toString().match(  
            /function\s*(\w+)/);  
  
        if (arr && arr.length == 2) {  
            return arr[1];  
        }  
    }  
  
    return undefined;  
}  
  
/* Serializes the given argument, PHP-style. 
 
   The type mapping is as follows: 
 
   JavaScript Type    PHP Type 
   ---------------    -------- 
   Number             Integer or Decimal 
   String             String 
   Boolean            Boolean 
   Array              Array 
   Object             Object 
   undefined          Null 
 
   The special JavaScript object null also becomes PHP Null. 
   This function may not handle associative arrays or array 
   objects with additional properties well. Returns false when 
   called with an argument that can't be represented in PHP. 
*/ 
function phpSerialize(val) {  
   switch (typeof(val)) {  
    case "number":  
        if (val == NaN || val == Infinity) {  
            return false;  
        }  
 
        return (Math.floor(val) == val ? "i" : "d") + ":" +  
            val + ";";  
  
    case "string":  
        return "s:" + val.length + ":\"" + val + "\";";  
  
    case "boolean":  
        return "b:" + (val ? "1" : "0") + ";";  
  
    case "object":  
        if (val == null) {  
           return "N;";  
        } else if (val instanceof Array) {  
            var idxobj = { idx: -1 };  
  
            return "a:" + val.length + ":{" + val.map(  
               function (item) {  
                    this.idx++;  
 
                   var ser = phpSerialize(item);  
 
                    return ser ?  
                        phpSerialize(this.idx) + ser :  
                        false;  
                }, idxobj).filter(  
                function (item) {  
                    return item;  
                }).join("") + "}";  
        } else {  
            var class_name = getObjectClass(val);  
  
            if (class_name == undefined) {  
                return false;  
            }  
  
            var props = new Array();  
  
            for (var prop in val) {  
                var ser = phpSerialize(val[prop]);  
  
                if (ser) {  
                    props.push(phpSerialize(prop) + ser);  
                }  
            }  
  
            return "O:" + class_name.length + ":\"" +  
                class_name + "\":" + props.length + ":{" +  
                props.join("") + "}";  
        }  
    case "undefined":  
        return "N;";  
    }  
  
    return false;  
}

function phpSerialize2( mixed_value ) 
{
    // http://kevin.vanzonneveld.net
    // +   original by: Arpad Ray (mailto:arpad@php.net)
    // +   improved by: Dino
    // +   bugfixed by: Andrej Pavlovic
    // +   bugfixed by: Garagoth
    // +      input by: DtTvB (http://dt.in.th/2008-09-16.string-length-in-bytes.html)
    // +   bugfixed by: Russell Walker
    // %          note: We feel the main purpose of this function should be to ease the transport of data between php & js
    // %          note: Aiming for PHP-compatibility, we have to translate objects to arrays
    // *     example 1: serialize(['Kevin', 'van', 'Zonneveld']);
    // *     returns 1: 'a:3:{i:0;s:5:"Kevin";i:1;s:3:"van";i:2;s:9:"Zonneveld";}'
    // *     example 2: serialize({firstName: 'Kevin', midName: 'van', surName: 'Zonneveld'});
    // *     returns 2: 'a:3:{s:9:"firstName";s:5:"Kevin";s:7:"midName";s:3:"van";s:7:"surName";s:9:"Zonneveld";}'
 
    var _getType = function( inp ) {
        var type = typeof inp, match;
        var key;
        if (type == 'object' && !inp) {
            return 'null';
        }
        if (type == "object") {
            if (!inp.constructor) {
                return 'object';
            }
            var cons = inp.constructor.toString();
            match = cons.match(/(\w+)\(/);
            if (match) {
                cons = match[1].toLowerCase();
            }
            var types = ["boolean", "number", "string", "array"];
            for (key in types) {
                if (cons == types[key]) {
                    type = types[key];
                    break;
                }
            }
        }
        return type;
    };
    var type = _getType(mixed_value);
    var val, ktype = '';
    
    switch (type) {
        case "function": 
            val = ""; 
            break;
        case "undefined":
            val = "N";
            break;
        case "boolean":
            val = "b:" + (mixed_value ? "1" : "0");
            break;
        case "number":
            val = (Math.round(mixed_value) == mixed_value ? "i" : "d") + ":" + mixed_value;
            break;
        case "string":
            val = "s:" + encodeURIComponent(mixed_value).replace(/%../g, 'x').length + ":\"" + mixed_value + "\"";
            break;
        case "array":
        case "object":
            val = "a";
            var count = 0;
            var vals = "";
            var okey;
            var key;
            for (key in mixed_value) {
                ktype = _getType(mixed_value[key]);
                if (ktype == "function") { 
                    continue; 
                }
                
                okey = (key.match(/^[0-9]+$/) ? parseInt(key, 10) : key);
                vals += phpSerialize2(okey) +
                        phpSerialize2(mixed_value[key]);
                count++;
            }
            val += ":" + count + ":{" + vals + "}";
            break;
    }
    if (type != "object" && type != "array") {
        val += ";";
    }
    return val;
}

function utf8_encode(argString) 
{
    // Encodes an ISO-8859-1 string to UTF-8  
    // 
    // version: 909.322
    // discuss at: http://phpjs.org/functions/utf8_encode
    // +   original by: Webtoolkit.info (http://www.webtoolkit.info/)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: sowberry
    // +    tweaked by: Jack
    // +   bugfixed by: Onno Marsman
    // +   improved by: Yves Sucaet
    // +   bugfixed by: Onno Marsman
    // +   bugfixed by: Ulrich
    // *     example 1: utf8_encode('Kevin van Zonneveld');
    // *     returns 1: 'Kevin van Zonneveld'
    var string = (argString+''); // .replace(/\r\n/g, "\n").replace(/\r/g, "\n");

    var utftext = "";
    var start, end;
    var stringl = 0;

    start = end = 0;
    stringl = string.length;
    for (var n = 0; n < stringl; n++) {
        var c1 = string.charCodeAt(n);
        var enc = null;

        if (c1 < 128) {
            end++;
        } else if (c1 > 127 && c1 < 2048) {
            enc = String.fromCharCode((c1 >> 6) | 192) + String.fromCharCode((c1 & 63) | 128);
        } else {
            enc = String.fromCharCode((c1 >> 12) | 224) + String.fromCharCode(((c1 >> 6) & 63) | 128) + String.fromCharCode((c1 & 63) | 128);
        }
        if (enc !== null) {
            if (end > start) {
                utftext += string.substring(start, end);
            }
            utftext += enc;
            start = end = n+1;
        }
    }

    if (end > start) {
        utftext += string.substring(start, string.length);
    }

    return utftext;
}

function phpSerialize3(mixed_value) 
{
    // Returns a string representation of variable (which can later be unserialized)  
    // 
    // version: 910.813
    // discuss at: http://phpjs.org/functions/serialize
    // +   original by: Arpad Ray (mailto:arpad@php.net)
    // +   improved by: Dino
    // +   bugfixed by: Andrej Pavlovic
    // +   bugfixed by: Garagoth
    // +      input by: DtTvB (http://dt.in.th/2008-09-16.string-length-in-bytes.html)
    // +   bugfixed by: Russell Walker (http://www.nbill.co.uk/)
    // +   bugfixed by: Jamie Beck (http://www.terabit.ca/)
    // +      input by: Martin (http://www.erlenwiese.de/)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // -    depends on: utf8_encode
    // %          note: We feel the main purpose of this function should be to ease the transport of data between php & js
    // %          note: Aiming for PHP-compatibility, we have to translate objects to arrays
    // *     example 1: serialize(['Kevin', 'van', 'Zonneveld']);
    // *     returns 1: 'a:3:{i:0;s:5:"Kevin";i:1;s:3:"van";i:2;s:9:"Zonneveld";}'
    // *     example 2: serialize({firstName: 'Kevin', midName: 'van', surName: 'Zonneveld'});
    // *     returns 2: 'a:3:{s:9:"firstName";s:5:"Kevin";s:7:"midName";s:3:"van";s:7:"surName";s:9:"Zonneveld";}'
    var _getType = function (inp) {
        var type = typeof inp, match;
        var key;
        if (type == 'object' && !inp) {
            return 'null';
        }
        if (type == "object") {
            if (!inp.constructor) {
                return 'object';
            }
            var cons = inp.constructor.toString();
            match = cons.match(/(\w+)\(/);
            if (match) {
                cons = match[1].toLowerCase();
            }
            var types = ["boolean", "number", "string", "array"];
            for (key in types) {
                if (cons == types[key]) {
                    type = types[key];
                    break;
                }
            }
        }
        return type;
    };
    var type = _getType(mixed_value);
    var val, ktype = '';
    
    switch (type) {
        case "function": 
            val = ""; 
            break;
        case "boolean":
            val = "b:" + (mixed_value ? "1" : "0");
            break;
        case "number":
            val = (Math.round(mixed_value) == mixed_value ? "i" : "d") + ":" + mixed_value;
            break;
        case "string":
            mixed_value = this.utf8_encode(mixed_value);
//            val = "s:" + encodeURIComponent(mixed_value).replace(/%../g, 'x').length + ":\"" + mixed_value + "\"";
            val = "s:" + mixed_value.length + ":\"" + mixed_value + "\"";
            break;
        case "array":
        case "object":
            val = "a";
            /*
            if (type == "object") {
                var objname = mixed_value.constructor.toString().match(/(\w+)\(\)/);
                if (objname == undefined) {
                    return;
                }
                objname[1] = this.serialize(objname[1]);
                val = "O" + objname[1].substring(1, objname[1].length - 1);
            }
            */
            var count = 0;
            var vals = "";
            var okey;
            var key;
            for (key in mixed_value) {
                ktype = _getType(mixed_value[key]);
                if (ktype == "function") { 
                    continue; 
                }
                
                okey = (key.match(/^[0-9]+$/) ? parseInt(key, 10) : key);
                vals += this.phpSerialize3(okey) +
                        this.phpSerialize3(mixed_value[key]);
                count++;
            }
            val += ":" + count + ":{" + vals + "}";
            break;
        case "undefined": // Fall-through
        default: // if the JS object has a property which contains a null value, the string cannot be unserialized by PHP
            val = "N";
            break;
    }
    if (type != "object" && type != "array") {
        val += ";";
    }
    return val;
}

function number_format (number, decimals, dec_point, thousands_sep) {
    // Formats a number with grouped thousands
    //
    // version: 906.1806
    // discuss at: http://phpjs.org/functions/number_format
    // +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +     bugfix by: Michael White (http://getsprink.com)
    // +     bugfix by: Benjamin Lupton
    // +     bugfix by: Allan Jensen (http://www.winternet.no)
    // +    revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +     bugfix by: Howard Yeend
    // +    revised by: Luke Smith (http://lucassmith.name)
    // +     bugfix by: Diogo Resende
    // +     bugfix by: Rival
    // +     input by: Kheang Hok Chin (http://www.distantia.ca/)
    // +     improved by: davook
    // +     improved by: Brett Zamir (http://brett-zamir.me)
    // +     input by: Jay Klehr
    // +     improved by: Brett Zamir (http://brett-zamir.me)
    // +     input by: Amir Habibi (http://www.residence-mixte.com/)
    // +     bugfix by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: number_format(1234.56);
    // *     returns 1: '1,235'
    // *     example 2: number_format(1234.56, 2, ',', ' ');
    // *     returns 2: '1 234,56'
    // *     example 3: number_format(1234.5678, 2, '.', '');
    // *     returns 3: '1234.57'
    // *     example 4: number_format(67, 2, ',', '.');
    // *     returns 4: '67,00'
    // *     example 5: number_format(1000);
    // *     returns 5: '1,000'
    // *     example 6: number_format(67.311, 2);
    // *     returns 6: '67.31'
    // *     example 7: number_format(1000.55, 1);
    // *     returns 7: '1,000.6'
    // *     example 8: number_format(67000, 5, ',', '.');
    // *     returns 8: '67.000,00000'
    // *     example 9: number_format(0.9, 0);
    // *     returns 9: '1'
    // *     example 10: number_format('1.20', 2);
    // *     returns 10: '1.20'
    // *     example 11: number_format('1.20', 4);
    // *     returns 11: '1.2000'
    // *     example 12: number_format('1.2000', 3);
    // *     returns 12: '1.200'
    var n = number, prec = decimals;

    var toFixedFix = function (n,prec) {
        var k = Math.pow(10,prec);
        return (Math.round(n*k)/k).toString();
    };

    n = !isFinite(+n) ? 0 : +n;
    prec = !isFinite(+prec) ? 0 : Math.abs(prec);
    var sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep;
    var dec = (typeof dec_point === 'undefined') ? '.' : dec_point;

    var s = (prec > 0) ? toFixedFix(n, prec) : toFixedFix(Math.round(n), prec); //fix for IE parseFloat(0.55).toFixed(0) = 0;

    var abs = toFixedFix(Math.abs(n), prec);
    var _, i;

    if (abs >= 1000) {
        _ = abs.split(/\D/);
        i = _[0].length % 3 || 3;

        _[0] = s.slice(0,i + (n < 0)) +
              _[0].slice(i).replace(/(\d{3})/g, sep+'$1');
        s = _.join(dec);
    } else {
        s = s.replace('.', dec);
    }

    var decPos = s.indexOf(dec);
    if (prec >= 1 && decPos !== -1 && (s.length-decPos-1) < prec) {
        s += new Array(prec-(s.length-decPos-1)).join(0)+'0';
    }
    else if (prec >= 1 && decPos === -1) {
        s += dec+new Array(prec).join(0)+'0';
    }
    return s;
}

function nl2br (str, is_xhtml) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Philip Peterson
    // +   improved by: Onno Marsman
    // +   improved by: Atli Þór
    // +   bugfixed by: Onno Marsman
    // +      input by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: nl2br('Kevin\nvan\nZonneveld');
    // *     returns 1: 'Kevin<br />\nvan<br />\nZonneveld'
    // *     example 2: nl2br("\nOne\nTwo\n\nThree\n", false);
    // *     returns 2: '<br>\nOne<br>\nTwo<br>\n<br>\nThree<br>\n'
    // *     example 3: nl2br("\nOne\nTwo\n\nThree\n", true);
    // *     returns 3: '<br />\nOne<br />\nTwo<br />\n<br />\nThree<br />\n'
 
    var breakTag = '';
 
    breakTag = '<br />';
    if (typeof is_xhtml != 'undefined' && !is_xhtml) {
        breakTag = '<br>';
    }
 
    return (str + '').replace(/([^>]?)\n/g, '$1'+ breakTag +'\n');
}

/*
 * Função de delay
 */
function delay(millis)
{
	var date = new Date();
	var curDate = null;

	do { curDate = new Date(); }
	while(curDate-date < millis);
} 