//habilitar a transparencia no firefox/linux
$.blockUI.defaults.applyPlatformOpacityRules = false;

function block(){
	$( 'html' ).css( 'cursor', 'wait' );
	$.blockUI( { css: {}, message: '<img src="/_img/ajax-loader.gif">' } ); 
}
function unblock(){
	$( 'html' ).css( 'cursor', 'default' );
	$( 'html' ).unblock();
}

/**
 * Funcao que verifica se a senha foi digitada corretamente
 */
function verificaSenha(Senha, Senha2){
	if((Senha.length > 0) && (Senha2.length > 0)){
		if(Senha != Senha2){
			SenhaOk = false;
			document.getElementById('Senha2Msg').innerHTML = '- Conferir senha!';
		} else{
			SenhaOk = true;
			document.getElementById('Senha2Msg').innerHTML = '';
		}
	} else{ 
		document.getElementById('Senha2Msg').innerHTML = ''; 
	}
}

function replaceAll(str, de, para){
    var pos = str.indexOf(de);
    while (pos > -1){
		str = str.replace(de, para);
		pos = str.indexOf(de);
	}
    return (str);
}

function geraPermaLink(texto, id){
	// Troco letras maiusculas por minusculas
	texto = texto.toLowerCase(); 
	
	// Troco a com acento por a sem acento
	texto = replaceAll(texto, 'á', 'a');
	texto = replaceAll(texto, 'à', 'a');
	texto = replaceAll(texto, 'ã', 'a');
	texto = replaceAll(texto, 'â', 'a');
	texto = replaceAll(texto, 'ä', 'a');
	
	// Troco e com acento por e sem acento
	texto = replaceAll(texto, 'é', 'e');
	texto = replaceAll(texto, 'è', 'e');
	texto = replaceAll(texto, 'ê', 'e');
	texto = replaceAll(texto, 'ë', 'e');
	
	// Troco i com acento por i sem acento
	texto = replaceAll(texto, 'í', 'i');
	texto = replaceAll(texto, 'ì', 'i');
	texto = replaceAll(texto, 'î', 'i');
	texto = replaceAll(texto, 'ï', 'i');
	
	// Troco o com acento por o sem acento
	texto = replaceAll(texto, 'ó', 'o');
	texto = replaceAll(texto, 'ò', 'o');
	texto = replaceAll(texto, 'õ', 'o');
	texto = replaceAll(texto, 'ô', 'o');
	texto = replaceAll(texto, 'ö', 'o');
	
	// Troco u com acento por u sem acento
	texto = replaceAll(texto, 'ú', 'u');
	texto = replaceAll(texto, 'ù', 'u');
	texto = replaceAll(texto, 'û', 'u');
	texto = replaceAll(texto, 'ü', 'u');
	
	// Troco cedilha por c
	texto = replaceAll(texto, 'ç', 'c');
	
	// Troco caracteres reservados por -
	texto = replaceAll(texto, ';', '-');
	texto = replaceAll(texto, '/', '-');
	texto = replaceAll(texto, '?', '-');
	texto = replaceAll(texto, ':', '-');
	texto = replaceAll(texto, '@', '-');
	texto = replaceAll(texto, '&', 'e');
	texto = replaceAll(texto, '=', '-');
	texto = replaceAll(texto, '+', '-');
	texto = replaceAll(texto, '$', '-');
	texto = replaceAll(texto, ',', '-');	

	// Troco caracteres excluidos por -
	texto = replaceAll(texto, ' ', '-');
	texto = replaceAll(texto, '<', '-');
	texto = replaceAll(texto, '>', '-');
	texto = replaceAll(texto, '#', '-');
	texto = replaceAll(texto, '%', '-');
	texto = replaceAll(texto, '"', '-');
	texto = replaceAll(texto, '{', '-');
	texto = replaceAll(texto, '}', '-');
	texto = replaceAll(texto, '|', '-');
	texto = replaceAll(texto, '\\', '-');
	texto = replaceAll(texto, '^', '-');
	texto = replaceAll(texto, '[', '-');
	texto = replaceAll(texto, ']', '-');
	texto = replaceAll(texto, '`', '-');
	texto = replaceAll(texto, '~', '-');
	
	if(id){
		$('#'+id).val(texto);
	} else{
		return permaLink;
	}
	
}

function corrigeAcentuacao(texto){
		///a{1}/gi
        texto = texto.replace(/Ã¡/gi, "á").replace(/Ã¢/gi, "â").replace(/Ã£/gi, "ã").replace(/Ã©/gi, "é").replace(/Ãª/gi, "ê").replace(/Ã®/gi, "î").replace(/Ã³/gi, "ó").replace(/Ã´/gi, "ô").replace(/Ãµ/gi, "õ").replace(/Ãº/gi, "ú").replace(/Ã»/gi, "û");  
        texto = texto.replace(/Ã\?/gi, "Á").replace(/Ã‚/gi, "Â").replace(/Ã‰/gi, "É").replace(/ÃŠ/gi, "Ê").replace(/Ã\?/gi, "Í").replace(/Ã“/gi, "Ó").replace(/Ã”/gi, "Ô").replace(/Ã•/gi, "Õ").replace(/Ãš/gi, "Ú");  
        texto = texto.replace(/Ã§/gi, "ç").replace(/Ã‡/gi, "Ç").replace(/Âº/gi, "º");
 		texto = texto.replace(/(Ã[^ƒ])/g, "í");
		texto = texto.replace(/Ãƒ/gi, "Ã");
		texto = texto.replace(/(íshy;)/g, "í");
        return texto;  
	}

function isHexa( value ){
	
	RegExp = new RegExp('#[0-9A-Fa-f]{6}');
	if( RegExp.test( value ) ){
		alert('sim');
	} else{
		alert('nao');
	}
	RegExp = '';
}

// Função para validar datas por java script
function validaData(data,tipo){
    var erData = /^[0-3][0-9]\/[01][0-9]\/\d{4}$/;
	var erDia = /[0-2][0-9]/;
	var erMes = /0[1-9]/;
	
    if(erData.test(data)){
    	var aData = data.split("/");
    	aData[2] = aData[2]*1;
		if( erDia.test(aData[0]) || aData[0] == 30 || aData[0] == 31 ){
			if( erMes.test(aData[1]) || aData[1] == 10 || aData[1] == 11 || aData[1] == 12 ){
				if( aData[2] >= 2009 ){
				 	return true;								
				}else{
					return false;
				}
			}else{
				return false;
			}
    	}else{
			return false;
		}
    }else{
    	return false;
    }
		
}

function verificaData(data1, data2, tipo){
	var aData1 = data1.split("/");
	var aData2 = data2.split("/");
	
	aData1[0] = aData1[0]*1;
	aData1[1] = aData1[1]*1;
	aData1[2] = aData1[2]*1;
	
	aData2[0] = aData2[0]*1;
	aData2[1] = aData2[1]*1;
	aData2[2] = aData2[2]*1;
	
	//verifica o dia de inicio da data
	if(tipo == 'dataInicio'){ 
		if(aData1[2] > aData2[2]){
			return true;
		}else if(aData1[2] = aData2[2]){
			if(aData1[1] > aData2[1]){
				return true;	
			}else if(aData1[1] = aData2[1]){
				if(aData1[0] >= aData2[0]){
					return true;
				}else{
					return false;
				}
			}else{
				return false;
			}
			
		}else{
			return false;
		}
	}
	
	//verifica o dia de inicio da data
	if(tipo == 'diffDatas'){
		if(aData2[2] > aData1[2]){
			return true;
		}else if(aData2[2] = aData1[2]){			
			if(aData2[1] > aData1[1]){
				return true;	
			}else if(aData2[1] = aData1[1]){
				if(aData2[0] >= aData1[0]){
					return true;
				}else{
					return false;
				}
			}else{
				return false;
			}
			
		}else{
			return false;
		}
	}
	
	
}

/**
 * Funcao que permite adicionar uma URL aos favoritos da maioria dos browsers
 */
function addFav(){
    var url      = 'http://painel.dev.rededor.com.br';
    var title    = 'Mail PDC';
    if (window.sidebar) window.sidebar.addPanel(title, url,"");
    else if(window.opera && window.print){
        var mbm = document.createElement('a');
        mbm.setAttribute('rel','sidebar');
        mbm.setAttribute('href',url);
        mbm.setAttribute('title',title);
        mbm.click();
    }
    else if(document.all){window.external.AddFavorite(url, title);}
}


/**
 * Permite requisicoes via http(Ajax)
 *	
 * @param  String  urlRequest 
 * @param  Boolean loading
 *	
 * @return String responseText
 *	
 * Obs: A propriedade async foi alterada para false, pois
 * o quando true o "restante" do script era executado
 * enquato a "resposta" nao chegava, e quando ela a mesma era
 * obtida ele ja tinha terminado o script. ex: excluirRegistro
 */


function httpRequest( urlDo, dadosForm ){
	block();
	var resp; 
	
	var ajax = $.ajax( { 
		type: 'POST', 
		url: urlDo,
		data: dadosForm,
		async: false,
		/*beforeSend: function(){
						$( 'html' ).css( 'cursor', 'wait' );
						$.blockUI( { message: '<img src="/_img/ajax-loader.gif">' } ); 
					},*/
		success: function( resposta ){
			     	/**$( 'html' ).css( 'cursor', 'default' );
			    	//$.unblockUI();
			    	$( 'html' ).unblock();
	             	/**
	             	 * Armazenamos numa variavel global da funcao, pois nao foi possivel dar return
	             	 * de dentro desta function.
	             	 */
		         	 resp = resposta;
		         }		         
	} );
	
	unblock();
	// Retorna a resposta, caso ela tenha sido obtida e nenhum idCampo for informado
	return resp;

}

/**
 * Funcao que permite requisicoes via http( Ajax ) sem barra de load
 *	
 * @param  String  urlRequest 
 * @param  Boolean loading
 *	
 * @return String responseText
 *	
 * Obs: A propriedade async foi alterada para false, pois
 * o quando true o "restante" do script era executado
 * enquato a "resposta" nao chegava, e quando ela a mesma era
 * obtIda ele ja tinha terminado o script. ex: excluirRegistro
 */
function httpRequestNoBlock( urlRequest, dadosForm ){
	
	var resp;
	
	var ajax = $.ajax( { 
		type: 'POST', 
		url: urlRequest,
		data: dadosForm,
		async: false,
		success: function( resposta ){
	             	/**
	             	 * Armazenamos numa variavel global da funcao, pois nao foi possivel dar return
	             	 * de dentro desta function.
	             	 */
		         	 resp = resposta;
		         }	
	} );
	
	// Retorna a resposta, caso ela tenha sIdo obtIda e nenhum IdCampo for informado
	return resp;

}

// var_dump em JavaScrip. Apenas retorna valor, e necessario imprimi-lo
function var_dump(obj){
	if( typeof obj == "object" ){
		return "Type: " + typeof( obj )+( ( obj.constructor ) ? "\nConstructor: " + obj.constructor : "") + "\nValue: " + obj;
	} else {
		return "Type: " + typeof( obj ) + "\nValue: " + obj;
	}
}

// Funcao que da um reload na pagina
function refresh(){
	window.location.reload();
}

// Aplica o efeito Toogle em derterminado campo
function toogle( Id ){
	$( '#' + Id ).toggle( 400 );
}

// Esconde derterminado campo
function hide( Id ){
	$( '#' + Id ).hide();
}

// Mostra derterminado campo
function show( Id ){
	$( '#' + Id ).show();
}

// Remover determinado campo
function remove( Id ){
	$( '#' + Id ).remove();	
}

// Funcao que reseta os valores do formulario
function resetForm( Id ){
	
	$( '#' + Id ).resetForm();
	$('#' + Id + " input[type*='hidden'][name!='Acao']").val( '' );
	
	//alert ( $('#' + Id + ' fieldset ul li textarea').val() );
	//$('#' + Id + " textarea").val( '' );
	//console.log($('#' + Id + ' fieldset ul li textarea').val());
	//$('#' + Id + ' fieldset ul li textarea').val( '' );
	if (typeof(CKEDITOR) != 'undefined') {
		for (var instanceName in CKEDITOR.instances) {
			CKEDITOR.instances[instanceName].setData("");
		}
		for( i=0;i<document.getElementById(Id).elements.length;i++ ){
			if( document.getElementById(Id).elements[i].tagName == "TEXTAREA" ){
				document.getElementById(Id).elements[i].style.display = "block";				
				document.getElementById(Id).elements[i].value = "";
				document.getElementById(Id).elements[i].style.display = "none";		
			}
		}
	}else{
		for( i=0;i<document.getElementById(Id).elements.length;i++ ){
			if( document.getElementById(Id).elements[i].tagName == "TEXTAREA" ){				
				document.getElementById(Id).elements[i].value = "";
			}
		}
	}	
	//$("textarea").val('');
	//$( "#" + Id ).each(function() {
	//	  alert( $(this).attr('class') == 'jqeditor' );  
	//	});
	//alert( $( "#" + Id + " textarea").val() );  //   --NAO FUNCIONA NO IE
	//$('#' + Id + " input[title^='*']").removeClass("campo-erro"); --NAO FUNCIONA NO IE
	retiraCorForm(document.getElementById(Id));
	
	//$("#Acao").val( 'insert' );
	$( '#box' ).hide();
	
	/*if (typeof(CKEDITOR) != 'undefined') {
		//percorremos os editores CKEDITOR e atualizamos os mesmos em relação a sua textarea.
		for (var instanceName in CKEDITOR.instances) {
			//alert( instanceName );
			///idCkeditor = CKEDITOR.instances[instanceName].name;
			//valorEdiorAtualizado = $( '#' + instanceName).val();
			//$( '#' + instanceName).val('');
			CKEDITOR.instances[instanceName].setData("");
			//CKEDITOR.instances[instanceName].updateElement();
			//$("#cke_" + idCkeditor + " span span").removeClass("campo-erro-cke");
			//eval('CKEDITOR.instances.' + instanceName + '.setUiColor(\'#D3D3D3\')');
			
		}
	}*/
	
	
	
	//Usa XPath para alcancar todos os campos (input, select, textarea, button).
	//$( '#' + form_id + '	:input:hidden' ).val( '' ); --NAO FUNCIONA NO IE
	//$( '#'+form_id+' :textarea' ).val( '' );
    // OU se cajo deseje resetar apenas os especificos: -> $( '#' + form_id + ' .resetar' ).val( '' );
}

/**
 * Faz a validacao dos campos de um formulario
 *
 * @param DOM form
 * @return Boolean
 */
function retiraCorForm( form ){
	

	// Percorremos todos os elementos do formulario
	for( i=0;i<form.elements.length;i++ ){
		
		
		// Verificamos se o campo tem preenchimento obrigatorio
		if( form.elements[i].title.indexOf( '*' ) > -1 ){
			
				form.elements[i].className = '';
				
		}
		
		//// Verficamos se o campo exige validacao de CKEDITOR
		/*if( form.elements[i].title.indexOf( '|-' ) > -1 ){
			
			//pega o id do textarea que tem o ckeditor
			idCkeditor = form.elements[i].id;
			//guarda o texto do ckeditor em uma variavel para poder ser calculado seu tamanho 
			if (typeof CKEDITOR != 'undefined') {
				txtCkEditor = eval('CKEDITOR.instances.' + idCkeditor + '.getData()');
			}
			if( txtCkEditor.length == 0  ){
				eval('CKEDITOR.instances.' + idCkeditor + '.setUiColor(\'#D3D3D3\')');
			}
				
		}*/
	}	
}

/**
 * Escreve em campo html a resposta da requisicao http(Ajax)
 */
function exibeResposta( Id, resposta ){
	$( '#' + Id ).html( resposta );
	
}

/**
 * Funcao de teste para informar o funcionamento do ajax
 */
function httpResposta( urlDo, dadosForm, Id ){	
	var resposta = httpRequest( urlDo, dadosForm );
	exibeResposta( Id, resposta );
}

/**
 * Faz a validacao dos campos de um formulario
 *
 * @param DOM form
 * @return Boolean
 */
function validaForm( form ){
	var preenchidos = true;
	// Percorremos todos os elementos do formulario
	for( i=0;i<form.elements.length;i++ ){
		
		// Verificamos se o campo tem preenchimento obrigatorio
		if( form.elements[i].title.indexOf( '*' ) > -1 ){
			
			if( form.elements[i].value.length == 0 ){
				preenchidos = false;
				
                                form.elements[i].className += ' campo-erro';
			} else{
				form.elements[i].className += '';
			}
			
		}
		
		// Verficamos se o campo exige validacao por IP
		if( form.elements[i].title.indexOf( '#' ) > -1 ){
			
			// So verificamos se o ip e valido se o campo for preenchido
			if( form.elements[i].value.length == 0 ){
				
				// Verificamos se o ip for nao foi informado correntamente
				if( !( validaIP( form.elements[i].value ) ) ){
					preenchidos = false;
					form.elements[i].style.borderColor = 'red';
				} else {
					form.elements[i].style.borderColor = 'black';
				}

			}
		
		}
		
		
		/*/// Verficamos se o campo exige validacao de CKEDITOR
		if( form.elements[i].title.indexOf( '|-' ) > -1 ){
			
			//pega o id do textarea que tem o ckeditor
			idCkeditor = form.elements[i].id;
			//guarda o texto do ckeditor em uma variavel para poder ser calculado seu tamanho 
			if (typeof CKEDITOR != 'undefined') {
				txtCkEditor = eval('CKEDITOR.instances.' + idCkeditor + '.getData()');
			}
			if( txtCkEditor.length == 0  ){
				preenchidos = false;
					//form.elements[i].style.borderColor = 'red';
					//eval( 'CKEDITOR.instances.'+ idCkeditor + '.addStylesSet()' );
					//$("#cke_"+idCkeditor+" span span").addClass("campo-erro-cke");
					eval('CKEDITOR.instances.' + idCkeditor + '.setUiColor(\'#f1c4c9\')');
					
				} else {
					//form.elements[i].style.borderColor = 'black';
					//$("#cke_"+idCkeditor+" span span").removeClass("campo-erro-cke");
					eval('CKEDITOR.instances.' + idCkeditor + '.setUiColor(\'#D3D3D3\')');
				}
				
			}*/
			
			/*/ So verificamos se o ip e valido se o campo for preenchido
			if( form.elements[i].value.length == 0 ){
				
				// Verificamos se o ip for nao foi informado correntamente
				if( !( validaIP( form.elements[i].value ) ) ){
					preenchidos = false;
					form.elements[i].style.borderColor = 'red';
				} else {
					form.elements[i].style.borderColor = 'black';
				}

			}*/
		
	}
	
	// Caso um dos campos obrigatorios nao tenham sido preenchido
	if( !preenchidos ){
		return false;
	} else {
		return true;		
	}
	
}

/**
 * Verfica se um valor informado e um IP valido.
 */
function validaIP( IPvalue ){
	ok = true;
	regraIP = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/;
	var ipArray = IPvalue.match(regraIP);
	
	// Verificamos se o IP e diferente de 0.0.0.0 e 255.555.555.555
	if( IPvalue == "0.0.0.0" || IPvalue == "255.555.555.555" ){
		ok = false;
	}
	
	/**
	 * Verificamos se a regra de expressao regular retornou um array, 
	 * confirmando assim que o IP � valido
	 */
	if ( ipArray != null ){
		
		// Verificamos cada digito do IP
		for( j=0; j<4; j++ ){
			if ( ( ipArray[j] == 0 && j == 0 ) || ipArray[j] == 255 || ipArray[j] > 255 ){
				ok = false;				
			}
		}		
		
	} else{
		ok = false;		
	}
		
	return ok;

}

/**
 * Verifica se um CPF é válido
 * 
 * @param String   - CPF ex:( 123.777.218-05 )
 */
function validaCPF( CPF ){
	if( ( CPF != '___.___.___-__' )  && ( CPF.length > 0 ) ){
		var s = CPF.replace( ".", "" );
		var s = s.replace( ".", "" );
		var s = s.replace( "-" , "" );
		
		CPFOk1 = true;
		
		if( isNaN( s ) ){
			CPFOk1 = false;
		}
		
		if( s == "00000000000" || s == "11111111111" || s == "22222222222" || s == "33333333333" || s == "44444444444" || s == "55555555555" || s == "66666666666" || s == "77777777777" || s == "88888888888" || s == "99999999999" || s == "12345678909" ){
		  CPFOk1 =  false;
	    }
	    
		var i;
		
		var c = s.substr( 0, 9 );
		
		var dv = s.substr( 9, 2 );
		
		var d1 = 0;
		
		for( i = 0; i < 9; i++ ){
			d1 += c.charAt( i ) * ( 10 - i );
		}
		
		if( d1 == 0 ){
			CPFOk1 =  false;
		}    
		     
		d1 = 11 - (d1 % 11);
		
		if( d1 > 9 ) d1 = 0; 
		        
		if( dv.charAt( 0 ) != d1 ){
			CPFOk1 =  false;         
		}
		
		d1 *= 2;
		
		for( 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 ){
			CPFOk1 = false;
		}
		
		if( CPFOk1 ){
			document.getElementById( 'CPFMsg' ).innerHTML = '';
			$('#CPF').removeClass('campo-erro');
		} else{
			document.getElementById( 'CPFMsg' ).innerHTML = '- CPF inválido!';
			$('#CPF').addClass('campo-erro');
		}
	} else{
		document.getElementById( 'CPFMsg' ).innerHTML = '';
		$('#CPF').removeClass('campo-erro');
	}
}


/**
 * Verifica se um CNPJ e valido
 * 
 * @param String   - CNPJ ex:(12.345.678/9012-34)
 */
function validaCNPJ( nCNPJ ){
	if( ( nCNPJ != '__.___.___/____-__' )  && ( nCNPJ.length > 0 ) ){
		
		var CNPJ = nCNPJ.replace( ".", "" );
		var CNPJ = CNPJ.replace( ".", "" );
		var CNPJ = CNPJ.replace( "/", "" );	
		var CNPJ = CNPJ.replace( "-", "" );	
		
		CNPJOk = true;
		
		erro = new String;
		  
		if( CNPJ.length < 14 ) CNPJOk = false;
		
		var nonNumbers = /\D/;
		
		if( nonNumbers.test( CNPJ ) ) erro += "A verificacao de CNPJ suporta apenas n&uacute;meros!";	
		
		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 += "Digito verificador com problema!";
		}
		
		if ( erro.length > 0 ){
			CNPJOk =  false;
		}
		
		if( CNPJOk ){
			document.getElementById( 'CNPJMsg' ).innerHTML = '';
			$('#CNPJ').removeClass('campo-erro');
		} else{
			document.getElementById( 'CNPJMsg' ).innerHTML = '- CNPJ inv&aacute;lido!';
			$('#CNPJ').addClass('campo-erro');
		}
	} else{
		document.getElementById( 'CNPJMsg' ).innerHTML = '';
		$('#CNPJ').removeClass('campo-erro');
	}
}

/**
 * Classe para criar password aleatorio de numeros e letras 
 * 
 * @exemplo
 *	var pwd = new Password();
 *	document.getElementById(IdObjeto).value = pwd.generate(numCaracteres)
 *	
 */

var Password = function() {
	this.pass = "";

	this.generate = function(chars) {
		for (var i= 0; i<chars; i++) {
			this.pass += this.getRandomChar();
		}
		return this.pass;
	}

	this.getRandomChar = function() {
		 /*
		*    matriz contendo em cada linha indices (inicial e final) da tabela ASCII para retornar alguns caracteres.
		*    [48, 57] = numeros;
		*    [64, 90] = "@" mais letras maiusculas;
		*    [65, 90] = apenas as letras maiusculas; //modificado para não colocar o @ por Marcos Luiz
		*    [97, 122] = letras minusculas;
		*/
		var ascii = [[48, 57],[65,90],[97,122]];
		var i = Math.floor(Math.random()*ascii.length);
		return String.fromCharCode(Math.floor(Math.random()*(ascii[i][1]-ascii[i][0]))+ascii[i][0]);
	}
}

/* ************************************************************
Created: 20060120
Author:  Steve Moitozo <god at zilla dot us> -- geekwisdom.com
Description: This is a quick and dirty password quality meter 
		 written in JavaScript so that the password does 
		 not pass over the network.
License: MIT License (see below)
Modified: 20060620 - added MIT License
Modified: 20061111 - corrected regex for letters and numbers
                     Thanks to Zack Smith -- zacksmithdesign.com
---------------------------------------------------------------
Copyright (c) 2006 Steve Moitozo <god at zilla dot us>

Permission is hereby granted, free of charge, to any person 
obtaining a copy of this software and associated documentation 
files (the "Software"), to deal in the Software without 
restriction, including without limitation the rights to use, 
copy, modify, merge, publish, distribute, sublicense, and/or 
sell copies of the Software, and to permit persons to whom the 
Software is furnished to do so, subject to the following 
conditions:

   The above copyright notice and this permission notice shall 
be included in all copies or substantial portions of the 
Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY 
KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE 
WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE 
AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE 
OR OTHER DEALINGS IN THE SOFTWARE. 
---------------------------------------------------------------


Password Strength Factors and Weightings

password length:
level 0 (3 point): less than 4 characters
level 1 (6 points): between 5 and 7 characters
level 2 (12 points): between 8 and 15 characters
level 3 (18 points): 16 or more characters

letters:
level 0 (0 points): no letters
level 1 (5 points): all letters are lower case
level 2 (7 points): letters are mixed case

numbers:
level 0 (0 points): no numbers exist
level 1 (5 points): one number exists
level 1 (7 points): 3 or more numbers exists

special characters:
level 0 (0 points): no special characters
level 1 (5 points): one special character exists
level 2 (10 points): more than one special character exists

combinatons:
level 0 (1 points): letters and numbers exist
level 1 (1 points): mixed case letters
level 1 (2 points): letters, numbers and special characters 
					exist
level 1 (2 points): mixed case letters, numbers and special 
					characters exist


NOTE: Because I suck at regex the code might need work
	  
NOTE: Instead of putting out all the logging information,
	  the score, and the verdict it would be nicer to stretch
	  a graphic as a method of presenting a visual strength
	  guage.

************************************************************ */
function testPassword( passwd , idCampo ){
	if( passwd.length > 0 ){
		var intScore   = 0
		var strVerdict = "weak"
		var strLog     = ""

		// PASSWORD LENGTH
		if( passwd.length < 5 ){                         // length 4 or less
                        //$('#'+idCampo).removeClass('campo-erro');
			//intScore = ( intScore + 3 )
			strLog   = strLog + "3 points for length (" + passwd.length + ")\n"
		} else if( passwd.length > 4 && passwd.length < 8 ){ // length between 5 and 7
			intScore = ( intScore + 8 )
			strLog   = strLog + "6 points for length (" + passwd.length + ")\n"
		} else if( passwd.length > 7 && passwd.length < 16 ){ // length between 8 and 15
			intScore = ( intScore + 12 )
			strLog   = strLog + "12 points for length (" + passwd.length + ")\n"
		} else if( passwd.length > 15 ){                    // length 16 or more
			intScore = ( intScore + 18 )
				strLog   = strLog + "18 point for length (" + passwd.length + ")\n"
		}
                if ( intScore > 0 ) {

			// LETTERS (Not exactly implemented as dictacted above because of my limited understanding of Regex)
			if ( passwd.match(/[a-z]/) )                              // [verified] at least one lower case letter
			{
				intScore = ( intScore + 1 )
				strLog   = strLog + "1 point for at least one lower case char\n"
			}

			if ( passwd.match(/[A-Z]/) )                              // [verified] at least one upper case letter
			{
				intScore = ( intScore + 5 )
				strLog   = strLog + "5 points for at least one upper case char\n"
			}

			// NUMBERS
			if(passwd.match(/\d+/))                                 // [verified] at least one number
			{
				intScore = ( intScore + 4 )
				strLog   = strLog + "5 points for at least one number\n"
			}

			if( passwd.match(/(.*[0-9].*[0-9].*[0-9])/) )             // [verified] at least three numbers
			{
				intScore = ( intScore + 5 )
				strLog   = strLog + "5 points for at least three numbers\n"
			}


			// SPECIAL CHAR
			if( passwd.match(/.[!,@,#,$,%,^,&,*,?,_,~]/) )            // [verified] at least one special character
			{
				intScore = ( intScore + 5 )
				strLog   = strLog + "5 points for at least one special char\n"
			}

										 // [verified] at least two special characters
			if ( passwd.match(/(.*[!,@,#,$,%,^,&,*,?,_,~].*[!,@,#,$,%,^,&,*,?,_,~])/) )
			{
				intScore = ( intScore + 5 )
				strLog   = strLog + "5 points for at least two special chars\n"
			}


			// COMBOS
			if ( passwd.match(/([a-z].*[A-Z])|([A-Z].*[a-z])/) )        // [verified] both upper and lower case
			{
				intScore = ( intScore + 2 )
				strLog   = strLog + "2 combo points for upper and lower letters\n"
			}

			if ( passwd.match(/([a-zA-Z])/) && passwd.match(/([0-9])/) ) // [verified] both letters and numbers
			{
				intScore = ( intScore + 5 )
				strLog   = strLog + "2 combo points for letters and numbers\n"
			}

										// [verified] letters, numbers, and special characters
			if ( passwd.match(/([a-zA-Z0-9].*[!,@,#,$,%,^,&,*,?,_,~])|([!,@,#,$,%,^,&,*,?,_,~].*[a-zA-Z0-9])/) )
			{
				intScore = ( intScore + 2 )
				strLog   = strLog + "2 combo points for letters, numbers and special chars\n"
			}
                }


			if( intScore < 9 ){
			    strVerdict = 'Senha muito fraca!';
			    corEspecifica = '#FF0000';

			} else if( intScore > 8 && intScore < 25 ){
			    strVerdict = 'Senha fraca!';
                            corEspecifica = "#FF6600";

			} else if( intScore > 24 && intScore < 35 ){
				strVerdict = 'Senha média!';
			    corEspecifica = "#FF9900";

			} else if( intScore > 34 && intScore < 45 ){
				strVerdict = 'Senha forte!';
				corEspecifica = "#006600";

			} else{
				strVerdict = 'Senha muito forte!';
				corEspecifica = "#006666";

			}

			document.getElementById( 'SenhaMsg' ).innerHTML = strVerdict;
			document.getElementById( 'SenhaMsg' ).style.color = corEspecifica;

			erSenha = /muito fraca!/i;
			if( erSenha.test(strVerdict) ){
				$('#'+idCampo).addClass('campo-erro');
			}else{
				$('#'+idCampo).removeClass('campo-erro');
			}
		} else{
			document.getElementById( 'SenhaMsg' ).innerHTML = '';
			$('#'+idCampo).removeClass('campo-erro');
		}
}

/**
 * Funcao que copia o valor de um elemento para outro elemento.
 */
function copy( From, To ){
	document.getElementById( To ).value += document.getElementById( From ).value;
	document.getElementById( To ).focus();
}

/**
 * Funcao que copia o Html de um elemento para outro elemento.
 */
function copyHtml( From, To ){
	document.getElementById( To ).value += $( '#' + From ).html();
	document.getElementById( To ).focus();
}

/**
* Funcao que anima o menu. (OLD)
*/
/*$(document).ready(function(){
	$('.menu').find('ul:eq(0)> li > a').click(function(){
		$(this).parent().find('ul:eq(0)').slideToggle('speed');

		$('.submenu').find('ul:eq(0)> li > a').click(function(){
			$(this).parent().find('ul:eq(0)').slideToggle('speed');
		});
	});
});*/ 

// Funcoes uteis para controlar drop down list
// Exemplo: http://totalvox.w3br.com/iax.php - Codificadores
// ===================================================================
// Author: Matt Kruse <matt@mattkruse.com>
// WWW 1: http://www.mattkruse.com/
// WWW 2: http://www.mattkruse.com/javascript/selectbox/index.html
//
// NOTICE: You may use this code for any purpose, commercial or
// private, without any further permission from the author. You may
// remove this notice from your final code if you wish, however it is
// appreciated by the author if at least my web site address is kept.
//
// You may *NOT* re-distribute this code in any way except through its
// use. That means, you can include it in your product, or your web
// site, or any other form where the code is actually being used. You
// may not put the plain javascript up on your site for download or
// include it in your javascript libraries for download. 
// If you wish to share this code with others, please just point them
// to the URL instead.
// Please DO NOT link directly to my .js files from your site. Copy
// the files to your server and use them there. Thank you.
// ===================================================================

function hasOptions(obj){if(obj!=null && obj.options!=null){return true;}return false;}
function selectUnselectMatchingOptions(obj,regex,which,only){if(window.RegExp){if(which == "select"){var selected1=true;var selected2=false;}else if(which == "unselect"){var selected1=false;var selected2=true;}else{return;}var re = new RegExp(regex);if(!hasOptions(obj)){return;}for(var i=0;i<obj.options.length;i++){if(re.test(obj.options[i].text)){obj.options[i].selected = selected1;}else{if(only == true){obj.options[i].selected = selected2;}}}}}
function selectMatchingOptions(obj,regex){selectUnselectMatchingOptions(obj,regex,"select",false);}
function selectOnlyMatchingOptions(obj,regex){selectUnselectMatchingOptions(obj,regex,"select",true);}
function unSelectMatchingOptions(obj,regex){selectUnselectMatchingOptions(obj,regex,"unselect",false);}
function sortSelect(obj){var o = new Array();if(!hasOptions(obj)){return;}for(var i=0;i<obj.options.length;i++){o[o.length] = new Option( obj.options[i].text, obj.options[i].value, obj.options[i].defaultSelected, obj.options[i].selected) ;}if(o.length==0){return;}o = o.sort(
function(a,b){if((a.text+"") <(b.text+"")){return -1;}if((a.text+"") >(b.text+"")){return 1;}return 0;});for(var i=0;i<o.length;i++){obj.options[i] = new Option(o[i].text, o[i].value, o[i].defaultSelected, o[i].selected);}}
function selectAllOptions(obj){if(!hasOptions(obj)){return;}for(var i=0;i<obj.options.length;i++){obj.options[i].selected = true;}}
function unSelectAllOptions(obj){if(!hasOptions(obj)){return;}for(var i=0;i<obj.options.length;i++){obj.options[i].selected = false;}}
function moveSelectedOptions(from,to){if(arguments.length>3){var regex = arguments[3];if(regex != ""){unSelectMatchingOptions(from,regex);}}if(!hasOptions(from)){return;}for(var i=0;i<from.options.length;i++){var o = from.options[i];if(o.selected){if(!hasOptions(to)){var index = 0;}else{var index=to.options.length;}to.options[index] = new Option( o.text, o.value, false, false);}}for(var i=(from.options.length-1);i>=0;i--){var o = from.options[i];if(o.selected){from.options[i] = null;}}if((arguments.length<3) ||(arguments[2]==true)){sortSelect(from);sortSelect(to);}from.selectedIndex = -1;to.selectedIndex = -1;}
function copySelectedOptions(from,to){var options = new Object();if(hasOptions(to)){for(var i=0;i<to.options.length;i++){options[to.options[i].value] = to.options[i].text;}}if(!hasOptions(from)){return;}for(var i=0;i<from.options.length;i++){var o = from.options[i];if(o.selected){if(options[o.value] == null || options[o.value] == "undefined" || options[o.value]!=o.text){if(!hasOptions(to)){var index = 0;}else{var index=to.options.length;}to.options[index] = new Option( o.text, o.value, false, false);}}}if((arguments.length<3) ||(arguments[2]==true)){sortSelect(to);}from.selectedIndex = -1;to.selectedIndex = -1;}
function moveAllOptions(from,to){selectAllOptions(from);if(arguments.length==2){moveSelectedOptions(from,to);}else if(arguments.length==3){moveSelectedOptions(from,to,arguments[2]);}else if(arguments.length==4){moveSelectedOptions(from,to,arguments[2],arguments[3]);}}
function copyAllOptions(from,to){selectAllOptions(from);if(arguments.length==2){copySelectedOptions(from,to);}else if(arguments.length==3){copySelectedOptions(from,to,arguments[2]);}}
function swapOptions(obj,i,j){var o = obj.options;var i_selected = o[i].selected;var j_selected = o[j].selected;var temp = new Option(o[i].text, o[i].value, o[i].defaultSelected, o[i].selected);var temp2= new Option(o[j].text, o[j].value, o[j].defaultSelected, o[j].selected);o[i] = temp2;o[j] = temp;o[i].selected = j_selected;o[j].selected = i_selected;}
function moveOptionUp(obj){if(!hasOptions(obj)){return;}for(i=0;i<obj.options.length;i++){if(obj.options[i].selected){if(i != 0 && !obj.options[i-1].selected){swapOptions(obj,i,i-1);obj.options[i-1].selected = true;}}}}
function moveOptionDown(obj){if(!hasOptions(obj)){return;}for(i=obj.options.length-1;i>=0;i--){if(obj.options[i].selected){if(i !=(obj.options.length-1) && ! obj.options[i+1].selected){swapOptions(obj,i,i+1);obj.options[i+1].selected = true;}}}}
function removeSelectedOptions(from){if(!hasOptions(from)){return;}if(from.type=="select-one"){from.options[from.selectedIndex] = null;}else{for(var i=(from.options.length-1);i>=0;i--){var o=from.options[i];if(o.selected){from.options[i] = null;}}}from.selectedIndex = -1;}
function removeAllOptions(from){if(!hasOptions(from)){return;}for(var i=(from.options.length-1);i>=0;i--){from.options[i] = null;}from.selectedIndex = -1;}
//função alterada para receber parametro se deve repetir o valor ou nao. Por Marcos Luiz
function addOption(obj,text,value,selected,repeat){
			if(obj!=null && obj.options!=null){
				var erro = 0;
				if( hasOptions(obj) && repeat == false ){
					for(i=0;i<obj.options.length;i++){
						if((obj.options[i].value == value)&&(obj.options[i].text == text)){
							erro++;
						}
					}
				}
				if(erro == 0){	
					obj.options[obj.options.length] = new Option(text, value, false, selected);
				}	
			}	
		}
