function formataMoeda(objTextBox, SeparadorMilesimo, SeparadorDecimal, e) //USO: <input type="text" onKeyPress="return(formataMoeda(this,'','.',event))" />
{
	var sep = 0;
	var key = '';
	var i = j = 0;
	var len = len2 = 0;
	var strCheck = '0123456789';
	var aux = aux2 = '';
	var whichCode = (window.Event) ? e.which : e.keyCode;    
	// 13=enter, 8=backspace as demais retornam 0(zero)
	// whichCode==0 faz com que seja possivel usar todas as teclas como delete, setas, etc    
	if ((whichCode == 13) || (whichCode == 0) || (whichCode == 8))
		return true;
	key = String.fromCharCode(whichCode); // Valor para o código da Chave
 
 
	if (strCheck.indexOf(key) == -1) 
		return false; // Chave inválida
	len = objTextBox.value.length;
	for(i = 0; i < len; i++)
		if ((objTextBox.value.charAt(i) != '0') && (objTextBox.value.charAt(i) != SeparadorDecimal)) 
			break;
	aux = '';
	for(; i < len; i++)
		if (strCheck.indexOf(objTextBox.value.charAt(i))!=-1) 
			aux += objTextBox.value.charAt(i);
	aux += key;
	len = aux.length;
	if (len == 0) 
		objTextBox.value = '';
	if (len == 1) 
		objTextBox.value = '0'+ SeparadorDecimal + '0' + aux;
	if (len == 2) 
		objTextBox.value = '0'+ SeparadorDecimal + aux;
	if (len > 2) {
		aux2 = '';
		for (j = 0, i = len - 3; i >= 0; i--) {
			if (j == 3) {
				aux2 += SeparadorMilesimo;
				j = 0;
			}
			aux2 += aux.charAt(i);
			j++;
		}
		objTextBox.value = '';
		len2 = aux2.length;
		for (i = len2 - 1; i >= 0; i--)
			objTextBox.value += aux2.charAt(i);
		objTextBox.value += SeparadorDecimal + aux.substr(len - 2, len);
	}
	return false;
}
function SomenteNumeros(e) // USO: <input type="text" onkeypress="javascript:return SomenteNumeros(event);">
{
	var tecla=new Number();
	
	if(window.event)
	{
		tecla = e.keyCode;
	}
	else if(e.which)
	{
		tecla = e.which;
	}
	else
	{
		return true;
	}
	
	if(((tecla < 48) || (tecla > 57)) && (tecla!=8) )
	{
		return false;
	}
}
function SomenteLetras(e) // USO: <input type="text" onkeypress="javascript:return SomenteLetras(event);">
{
	var tecla=new Number();
	
	if(window.event)
	{
		tecla = e.keyCode;
	}
	else if(e.which)
	{
		tecla = e.which;
	}
	else
	{
		return true;
	}
	
	if( ((tecla < 65) || (tecla > 90)) && ((tecla < 97) || (tecla > 122)) && (tecla!=8) )
	{
		return false;
	}
}
function SomenteEmail(e) // USO: <input type="text" onkeypress="javascript:return SomenteEmail(event);">
{
	var tecla=new Number();
	
	if(window.event)
	{
		tecla = e.keyCode;
	}
	else if(e.which)
	{
		tecla = e.which;
	}
	else
	{
		return true;
	}
	
	if( ((tecla < 65) || (tecla > 90)) && ((tecla < 97) || (tecla > 122)) && ((tecla < 48) || (tecla > 57)) && (tecla!=8) && (tecla!=45) && (tecla!=46) && (tecla!=95) )
	{
		return false;
	}
}
function descricaoimagemgaleria(imagem)
{
	AbreDivPopup('div=AlertaAzul&largura=350&altura=250&modal=false');
	$('.AlertaAzulTitulo').html('<img src="/_img/iconeescrever.gif" align="absmiddle">&nbsp;Configurações');
	var Url = 'pg=descricaoimagemgaleria&imagem='+imagem;
	$.ajax(
	{
		type: 'POST',
		url: '/ajax.php',
		dataType: 'json',
		data: Url,
		success: function(Retorno)
		{
			$('.AlertaAzulConteudo').html(Retorno.Html);
		}
	});
}
function salvadescricaoimagemgaleria()
{
	var Url = 'pg=salvadescricaoimagemgaleria&txtDescricao='+escape($('#txtDescricao').val())+'&txtOrdem='+$('#txtOrdem').val()+'&idimagem='+$('#idimagem').val();
	$.ajax(
	{
		type: 'POST',
		url: '/ajax.php',
		dataType: 'json',
		data: Url,
		success: function(Retorno)
		{
			$('.MsgAjaxLocal').livequery(function()
			{
				$(this).html('').html(Retorno.Msg).slideToggle();
				setTimeout(function()
				{
					$('.MsgAjaxLocal').slideToggle().expire();
				}, 4000);
			});
		}
	});
}

var src;
function VerImagem()
{
	AbrePopupTopLeft('/?pg=verimagem&src='+src, 'IMAGEM', 100, 100, 0, 0, 0);
}
function AbreModelos(tipo)
{
	var pasta;
	if( tipo == 'topos' )
	{
		pasta = 'upload/modelos/topo';
	}
	else if( tipo == 'backgrounddosite' )
	{
		pasta = 'upload/modelos/fundo';
	}
	else if( tipo == 'backgrounddotopo' )
	{
		pasta = 'upload/modelos/fundo';
	}
	else if( tipo == 'backgrounddoconteudo' )
	{
		pasta = 'upload/modelos/fundo';
	}
	
	w = 400;
	h = 300;
	p = 10;
	
	Popin('.divUso', w, h, p);
	$('.divUso').html('<iframe src="/?pg=modelos&tipo='+tipo+'&pasta='+base64_encode(pasta)+'" frameborder="0" marginheight="0" marginwidth="0" scrolling="auto" width="100%" height="'+(h-30)+'"></iframe>');
}
function SubtraiOrdem(obj)
{
	if( $('#'+obj).val() > 0 )
	{
		$('#'+obj).val($('#'+obj).val()-1);
	}
}
function SomaOrdem(obj)
{
	if( $('#'+obj).val() < 999 )
	{
		$('#'+obj).val(parseInt($('#'+obj).val())+1);
	}
}
function StatusDoElementoDaGrid(acao, id)
{
	Url = 'pg=statusdoelementodagrid&'+acao;
	$.ajax(
	{
		type: 'POST',
		url: '/ajax.php',
		dataType: 'json',
		data: Url,
		success: function(Retorno)
		{
			//alert(Retorno.Msg);
			$('.conteudo').html(Retorno.Html);
		}
	});
}
function mudastatus(url)
{
	Url = 'pg=mudastatus&'+url;
	$.ajax(
	{
		type: 'POST',
		url: '/ajax.php',
		dataType: 'json',
		data: Url,
		success: function(Retorno)
		{
			//alert(Retorno.Msg);
			$('.conteudo').html(Retorno.Html);
		}
	});
}
function adicionavotoenquete()
{
	Url = 'pg=adicionavotoenquete&id='+$(".optRespostaDaEnquete[type='radio']:checked").val();
	$.ajax(
	{
		type: 'POST',
		url: '/ajax.php',
		dataType: 'json',
		data: Url,
		success: function(Retorno)
		{
			alert(Retorno.Status);
		}
	});
}
function resultadodaenquete()
{
	var Url = 'pg=resultadodaenquete';
	$.ajax(
	{
		type: 'POST',
		url: '/ajax.php',
		dataType: 'json',
		data: Url,
		beforeSend: function()
		{
			Popin('.BarraCarregando', 250, 68, 0);
		},
		success: function(Retorno)
		{
			Popin('.divUso', 400, 230, 10);
			$('.divUso').html(Retorno.Html);
		}
	});
}
function MostraNoticia(id)
{
	Popin('.divUso', 500, 300, 10);
	$('.divUso').load(escape('/noticiasinternas/'+id));
}
function MostraNoticiaDeTodas(id)
{
	Popin('.divUso', 500, 300, 10);
	$('.divUso').load(escape(id));
}
function dadoswidget(id)
{
	AbreDivPopup('div=AlertaAzul&largura=400&altura=200&modal=false');
	$.ajax(
	{
		type: 'POST',
		url: '/ajax.php',
		dataType: 'json',
		data: 'pg=dadoswidget&id='+id,
		beforeSend: function()
		{
			//AbreDivPopup('largura=250&altura=68&modal=true');
			//$('.DivPopup').css({textAlign: 'center'}).html($('.BarraCarregando').html());
		},
		success: function(Retorno)
		{
			$('.AlertaAzulConteudo').html(Retorno.Html);
			PosicaoDivPopup();
		}
	});
}
function salvadadoswidget()
{
	var Url = 'pg=salvadadoswidget&'+$('.AlertaAzulConteudo input,select').serialize();
	$.ajax(
	{
		type: 'POST',
		url: '/ajax.php',
		dataType: 'json',
		data: Url,
		beforeSend: function()
		{
			//AbreDivPopup('largura=250&altura=68&modal=true');
			//$('.DivPopup').css({textAlign: 'center'}).html($('.BarraCarregando').html());
		},
		success: function(Retorno)
		{
			$('.MsgAjaxLocal').livequery(function()
			{
				$(this).html('').html(Retorno.Msg).slideToggle();
				setTimeout(function()
				{
					$('.MsgAjaxLocal').slideToggle().expire();
				}, 4000);
			});
		}
	});
}
function editarpagina()
{
	AbreDivPopup('largura=250&altura=68&modal=true');
	$('.DivPopup').css({textAlign: 'center'}).html($('.BarraCarregando').html());
	
	var Url = 'pg=editarpagina&id='+$('#id').val()+'&'+$('.conteudo input,select').serialize()+'&txtConteudo='+encodeURIComponent(tinyMCE.get('txtConteudo').getContent());
	$.ajax(
	{
		type: 'POST',
		url: '/ajax.php',
		dataType: 'json',
		data: Url,
		success: function(Retorno)
		{
			$('.DivPopup').css({textAlign: 'left', width: '275px', padding: '5px'}).show().html(Retorno.Msg);
			LarguraDivPopup = 275;
			//AlturaDivPopup = 200;
			PosicaoDivPopup();
			setTimeout('FechaDivPopup()', 1000);
		}
	});
}
function editar(acao)
{
	var id;
	var contador = 0;
	$("input[type='checkbox']").each(function()
	{
		if( $(this).attr('checked') == true )
		{
			id = $(this).val();
			contador++;
		}
	});

	if( contador == 0 )
	{
		alert('AVISO!\n\nSelecione pelo menos 1 registro para executar a ação.');
	}
	else if( contador > 1 )
	{
		alert('AVISO!\n\nVocê só pode editar apenas 1 registro por vez.');
	}
	else
	{
		window.location = '?pg='+acao+'&id='+id;
	}
}
function AdicionaTemplate(id)
{
	if (confirm("ATENÇÃO:\n\nVocê já habilitou o (cadeado) nas opções: Páginas, Topos, Rodapé, Menus, BG do Topo, BG do Site (dentro), BG do Site (fora) e Topo-Conteúdo, que você deseja preservar?"))
	{
		if (confirm('Você realmente deseja adicionar este template ?             '))
		{
			Url = 'pg=adicionamodelos&id='+id;
			$.ajax(
			{
				type: 'POST',
				url: '/ajax.php',
				dataType: 'json',
				data: Url,
				beforeSend: function()
				{
					AbreDivPopup('largura=250&altura=68&modal=true');
					$('.DivPopup').css({textAlign: 'center'}).html($('.BarraCarregando').html());
				},
				success: function(Retorno)
				{
					$('.DivPopup').css({textAlign: 'left', width: '275px', padding: '5px'}).html(Retorno.Msg);
					LarguraDivPopup = 275;
					PosicaoDivPopup();
					setTimeout('FechaDivPopup();window.location="/";', 1000);
				}
			});
		}
	}
}
function excluir(acao)
{
	var id = '';
	var contador = 0;
	$("input[type='checkbox']").each(function()
	{
		if( $(this).attr('checked') == true )
		{
			id += $(this).val()+',';
			contador++;
		}
	});
	if( contador == 0 )
	{
		alert('AVISO!\n\nSelecione pelo menos 1 registro para executar a ação.\t\n');
	}
	else
	{
		id = id.substring(0,id.length-1);
		if (confirm('Você realmente deseja excluir este(s) registro(s) ?             '))
		{
			Url = 'pg=excluir'+acao+'&id='+id;
			$.ajax(
			{
				type: 'POST',
				url: '/ajax.php',
				dataType: 'json',
				data: Url,
				beforeSend: function()
				{
					AbreDivPopup('largura=250&altura=68&modal=true');
					$('.DivPopup').css({textAlign: 'center'}).html($('.BarraCarregando').html());
				},
				success: function(Retorno)
				{
					$('.DivPopup').css({textAlign: 'left', width: '275px', padding: '5px'}).html(Retorno.Msg);
					$('.conteudo').html(Retorno.Html);
					LarguraDivPopup = 275;
					//AlturaDivPopup = 200;
					PosicaoDivPopup();
					setTimeout('FechaDivPopup()', 1000);
				}
			});
		}
	}
}
function excluirindividualmente(id, acao)
{
		if (confirm('Você realmente deseja excluir este registro ?             '))
		{
			Url = 'pg=excluir'+acao+'&id='+id;
			$.ajax(
			{
				type: 'POST',
				url: '/ajax.php',
				dataType: 'json',
				data: Url,
				beforeSend: function()
				{
					AbreDivPopup('largura=250&altura=68&modal=true');
					$('.DivPopup').css({textAlign: 'center'}).html($('.BarraCarregando').html());
				},
				success: function(Retorno)
				{
					$('.DivPopup').css({textAlign: 'left', width: '275px', padding: '5px'}).html(Retorno.Msg);
					$('.conteudo').html(Retorno.Html);
					LarguraDivPopup = 275;
					//AlturaDivPopup = 200;
					PosicaoDivPopup();
					setTimeout('FechaDivPopup()', 1000);
				}
			});
		}
}
function MostraBiblia()
{
	if( $('.BibliaLivro').val() != '-' )
	{
		Url = '/biblia/'+$('.BibliaLivro').val()+'/'+$('.BibliaCapitulos').val();
		if( $('.BibliaVersiculos').val() )
		{
			Url = Url+'/'+$('.BibliaVersiculos').val();
		}
		window.location = escape(Url);
		//alert(Url);
	}
}
function filemanagerKB(field_name, url, type, win)
{
	//alert("Field_Name: " + field_name + "\nURL: " + url + "\nType: " + type + "\nWin: " + win); // debug/testing
	
	/* If you work with sessions in PHP and your client doesn't accept cookies you might need to carry
	the session name and session ID in the request string (can look like this: "?PHPSESSID=88p0n70s9dsknra96qhuk6etm5").
	These lines of code extract the necessary parameters and add them back to the filebrowser URL again. */
	
	var cmsURL = '/?pg=filemanager&pasta='+base64_encode('upload');    // script URL - use an absolute path!
	if (cmsURL.indexOf("?") < 0)
	{
		//add the type as the only query parameter
		cmsURL = cmsURL+'&tipo='+base64_encode(type);
	}
	else
	{
		//add the type as an additional query parameter
		// (PHP session ID is now included if there is one at all)
		cmsURL = cmsURL+'&tipo='+base64_encode(type);
	}
	tinyMCE.activeEditor.windowManager.open(
	{
			file : cmsURL,
			title : '',
			width : 450,  // Your dimensions may differ - toy around with them!
			height : 400,
			resizable : "yes",
			inline : "yes",  // This parameter only has an effect if you use the inlinepopups plugin!
			close_previous : "yes"
		},
		{
			window : win,
			input : field_name,
			resizable : "yes",
			inline : "yes",
			type : type
		}
	);
	return false;
}
function URLencode( sStr )
{
	return escape( sStr ).replace( /\+/g, '%2C' ).replace( /\"/g,'%22' ).replace( /\'/g, '%27' );
}
function trim( str )
{
	return str.replace( /^\s*|\s*$/g,"" );
}
/**
* Clone da função do PHP number_format()
*
* @param		int/string		-> Numero ao qual se quer formatar
* @param		int				-> Numero de casas decimais
* @param		string			-> Separador decimal
* @param		string			-> Separador Milheiro
* @return 		string
*/
function number_format(number, decimals, dec_point, thousands_sep)
{
	var exponent  = "";
	var numberstr = number.toString ();
	var eindex    = numberstr.indexOf ("e");

	if(numberstr.match(',') && numberstr.match('.')) {
		return numberstr;
	}

	if (eindex > -1)
	{
		exponent = numberstr.substring (eindex);
		number = parseFloat (numberstr.substring (0, eindex));
	}

	if (decimals != null)
	{
		var temp = Math.pow (10, decimals);
		number   = Math.round (number * temp) / temp;
	}

	var sign       = number < 0 ? "-" : "";
	var integer    = (number > 0 ?	Math.floor (number) : Math.abs (Math.ceil (number))).toString ();
	var fractional = number.toString().substring (integer.length + sign.length);

	dec_point  = dec_point != null ? dec_point : ".";
	fractional = decimals != null && decimals > 0 || fractional.length > 1 ? (dec_point + fractional.substring (1)) : "";

	if (decimals != null && decimals > 0)
	{
		for (i = fractional.length - 1, z = decimals; i < z; ++i)
		fractional += "0";
	}

	thousands_sep = (thousands_sep != dec_point || fractional.length == 0) ? thousands_sep : null;

	if (thousands_sep != null && thousands_sep != "")
	{
		for (i = integer.length - 3; i > 0; i -= 3)
		integer = integer.substring (0 , i) + thousands_sep + integer.substring (i);
	}

	return sign + integer + fractional + exponent;
}

function getURLParam(strParamName){
  var strReturn = "";
  var strHref = window.location.href;
  if ( strHref.indexOf("?") > -1 ){
    var strQueryString = strHref.substr(strHref.indexOf("?")).toLowerCase();
    var aQueryString = strQueryString.split("&");
    for ( var iParam = 0; iParam < aQueryString.length; iParam++ ){
      if (aQueryString[iParam].indexOf(strParamName.toLowerCase() + "=") > -1 ){
        var aParam = aQueryString[iParam].split("=");
        strReturn = aParam[1];
        break;
      }
    }
  }
  return unescape(strReturn);
}
function checkPopupBlocker()
{
	 var mine = window.open('','','width=1,height=1,left=0,top=0,scrollbars=no');
	 if(mine) {
	    var popUpsBlocked = false;
	 } else {
	    var popUpsBlocked = true;
	 }

	 mine.close();

	 return popUpsBlocked;
}
function escapeAll(string)
{
    var decHex = function(dec) {
        var chars = '0123456789ABCDEF';
        
        return chars.charAt(Math.floor(dec / 16)) + chars.charAt(dec % 16);
    };
    
    var out = '';
    
    for(var i = 0; i < string.length; i++) {
        var code = string.charCodeAt(i);
        
        if(code > 255)
            out += '%3F'; //coloca uma interrogacao caso o caractere seja desconhecido
        else
            out += '%' + decHex(code);
    }
    return out;
}
function Moeda2Numero(Num)
{
	texto = ((Num.toString()).replace('.','')).replace(',','.');
	return parseFloat(texto);
}
function Url2Array(query)
{
   var ArrayUrl = {};
   if ( ! query ) {return ArrayUrl;}// return empty object
   var Pairs = query.split(/[;&]/);
   for ( var i = 0; i < Pairs.length; i++ ) {
      var KeyVal = Pairs[i].split('=');
      if ( ! KeyVal || KeyVal.length != 2 ) {continue;}
      var key = unescape( KeyVal[0] );
      var val = unescape( KeyVal[1] );
      val = val.replace(/\+/g, ' ');
      ArrayUrl[key] = val;
   }
   return ArrayUrl;
}
function PegaExtensao(Url)
{
   var urlString = /\.jpg$|\.jpeg$|\.png$|\.gif$|\.bmp$/;
   var Url = Url.toLowerCase().match(urlString);
   return Url;
}
function removeHTMLTags(str)
{
	str = str.replace(/&(lt|gt);/g, function (strMatch, p1){ return (p1 == "lt")? "<" : ">";	});
	var str = str.replace(/<\/?[^>]+(>|$)/g, "");
	return str;
}
function Rnd(n)
{
	return ( Math.floor ( Math.random ( ) * n + 1 ) );
}
function ValidaEmail(sEmail)
{
	var regex=/^[a-zA-Z0-9._-]+@([a-zA-Z0-9.-]+\.)+[a-zA-Z0-9.-]{2,6}$/;
	return regex.test(sEmail);
}
function ValidaCEP(CEP)
{
	var validos="0123456789-";
	var NumHifens=0;
	if (CEP.length<8)return false;
	for (var i=0;i<CEP.length;i++)
	{
	temp=""+CEP.substring(i,i+1);
	if(temp=="-") NumHifens++;
	if(validos.indexOf(temp)=="-1")return false;
	if(NumHifens>0 && ""+CEP.charAt(5)!="-")return false;
	}
	return true;
}
function str_replace(str, de, para)
{
	var pos = str.indexOf(de);
	while (pos > -1)
	{
		str = str.replace(de, para);
		pos = str.indexOf(de);
	}
	return (str);
}
function ValidaCnpj(str)
{
	CNPJ = str;
	CNPJ = str_replace(CNPJ, '.', '');
	CNPJ = str_replace(CNPJ, '/', '');
	CNPJ = str_replace(CNPJ, '-', '');
	
	erro = new String;
	if (CNPJ.length < 14)
	{
		erro = "O CNPJ deve conter 14 dígitos!";
		alert(erro);
		return false;
	}
	
	var nonNumbers = /\D/;
	if (nonNumbers.test(CNPJ))
	{
		erro = "A verificação de CNPJ suporta apenas números!";
		alert(erro);
		return false;
	}
	
	var a = [];
	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]))
	{
		erro ="Dígito verificador com problema!";
		alert(erro);
		return false;
	}
	return true;
}
function ValidaCpf(str)
{
	str = str_replace(str, '.', '');
	str = str_replace(str, '-', '');
	
	if (VerificaCpf(str))
	{
		return true;
	}
	else
	{
		alert('CPF não é válido!');
		return false;
	}
	
	function VerificaCpf(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;
		add = 0;
		for (i=0; i < 9; i ++)
		add += parseInt(cpf.charAt(i)) * (10 - i);
		rev = 11 - (add % 11);
		if (rev == 10 || rev == 11)
		rev = 0;
		if (rev != parseInt(cpf.charAt(9)))
		return false;
		add = 0;
		for (i = 0; i < 10; i ++)
		add += parseInt(cpf.charAt(i)) * (11 - i);
		rev = 11 - (add % 11);
		if (rev == 10 || rev == 11)
		rev = 0;
		if (rev != parseInt(cpf.charAt(10)))
		return false;
		//alert('O CPF INFORMADO É VÁLIDO.');
		return true;
	}
}
//##########################################
function base64_encode(str)
{
	return encode64(str);
}
function base64_decode(str)
{
	return decode64(str);
}
// This code was written by Tyler Akins and has been placed in the
// public domain.  It would be nice if you left this header intact.
// Base64 code from Tyler Akins -- http://rumkin.com

var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

function encode64(input) {
   var output = "";
   var chr1, chr2, chr3;
   var enc1, enc2, enc3, enc4;
   var i = 0;

   do {
      chr1 = input.charCodeAt(i++);
      chr2 = input.charCodeAt(i++);
      chr3 = input.charCodeAt(i++);

      enc1 = chr1 >> 2;
      enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
      enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
      enc4 = chr3 & 63;

      if (isNaN(chr2)) {
         enc3 = enc4 = 64;
      } else if (isNaN(chr3)) {
         enc4 = 64;
      }

      output = output + keyStr.charAt(enc1) + keyStr.charAt(enc2) +
         keyStr.charAt(enc3) + keyStr.charAt(enc4);
   } while (i < input.length);

   return output;
}

function decode64(input) {
   var output = "";
   var chr1, chr2, chr3;
   var enc1, enc2, enc3, enc4;
   var i = 0;

   // remove all characters that are not A-Z, a-z, 0-9, +, /, or =
   input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

   do {
      enc1 = keyStr.indexOf(input.charAt(i++));
      enc2 = keyStr.indexOf(input.charAt(i++));
      enc3 = keyStr.indexOf(input.charAt(i++));
      enc4 = keyStr.indexOf(input.charAt(i++));

      chr1 = (enc1 << 2) | (enc2 >> 4);
      chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
      chr3 = ((enc3 & 3) << 6) | enc4;

      output = output + String.fromCharCode(chr1);

      if (enc3 != 64) {
         output = output + String.fromCharCode(chr2);
      }
      if (enc4 != 64) {
         output = output + String.fromCharCode(chr3);
      }
   } while (i < input.length);

   return output;
}

/*
*  md5.jvs 1.0b 27/06/96
*
* Javascript implementation of the RSA Data Security, Inc. MD5
* Message-Digest Algorithm.
*
* Copyright © 1996 Henri Torgemane. All Rights Reserved.
*
* Permission to use, copy, modify, and distribute this software
* and its documentation for any purposes and without
* fee is hereby granted provided that this copyright notice
* appears in all copies.
*
* Of course, this soft is provided "as is" without express or implied
* warranty of any kind.
*/


function array(n) {
  for(i=0;i<n;i++) this[i]=0;
  this.length=n;
}

/* Some basic logical functions had to be rewritten because of a bug in
* Javascript.. Just try to compute 0xffffffff >> 4 with it..
* Of course, these functions are slower than the original would be, but
* at least, they work!
*/

function integer(n) { return n%(0x7fffffff+0x7fffffff+2); }

function shr(a,b) {
  a=integer(a);
  b=integer(b);
  if (a-(0x7fffffff+1)>=0) {
    a=a%(0x7fffffff+1);
    a=a >> b;
    a+=0x40000000>>(b-1);
  } else
    a=a >> b;
  return a;
}

function shl1(a) {
  a=a%(0x7fffffff+1);
  if (a&0x40000000==0x40000000)
  {
    a-=0x40000000;  
    a*=2;
    a+=(0x7fffffff+1);
  } else
    a*=2;
  return a;
}

function shl(a,b) {
  a=integer(a);
  b=integer(b);
  for (var i=0;i<b;i++) a=shl1(a);
  return a;
}

function and(a,b) {
  a=integer(a);
  b=integer(b);
  var t1=(a-0x7fffffff-1);
  var t2=(b-0x7fffffff-1);
  if (t1>=0) 
    if (t2>=0) 
      return ((t1&t2)+(0x7fffffff+1));
    else
      return (t1&b);
  else
    if (t2>=0)
      return (a&t2);
    else
      return (a&b);  
}

function or(a,b) {
  a=integer(a);
  b=integer(b);
  var t1=(a-(0x7fffffff+1));
  var t2=(b-(0x7fffffff+1));
  if (t1>=0) 
    if (t2>=0) 
      return ((t1|t2)+(0x7fffffff+1));
    else
      return ((t1|b)+(0x7fffffff+1));
  else
    if (t2>=0)
      return ((a|t2)+(0x7fffffff+1));
    else
      return (a|b);  
}

function xor(a,b) {
  a=integer(a);
  b=integer(b);
  var t1=(a-(0x7fffffff+1));
  var t2=(b-(0x7fffffff+1));
  if (t1>=0) 
    if (t2>=0) 
      return (t1^t2);
    else
      return ((t1^b)+(0x7fffffff+1));
  else
    if (t2>=0)
      return ((a^t2)+(0x7fffffff+1));
    else
      return (a^b);  
}

function not(a) {
  a=integer(a);
  return (0x7fffffff+0x7fffffff+1-a);
}

/* Here begin the real algorithm */

    var state = new array(4); 
    var count = new array(2);
count[0] = 0;
count[1] = 0;                    
    var buffer = new array(64); 
    var transformBuffer = new array(16); 
    var digestBits = new array(16);

    var S11 = 7;
    var S12 = 12;
    var S13 = 17;
    var S14 = 22;
    var S21 = 5;
    var S22 = 9;
    var S23 = 14;
    var S24 = 20;
    var S31 = 4;
    var S32 = 11;
    var S33 = 16;
    var S34 = 23;
    var S41 = 6;
    var S42 = 10;
    var S43 = 15;
    var S44 = 21;

    function F(x,y,z) {
return or(and(x,y),and(not(x),z));
    }

    function G(x,y,z) {
return or(and(x,z),and(y,not(z)));
    }

    function H(x,y,z) {
return xor(xor(x,y),z);
    }

    function I(x,y,z) {
return xor(y ,or(x , not(z)));
    }

    function rotateLeft(a,n) {
return or(shl(a, n),(shr(a,(32 - n))));
    }


    function FF(a,b,c,d,x,s,ac) {
        a = a+F(b, c, d) + x + ac;
a = rotateLeft(a, s);
a = a+b;
return a;
    }

    function GG(a,b,c,d,x,s,ac) {
a = a+G(b, c, d) +x + ac;
a = rotateLeft(a, s);
a = a+b;
return a;
    }

    function HH(a,b,c,d,x,s,ac) {
a = a+H(b, c, d) + x + ac;
a = rotateLeft(a, s);
a = a+b;
return a;
    }

    function II(a,b,c,d,x,s,ac) {
a = a+I(b, c, d) + x + ac;
a = rotateLeft(a, s);
a = a+b;
return a;
    }

    function transform(buf,offset) { 
var a=0, b=0, c=0, d=0; 
var x = transformBuffer;

a = state[0];
b = state[1];
c = state[2];
d = state[3];

for (i = 0; i < 16; i++) {
    x[i] = and(buf[i*4+offset],0xff);
    for (j = 1; j < 4; j++) {
  x[i]+=shl(and(buf[i*4+j+offset] ,0xff), j * 8);
    }
}

/* Round 1 */
a = FF ( a, b, c, d, x[ 0], S11, 0x576aa479+0x7fffffff); /* 1 */
d = FF ( d, a, b, c, x[ 1], S12, 0x68c7b757+0x7fffffff); /* 2 */
c = FF ( c, d, a, b, x[ 2], S13, 0x242070db); /* 3 */
b = FF ( b, c, d, a, x[ 3], S14, 0x41bdceef+0x7fffffff); /* 4 */
a = FF ( a, b, c, d, x[ 4], S11, 0x757c0fb0+0x7fffffff); /* 5 */
d = FF ( d, a, b, c, x[ 5], S12, 0x4787c62a); /* 6 */
c = FF ( c, d, a, b, x[ 6], S13, 0x28304614+0x7fffffff); /* 7 */
b = FF ( b, c, d, a, x[ 7], S14, 0x7d469502+0x7fffffff); /* 8 */
a = FF ( a, b, c, d, x[ 8], S11, 0x698098d8); /* 9 */
d = FF ( d, a, b, c, x[ 9], S12, 0x0b44f7b0+0x7fffffff); /* 10 */
c = FF ( c, d, a, b, x[10], S13, 0x7fff5bb2+0x7fffffff); /* 11 */
b = FF ( b, c, d, a, x[11], S14, 0x095cd7bf+0x7fffffff); /* 12 */
a = FF ( a, b, c, d, x[12], S11, 0x6b901122); /* 13 */
d = FF ( d, a, b, c, x[13], S12, 0x7d987194+0x7fffffff); /* 14 */
c = FF ( c, d, a, b, x[14], S13, 0x2679438f+0x7fffffff); /* 15 */
b = FF ( b, c, d, a, x[15], S14, 0x49b40821); /* 16 */

/* Round 2 */
a = GG ( a, b, c, d, x[ 1], S21, 0x761e2563+0x7fffffff); /* 17 */
d = GG ( d, a, b, c, x[ 6], S22, 0x4040b341+0x7fffffff); /* 18 */
c = GG ( c, d, a, b, x[11], S23, 0x265e5a51); /* 19 */
b = GG ( b, c, d, a, x[ 0], S24, 0x69b6c7ab+0x7fffffff); /* 20 */
a = GG ( a, b, c, d, x[ 5], S21, 0x562f105e+0x7fffffff); /* 21 */
d = GG ( d, a, b, c, x[10], S22, 0x02441453); /* 22 */
c = GG ( c, d, a, b, x[15], S23, 0x58a1e682+0x7fffffff); /* 23 */
b = GG ( b, c, d, a, x[ 4], S24, 0x67d3fbc9+0x7fffffff); /* 24 */
a = GG ( a, b, c, d, x[ 9], S21, 0x21e1cde6); /* 25 */
d = GG ( d, a, b, c, x[14], S22, 0x433707d7+0x7fffffff); /* 26 */
c = GG ( c, d, a, b, x[ 3], S23, 0x74d50d88+0x7fffffff); /* 27 */
b = GG ( b, c, d, a, x[ 8], S24, 0x455a14ed); /* 28 */
a = GG ( a, b, c, d, x[13], S21, 0x29e3e906+0x7fffffff); /* 29 */
d = GG ( d, a, b, c, x[ 2], S22, 0x7cefa3f9+0x7fffffff); /* 30 */
c = GG ( c, d, a, b, x[ 7], S23, 0x676f02d9); /* 31 */
b = GG ( b, c, d, a, x[12], S24, 0x0d2a4c8b+0x7fffffff); /* 32 */

/* Round 3 */
a = HH ( a, b, c, d, x[ 5], S31, 0x7ffa3943+0x7fffffff); /* 33 */
d = HH ( d, a, b, c, x[ 8], S32, 0x0771f682+0x7fffffff); /* 34 */
c = HH ( c, d, a, b, x[11], S33, 0x6d9d6122); /* 35 */
b = HH ( b, c, d, a, x[14], S34, 0x7de5380d+0x7fffffff); /* 36 */
a = HH ( a, b, c, d, x[ 1], S31, 0x24beea45+0x7fffffff); /* 37 */
d = HH ( d, a, b, c, x[ 4], S32, 0x4bdecfa9); /* 38 */
c = HH ( c, d, a, b, x[ 7], S33, 0x76bb4b61+0x7fffffff); /* 39 */
b = HH ( b, c, d, a, x[10], S34, 0x3ebfbc71+0x7fffffff); /* 40 */
a = HH ( a, b, c, d, x[13], S31, 0x289b7ec6); /* 41 */
d = HH ( d, a, b, c, x[ 0], S32, 0x6aa127fb+0x7fffffff); /* 42 */
c = HH ( c, d, a, b, x[ 3], S33, 0x54ef3086+0x7fffffff); /* 43 */
b = HH ( b, c, d, a, x[ 6], S34, 0x04881d05); /* 44 */
a = HH ( a, b, c, d, x[ 9], S31, 0x59d4d03a+0x7fffffff); /* 45 */
d = HH ( d, a, b, c, x[12], S32, 0x66db99e6+0x7fffffff); /* 46 */
c = HH ( c, d, a, b, x[15], S33, 0x1fa27cf8); /* 47 */
b = HH ( b, c, d, a, x[ 2], S34, 0x44ac5666+0x7fffffff); /* 48 */

/* Round 4 */
a = II ( a, b, c, d, x[ 0], S41, 0x74292245+0x7fffffff); /* 49 */
d = II ( d, a, b, c, x[ 7], S42, 0x432aff97); /* 50 */
c = II ( c, d, a, b, x[14], S43, 0x2b9423a8+0x7fffffff); /* 51 */
b = II ( b, c, d, a, x[ 5], S44, 0x7c93a03a+0x7fffffff); /* 52 */
a = II ( a, b, c, d, x[12], S41, 0x655b59c3); /* 53 */
d = II ( d, a, b, c, x[ 3], S42, 0x0f0ccc93+0x7fffffff); /* 54 */
c = II ( c, d, a, b, x[10], S43, 0x7feff47e+0x7fffffff); /* 55 */
b = II ( b, c, d, a, x[ 1], S44, 0x05845dd2+0x7fffffff); /* 56 */
a = II ( a, b, c, d, x[ 8], S41, 0x6fa87e4f); /* 57 */
d = II ( d, a, b, c, x[15], S42, 0x7e2ce6e1+0x7fffffff); /* 58 */
c = II ( c, d, a, b, x[ 6], S43, 0x23014315+0x7fffffff); /* 59 */
b = II ( b, c, d, a, x[13], S44, 0x4e0811a1); /* 60 */
a = II ( a, b, c, d, x[ 4], S41, 0x77537e83+0x7fffffff); /* 61 */
d = II ( d, a, b, c, x[11], S42, 0x3d3af236+0x7fffffff); /* 62 */
c = II ( c, d, a, b, x[ 2], S43, 0x2ad7d2bb); /* 63 */
b = II ( b, c, d, a, x[ 9], S44, 0x6b86d392+0x7fffffff); /* 64 */

state[0] +=a;
state[1] +=b;
state[2] +=c;
state[3] +=d;

    }

    function init() {
count[0]=count[1] = 0;
state[0] = 0x67452301;
state[1] = 0x6fcdab8a+0x7fffffff;
state[2] = 0x18badcff+0x7fffffff;
state[3] = 0x10325476;
for (i = 0; i < digestBits.length; i++)
    digestBits[i] = 0;
    }

    function update(b) { 
var index,i;

index = and(shr(count[0],3) , 0x3f);
if (count[0]<0x7fffffff+0x7fffffff-6) 
  count[0] += 8;
        else {
  count[1]++;
  count[0]-=0x7fffffff+0x7fffffff+2;
          count[0]+=8;
        }
buffer[index] = and(b,0xff);
if (index  >= 63) {
    transform(buffer, 0);
}
    }

    function finish() {
var bits = new array(8);
var padding; 
var i=0, index=0, padLen=0;

for (i = 0; i < 4; i++) {
    bits[i] = and(shr(count[0],(i * 8)), 0xff);
}
        for (i = 0; i < 4; i++) {
    bits[i+4]=and(shr(count[1],(i * 8)), 0xff);
}
index = and(shr(count[0], 3) ,0x3f);
padLen = (index < 56) ? (56 - index) : (120 - index);
padding = new array(64); 
padding[0] = 0x80;
        for (i=0;i<padLen;i++)
  update(padding[i]);
        for (i=0;i<8;i++) 
  update(bits[i]);

for (i = 0; i < 4; i++) {
    for (j = 0; j < 4; j++) {
  digestBits[i*4+j] = and(shr(state[i], (j * 8)) , 0xff);
    }
} 
    }

/* End of the MD5 algorithm */

function hexa(n) {
var hexa_h = "0123456789abcdef";
var hexa_c=""; 
var hexa_m=n;
for (hexa_i=0;hexa_i<8;hexa_i++) {
  hexa_c=hexa_h.charAt(Math.abs(hexa_m)%16)+hexa_c;
  hexa_m=Math.floor(hexa_m/16);
}
return hexa_c;
}


var ascii="01234567890123456789012345678901" +
          " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ"+
          "[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~";

function MD5(entree) 
{
var l,s,k,ka,kb,kc,kd;

init();
for (k=0;k<entree.length;k++) {
  l=entree.charAt(k);
  update(ascii.lastIndexOf(l));
}
finish();
ka=kb=kc=kd=0;
for (i=0;i<4;i++) ka+=shl(digestBits[15-i], (i*8));
for (i=4;i<8;i++) kb+=shl(digestBits[15-i], ((i-4)*8));
for (i=8;i<12;i++) kc+=shl(digestBits[15-i], ((i-8)*8));
for (i=12;i<16;i++) kd+=shl(digestBits[15-i], ((i-12)*8));
s=hexa(kd)+hexa(kc)+hexa(kb)+hexa(ka);
return s; 
}
