/*Classe LibManivesUtility*/
	
/*Início do plugin TrocaTextoInput ---- x ---- x ---- x ---- x ---- x ---- x ---- x */
boolCampo = true; /*Var Booleana visa controlar o rececimento do focu no campo para que não caia em loop a troca do valor pelo campo na função AddValor*/
strCampo = ''; /*Var String obtém o valor do id do campo que foi adicionado */
strValor = '';

/*Criando o objeto LibM para ser usado em todo o sistema*/
LibM = new LibManivesUtility();

/*Habilitando o PNG para todo o site*/
//$(document).ready(function(){ $(document).pngFix(); }); 

/*Iniciando a construção da classe LibManivesUtility*/
function LibManivesUtility()
{
	/*
		- Plugin TrocaTextoInput para trocar um valor textual por um input
		É necessário que haja um elemento na página que receba o foco quando o enter for pressionado.
	  Nesse caso o elemento nomeado para receber o foco foi focus, um input hidden.
		
		- Variáveis Globais e de usuo para o plugin TrocaTextoInput
	*/
	
	/*Função para detectar o pressionamento da tecla enter e executa tirar o foco da tecla enter*/
	this.OnPress = function(strTeclaPressionada)
	{
		var strKeyCode = strTeclaPressionada.keyCode ? strTeclaPressionada.keyCode : strTeclaPressionada.charCode ? strTeclaPressionada.charCode : strTeclaPressionada.which ? strTeclaPressionada.which : void 0;
	
		if (strKeyCode == 13)
			$('#valorPesquisa').focus();
	}

	
	/*Função que troca o valor contido no elemento do campo input quantidade*/
	this.AddValor = function(objEleMesmo,idCount,idReferencia, strParametro)
	{
		if (boolCampo == true)
		{
			strValor = $(objEleMesmo).text();
			$(objEleMesmo).html('');
			if (strParametro == 'Q')
				$(objEleMesmo).html('<input type="text" fatorEmbalagem="' + $(objEleMesmo).attr('fatorEmabalagemResumo') +  '" name="campo_value" style="width:100%;font-size:10px; border:none;" id="campo_value" value="' + parseInt(retirarFormatacao(strValor)) + '" onKeyPress="LibM.OnPress(event); Mascara(this,SomenteNumeros);" onFocus="$(this).attr(\'valor_anterior\',$(this).val())" onBlur="TratarValorZerado(this,\'' + idReferencia + '\',\'' + idCount +  '\'); LibM.VoltarValor(this,\'Q\'); SomarItensGrade(\'' + idReferencia + '\',\'' + idCount +  '\'); UpdateLinha(\'' + idReferencia + '\',\'' + idCount +  '\'); ">');
			if (strParametro == 'P')
				$(objEleMesmo).html('<input type="text" name="campo_value" style="width:100%; font-size:10px; border:none;" size="8" maxlength="6" id="campo_value" value="' + strValor + '" onKeyPress="LibM.OnPress(event); return(FormatarValorDigitado(this,\'\',\',\',event));" onFocus="$(this).attr(\'valor_desc_anterior\',$(this).val());" onBlur="LibM.VoltarValor(this,\'P\'); AplicarDesconto(this,\'' + idCount +  '\'); UpdateLinha(\'' + idReferencia + '\',\'' + idCount +  '\');">');
			if (strParametro == 'A' )
				$(objEleMesmo).html('<input type="text" name="campo_value" style="width:100%;font-size:10px; border:none;" id="campo_value" value="' +strValor + '" onKeyPress="LibM.OnPress(event); return(FormatarValorDigitado(this,\'\',\',\',event)); " onFocus="$(this).attr(\'valor_desc_anterior\',$(this).val())" onBlur="LibM.VoltarValor(this,\'A\'); TratarDescontoAliquota(this,\'' + idCount +  '\'); UpdateItemDaNota(\'' + idReferencia + '\',\'' + idCount +  '\'); ">');
			if (strParametro == 'N')
				$(objEleMesmo).html('<input type="text" fatorEmbalagem="' + $(objEleMesmo).attr('fatorEmabalagemResumo') +  '" name="campo_value" style="width:100%;font-size:10px; border:none;" id="campo_value" value="' + parseInt(retirarFormatacao(strValor)) + '" onKeyPress="LibM.OnPress(event); Mascara(this,fuc_soNumeros);" onFocus="$(this).attr(\'valor_anterior\',$(this).val())" onBlur="TratarValorZerado(this,\'' + idReferencia + '\',\'' + idCount +  '\'); LibM.VoltarValor(this,\'Q\'); SomarItensGrade(\'' + idReferencia + '\',\'' + idCount +  '\'); UpdateLinha(\'' + idReferencia + '\',\'' + idCount +  '\',\'' + $(objEleMesmo).attr('cod_pedido_item') + '\'); ">');
			boolCampo = false;
			strCampo = $(objEleMesmo).attr('id');
			$('#campo_value').focus();
		}
	}   

	/*Função para retornar o valor preenchido no campo input para o elemento antigo*/
	this.VoltarValor = function(objEleMesmo,strParametro)
	{
		boolCampo = true;
		strValor = $(objEleMesmo).val();
		
		if (strValor == '')
			strValor = 0;
		if (strParametro == 'Q')
			$(objEleMesmo).parent().html(LibM.FormatarIteiroDeSaida(parseInt(strValor)));
		if (strParametro == 'P')
			$(objEleMesmo).parent().html(strValor);			
		if (strParametro == 'A')
			$(objEleMesmo).parent().html(strValor);
			
		$(objEleMesmo).remove();
	}
	/*Fim do plugin TrocaTextoInput ---- x ---- x ---- x ---- x ---- x ---- x ---- x */
	
	
	/*Função que gera um número aleatório com entre os um valor mínimo e máximo
		exemplo: Aleatorio(1,200);
		retornaria:33
	*/
	this.Aleatorio = function(intInferior,intSuperior)
	{
    intPossibilidades = intSuperior - intInferior
    intNumAleatorio = Math.random() * intPossibilidades
    intNumAleatorio = Math.floor(intNumAleatorio)
    return parseInt(intInferior) + intNumAleatorio
	} 


	/*Função de zebrar uma tabela*/
	this.ZebrarTabela = function(objId, strCor1, strCor2)
	{
	 $(objId).each(function(intCount) 
	 {
		if((intCount%2) == 0)
		 $(this).attr("bgColor", strCor1);
		else
		 $(this).attr("bgColor", strCor2);
	 });
	}

  
	/*Formata a saída de um número inteiro
		exemplo: 1000.05
		retornaria: 1.000,05
	*/
	this.FormatarIteiroDeSaida = function(intNum)
	{
    var intS = intNum.toString();
		var intP;
    for(intP = intS.length; (intP -= 3) > 0;)
    	intS = intS.substr(0, intP) + "." + intS.substr(intP);
    return intS;
	}

	/*Função que soma os valores contidos em uma coluna de uma tabela. A função antes usa a Retirar Formatação pois ela trabalha com os valores dos textos contidos em cada célula da tabela. */
	this.SomarColunaTabela = function(objId)
	{
		var fltTotal = 0; 
		$(objId).each(function(){
		 fltTotal += parseFloat(LibM.RetirarFormatacao($(this).text()));
		});
		return fltTotal;
	}	

	
	/*Função para formatar valores em reais*/
	this.FormatarSaidaMoeda = function(intNum) 
	{
		var intX = 0;
		
		if(intNum<0) 
		{
			intNum = Math.abs(intNum);
			intX = 1;
		}	
		if(isNaN(intNum)) 
			intNum = "0";
		strCentavos = Math.floor((intNum*100+0.5)%100);	
		intNum = Math.floor((intNum*100+0.5)/100).toString();
		if(strCentavos < 10) 
			strCentavos = "0" + strCentavos;
		for (var i = 0; i < Math.floor((intNum.length-(1+i))/3); i++)
			intNum = intNum.substring(0,intNum.length-(4*i+3)) + '.' + intNum.substring(intNum.length-(4*i+3));	
		strRetorno = intNum + ',' + strCentavos;	
		if (intX == 1) 
			strRetorno = ' - ' + strRetorno;
		return strRetorno;
	}
	
	/*Fução que conta quantos elementos há em um outro, tipo quantos tr tem em uma table*/
	this.ContarElementosContidos = function(objContener,objConteudo)
	{
		 return $(objContener).find(objConteudo).size()
	}

	/*Função para obter o texto de um combobox*/
	this.ObterTextoComboBox = function(objEleMesmo,strTypeComparacao)
	{
		var varintCod = $(objEleMesmo).val();
		var strTextoComboBox = '';
		if(varintCod != strTypeComparacao)
		{
			$(objEleMesmo + ' option').each(function()
			{
				if($(this).val() == varintCod)
				{
				strTextoComboBox = $(this).html();
				}
			});
			return strTextoComboBox;		
		}
		else
			return false;		
	}

	this.ObterValorCheckboxMarcado = function(strId)
	{
		var valor = -1;
		$("input[id=" + strId + "]").each(function() 
		{
			if(this.checked == true)
			{
				valor = this.value;
			}
		});
		return valor;
	}

	/*Função que remove itens duplicados em um vetor.
		 *example 1: array_unique(['Kevin','Kevin','van','Zonneveld','Kevin']);
		 returns 1: ['Kevin','van','Zonneveld']
		 * example 2: array_unique({'a': 'green', 0: 'red', 'b': 'green', 1: 'blue', 2: 'red'});
		 *x returns 2: {'a': 'green', 0: 'red', 1: 'blue'}
	*/
	this.ArrayUnique = function(array){
	var intKey = '', tmpArr1 = {}, tmpArr2 = {};
	var strVal = '';
	tmpArr1 = array;
	
	var __ArraySearch = function(strElemento, strConjuntoElementos, strRestringir)
	{
			var intKeyPesquisado = '';
			var strRestringir = !!strRestringir;
			for (intKeyPesquisado in strConjuntoElementos) 
			{
					if ((strRestringir && strConjuntoElementos[intKeyPesquisado] === strElemento) || (!strRestringir && strConjuntoElementos[intKeyPesquisado] == strElemento) ) 
					{
							return intKeyPesquisado;
					}
			}
			return false;
	}    
		for (intKey in tmpArr1)
		{
				strVal = tmpArr1[intKey];
				if (false === __ArraySearch(strVal, tmpArr2))
				{
						tmpArr2[intKey] = val;
				}
				delete tmpArr1[intKey];
		}
		return tmpArr2;
	} 
		
	/*Função que abate um valor percentua de um outro informado*/
	this.AbaterValorPercentual = function(fltTotal,fltParcela)
	{
		return LibM.ArredondarFloat(parseFloat(fltTotal) - ((parseFloat(fltParcela) / 100) * parseFloat(fltTotal)));
	}

  /*Arredonda número flutuante*/
	this.ArredondarFloat = function(fltValue) {
  	return Math.round( fltValue * Math.pow(10,2) ) / Math.pow(10,2);
	}
	
	/*Função que preenche um determinado número com uma quantidade especificada de zeros a esquerda*/
	this.PreencherComZerosAEsquerda = function(strValue,intQtdCaracteres)
	{
		var strZeros = '';
		var intCount = 0;
		
		for(intCount = 0; intCount < intQtdCaracteres - strValue.length; intCount++)
		{
			strZeros += '0';
		}
		return strZeros + strValue;
	}	
	
	
	/*Função para retirar a formatação de um falor flutuante
		exemplo: 1.000,05
		retornaria: 1000.05
	*/
	this.RetirarFormatacao = function(strValor)
	{
		if (strValor != '')
		{
			strValor = strValor.replace(/\./g,"");
			strValor = strValor.replace(/\,/g,".");
			return strValor;
		}
	}
	/*Função que calcula soma ou abate um intervalo de dias meses ou ano da data fornecida
	  O formato da data é mm/dd/YYYY
	  * exemplo: CalculaData('12/11/2000', - 1, 'ano');
		  retornaria: 12/11/1999
  */
	this.CalculaData = function(strData, intPeriodo, strTipo)
	{
		strNovaData = new Date();
		strData = strData.split("/");
		strNovaData.setDate(parseInt(strData[0]));
		strNovaData.setMonth(parseInt(strData[1]));
		strNovaData.setYear(parseInt(strData[2]));
		switch(strTipo)
		{
		  case 'dia':
				strNovaData.setDate(parseInt(strData[0]) + parseInt(intPeriodo));
				return strNovaData.getDate().toString() + '/' + (strNovaData.getMonth()).toString() + '/' + strNovaData.getFullYear().toString();	
 			break;
			case 'mes':
				strNovaData.setMonth(parseInt(strData[1]) + parseInt(intPeriodo));
				return strNovaData.getDate().toString() + '/' + (strNovaData.getMonth()).toString() + '/' + strNovaData.getFullYear().toString();
			break;
			case 'ano':
				strNovaData.setYear(parseInt(strData[2]) + parseInt(intPeriodo));
				return strNovaData.getDate().toString() + '/' + (strNovaData.getMonth()).toString() + '/' + strNovaData.getFullYear().toString();
			break;
		}    
 
	}
	
	/*Função que compara duas datas e retona true se uma é maior do que a outra*/
	this.ComparaDatas = function( strData1, strMaiorMenor, strData2 )
	{
      strData1 = strData1.split("/");
			strData2 = strData2.split("/");
			
			if (strData2[0].length == 1)
			strData2[0] = "0" + strData2[0]
			
			strData1 = parseInt(strData1[2]) + '' + parseInt(strData1[1]) + '' + strData1[0];
	 		strData2 = parseInt(strData2[2]) + '' + parseInt(strData2[1]) + '' + strData2[0];
			
	    // virficando que tipo de comparação deve ser feita entre as datas
	    switch (strMaiorMenor) {
	      case '<':
	          return ( (parseInt(strData1) < parseInt(strData2)) ? true : false );
	    	break;
	    	case '>':
	          return ( (parseInt(strData1) > parseInt(strData2)) ? true : false );
	    	break;
	    	case '<=':
	          return ( (parseInt(strData1) <= parseInt(strData2)) ? true : false );
	    	break;
	    	case '>=':
	          return ( (parseInt(strData1) >= parseInt(strData2)) ? true : false );
	    	break;
	    }
	}
	
	/*Função que centraliza um objeto na tela passando o elemento a largura a altura e o seu Zindex*/
	this.centralizar = function(objId,intL,intA,intZindex)
	{
		var intLargura;
		var intAltura;
		
		intLargura = $(objId).css('width');
		intAltura = $(objId).css('height');
		intAltura = intAltura.replace(/px/g,"");
		intLargura = intLargura.replace(/px/g,"");
		
		intLargura /=  -1 * (2 + intL);
		intAltura /= -1 * (2 + intA);
		
		$(objId).css({position: 'absolute',left:'50%', top:'50%',marginLeft: intLargura + 'px', marginTop: intAltura + 'px', zIndex:intZindex}); 
	}
	
	/*Função que centraliza um objeto na tela passando o elemento o left o top e o seu Zindex*/
	this.Posicionar = function(objId,intLeft,intTop,intZindex)
	{
		$(objId).css({position: 'absolute',left:intLeft + 'px', top:intTop + 'px', zIndex:intZindex});
	}


	this.ValidarImagem = function(strId,strMascaras)
	{
		
		var strImg = $(strId).val();
		var arrExtensoes = strMascaras.split('|');
		var boolFlag = false;
		var strExt = strImg.substr(strImg.lastIndexOf('.')+1, strImg.length);
		if (strImg != '')
		{
			for (i=0; i <= arrExtensoes.length-1; i++)
			{
				if (arrExtensoes[i] == strExt )
				{
					boolFlag = true;
				}
			}
			if (boolFlag == false)
			{
				alert('Somente são permitidos arquivos comas as seguintes extensões: ' + strMascaras.replace(/\|/g," | ").toUpperCase());
				$(strId).val('');
				$(strId).focus();
				return false
			}
		}
	}
		
	/*Função que gera uma popup fornecendo uma url sua largura e altura*/
	var popUpWin=0;
	this.PopUpWindow = function(strURL,width, height)
	{
		
		if(popUpWin)
		{
			if(!popUpWin.closed) 
				popUpWin.close();
		}
	 popUpWin = open(strURL, 'popUpWin', 'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,copyhistory=no,width='+width+',height='+height+'');
	}

	this.RetornoData = function(strTipo)
	{
		var strDataAtual = new Date();
		switch (strTipo)
		{
			case 'ano':
			 return strDataAtual.getUTCFullYear();
			break;
			case 'mes':
			 return strDataAtual.getUTCMonth();
			break;
			case 'dia':
			 return strDataAtual.getUTCDay();
			break;
			case 'data_completa':
			 return  strDataAtual.getUTCDay() + '/' + strDataAtual.getUTCMonth() + '/' + strDataAtual.getUTCFullYear();
			break;	
		}	
	}
	
	this.EliminaPontoMascaraData = function(strValue)
	{
	  var strAno = strValue.replace(/\./g,"");
		return strAno;
	}
	
	this.URLEncode = function(plaintext)
	{
		var SAFECHARS = "0123456789" +					// Numeric
						"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +	// Alphabetic
						"abcdefghijklmnopqrstuvwxyz" +
						"-_.!~*'";					// RFC2396 Mark characters
		var HEX = "0123456789ABCDEF";
	
		var encoded = "";
		for (var i = 0; i < plaintext.length; i++ ) {
			var ch = plaintext.charAt(i);
				if (ch == " ") {
					encoded += "+";				// x-www-urlencoded, rather than %20
			} else if (SAFECHARS.indexOf(ch) != -1) {
					encoded += ch;
			} else {
					var charCode = ch.charCodeAt(0);
				if (charCode > 255) {
						alert("Unicode Character '" 
													+ ch 
													+ "' cannot be encoded using standard URL encoding.\n" +
										"(URL encoding only supports 8-bit characters.)\n" +
								"A space (+) will be substituted." );
					encoded += "+";
				} else {
					encoded += "%";
					encoded += HEX.charAt((charCode >> 4) & 0xF);
					encoded += HEX.charAt(charCode & 0xF);
				}
			}
		} // for
	
		return encoded;
	};

	this.MarcarCheckbox = function(strValidacao,objId)
	{
		if (strValidacao == '1')  
			$(objId).attr('checked','true')
		else  
			$(objId).attr('checked','')
	}
	
	this.SetarFocus = function(objId)
	{
  	$(objId).focus();
	}
	
	this.ChecarTodosMarcados = function(strDiv,strTypeItem)
	{
		var objCheck = $(strDiv + ' :' + strTypeItem).get();	
		var strChecked = '';
		$.each(objCheck,function(k,v){
			 if (v.checked == false)
					strChecked += v.name;
					
		});
		if (strChecked == '')
			return true
		else
			return false
	}
	
	this.ChecarMarcados = function(strDiv,strTypeItem)
	{
		var objCheck = $(strDiv + ' :' + strTypeItem).get();	
		var strChecked = '';
		$.each(objCheck,function(k,v){
			 if (v.checked)
					strChecked += v.name;
					
		});
		if (strChecked == '')
		 return false
		else
		 return true
	}
	
	//checa vírgula na string
	this.TestaVirgula = function(objId)
	{
		var RegExp = /,/g;
		if(!RegExp.test($(objId).val()))
			$(objId).val('');
	}

	//Valida URL
	this.ValidarURL = function(strUrl)
	{
		var RegExp = /^(([\w]+:)?\/\/)?(([\d\w]|%[a-fA-f\d]{2,2})+(:([\d\w]|%[a-fA-f\d]{2,2})+)?@)?([\d\w][-\d\w]{0,253}[\d\w]\.)+[\w]{2,4}(:[\d]+)?(\/([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)*(\?(&?([-+_~.\d\w]|%[a-fA-f\d]{2,2})=?)*)?(([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)?$/;
		if(RegExp.test(strUrl))
			return true;
		else
			return false;
	}

	// Valida CPF
	this.ValidaCPF = function(textCpf)
	{
		var i;
		var s;
		s =  textCpf.replace(/\./g,"");
		s =  s.replace(/-/g,"");
		if( s == "00000000000" || s == "11111111111" ||
			s == "22222222222" || s == "33333333333" || s == "44444444444" ||
			s == "55555555555" || s == "66666666666" || s == "77777777777" ||
			s == "88888888888" || s == "99999999999")
		{
			alert('Você deve informar um CPF válido.');
			return false;
		}
		 
		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)
		{
			alert('Você deve informar um CPF válido.');
			return false;
		}
		d1 = 11 - (d1 % 11);
		if (d1 > 9) 
			d1 = 0;
		if (dv.charAt(0) != d1)
		{
			alert('Você deve informar um CPF válido.');
			return 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)
		{
			alert('Você deve informar um CPF válido.');
			return false;
		}
		return true;
	}
	
	// Função para testar caracteres especiais em campos de logins
  
  this.TestaCaracterEspecial = function(strValue) 
	{
		var strPadrao = /\W/;
		strOk = strPadrao.exec(strValue);
		if (strOk)
			return true
		else
			return false
	}
	
	// Inicio da função da validação de e-mail.
	this.TestaEmail = function(strEmail)
	{
		var strPadrao = new RegExp;
		strPadrao = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
		var strArgumento = strPadrao.exec(strEmail);
		if (strArgumento == null)
			return false
	}

	this.ValidaDataMaior = function(strData, strDataComparacao)
	{
		if (strData != '')
		{
			objData = new Date(strData.substr(6, 4), parseInt(strData.substr(3, 2), 10) - 1, parseInt(strData.substr(0, 2), 10)); 
			if (typeof(strDataComparacao) != "object") 
			{
				objDataComparacao = new Date(strDataComparacao.substr(6, 4), parseInt(strDataComparacao.substr(3, 2), 10) - 1, parseInt(strDataComparacao.substr(0, 2), 10))
				if (objData < objDataComparacao)
					return false;
			}
		}
	}
	
	//função que valida uma data em javascript
	this.ValidaData = function(strCampo)
	{
		if (strCampo.value!="")
		{
			strHoje = new Date();
			strAnoAtual = strHoje.getFullYear();
			arrBarras = strCampo.value.split("/");
			if (arrBarras.length == 3)
			{
				intDia = arrBarras[0];
				intMes = arrBarras[1];
				intAno = arrBarras[2];
				strResultado = (!isNaN(intDia) && (intDia > 0) && (intDia < 32)) && (!isNaN(intMes) && (intMes > 0) && (intMes < 13)) && (!isNaN(intAno) && (intAno.length == 4) && (intAno > 1900));
				if (!strResultado)
					return false;
			}
		}
		else
		{
			return false;
		}
		return true;
	}
	
	this.ValidaHora = function(strCampo)
	{
		if (strCampo.value!="")
		{
			arrPontos = strCampo.value.split(":");
			if (arrPontos.length == 2)
			{
				intHora = arrPontos[0];
				intMinuto = arrPontos[1];
				strResultado = (!isNaN(intHora) && (intHora >= 0) && (intHora < 25)) && (!isNaN(intMinuto) && (intMinuto >=0) && (intMinuto < 65));
				if (!strResultado)
					return false;
			}
		}
		else
		{
			return false;
		}
		return true;
	}
	
	// Inicio da função do campo númerico
	this.TestaInteiro = function(strField)
	{
		var intExp = strField.value;
		if (isNaN(intExp) || (intExp.length == 0))
			return false;
		else
			return true;
	}

  this.ConverterParaMaisculo = function(objId)
	{
		return objId.value.toUpperCase();
 	}
	
	this.ConverterParaMinusculo = function(objId)
	{
		return objId.value.toLowerCase();
	}
	
	this.PrimeiraLetraMaiuscula = function(frmObj)
	{
		var index;
		var tmpStr;
		var tmpChar;
		var preString;
		var postString;
		var strlen;
		tmpStr = frmObj.value.toLowerCase();
		strLen = tmpStr.length;
		if (strLen > 0)
		{
			for (index = 0; index < strLen; index++)
			{
				if (index == 0)
				{
					tmpChar = tmpStr.substring(0,1).toUpperCase();
					postString = tmpStr.substring(1,strLen);
					tmpStr = tmpChar + postString;
				}
				else
				{
					tmpChar = tmpStr.substring(index, index+1);
					if (tmpChar == " " && index < (strLen-1))
					{
						tmpChar = tmpStr.substring(index+1, index+2).toUpperCase();
						preString = tmpStr.substring(0, index+1);
						postString = tmpStr.substring(index+2,strLen);
						tmpStr = preString + tmpChar + postString; 
					}
				}
		  }
	  }
		frmObj.value = tmpStr;
	}


	// Funções que validam formatação de campos.
	this.Mascara = function(obj,strFuncao)
	{
		objElemento = obj;
		objFuncao = strFuncao;
		setTimeout("LibM.ExecutarMascara()",1)
	}

  this.ExecutarMascara = function()
	{
    objElemento.value = objFuncao(objElemento.value);
  }

  this.CaracteresParaCamposComuns = function(strTexto)
	{ //onKeyPress="Mascara(this,CaracteresParaCamposComuns)"
		/* para usar em campos com letras e números e espaços*/
	  return strTexto.replace(/[^abcdefghijklmnopqrstuvwxyzABCÇDEFGHIJLKMNOPRSTUVWXYZ0123456789áéíóúàèìòùâêîôûãõç .]/g,"")
	}

	this.CaracteresParaEndereco = function(strTexto)
	{ //onKeyPress="Mascara(this,CaracteresParaEndereco)"
		 /*para usar em endereços*/
		 return strTexto.replace(/[^abcdefghijklmnopqrstuvwxyzABCÇDEFGHIJLKMNOPRSTUVWXYZ0123456789áéíóúàèìòùâêîôûãõç º ,.]/g,"")
	}
	
	this.CaracteresAceitosEmEmail = function(strTexto)
	{ //onKeyPress="Mascara(this,CaracteresAceitosEmEmail)"
		 /*para usar em endereços*/
		 return strTexto.replace(/[^abcdefghijklmnopqrstuvwxyzABCDEFGHIJLKMNOPRSTUVWXYZ0123456789.-_@]/g,"")
	} 
	
	this.ValidaNumerosRomanos = function(strTexto)
	{
		strTexto = strTexto.toUpperCase();             //Maiúsculas
		strTexto = strTexto.replace(/[^IVXLCDM]/g,""); //Remove tudo o que não for I, V, X, L, C, D ou M
		//Essa é complicada! Copiei daqui: http://www.diveintopython.org/refactoring/refactoring.html
		while(strTexto.replace(/^M{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$/,"")!="");
				strTexto=strTexto.replace(/.$/,"");
		return strTexto
	}
	
	this.SomenteNumeros = function(strTexto){ //onKeyPress="fuc_mascara(this,fuc_soNumeros)"
		return strTexto.replace(/\D/g,"")
	}
	 
	this.FormatarValorDigitado = function(strTexto)
	{
		strTexto = strTexto.replace(/\D/g,"") //Remove tudo o que não é dígito
		strTexto = strTexto.replace(/^([0-9]{3}\.?){3}-[0-9]{2}$/,"$1.$2");
		//v=v.replace(/(\d{3})(\d)/g,"$1,$2")
		strTexto = strTexto.replace(/(\d)(\d{2})$/,"$1.$2") //Coloca ponto antes dos 2 últimos digitos
		return strTexto
	}
	
	this.ValidaSite = function(strURL)
	{
		strURL = strURL.replace(/^http:\/\/?/,"");
		strDominio = strURL;
		strCaminho = "";
		if(strURL.indexOf("/") > -1);
		strDominio = strURL.split("/")[0];
		strCaminho = strURL.replace(/[^\/]*/,"");
		strDominio = strDominio.replace(/[^\w\.\+-:@]/g,"");
		strCaminho = strCaminho.replace(/[^\w\d\+-@:\?&=%\(\)\.]/g,"");
		strCaminho = strCaminho.replace(/([\?&])=/,"$1")
		if(strCaminho != "")
			strDominio = strDominio.replace(/\.+$/,"");
			
		strURL = "http://" + strDominio + strCaminho;
		return strURL
	}
	
	
	this.ArredondarFloats = function(fltNum) 
	{
		return Math.round(fltNum * Math.pow(10,2)) / Math.pow(10,2);
	}
	
	this.FormataMoeda = function(objTextBox, SeparadorMilesimo, SeparadorDecimal, e)
	{
		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;
	}

}
/*Fim da Classe LibManivesUtility --------------------------------------------------------------------------------------------------------*/

// Mascaras Utilizando a Jquery Plugin *********************************************************************************************************
/*jQuery(function($){ // aqui ativamos a chamada para aplicar a formatação dos campos.
   $("#id_datanascimento").mask("99/99/9999");
   $("#id_pretencaosalarial").mask("(999) 999-9999");

});*/
(function($) {

	//Helper Function for Caret positioning
	$.fn.caret=function(begin,end){	
		if(this.length==0) return;
		if (typeof begin == 'number') {
            end = (typeof end == 'number')?end:begin;  
			return this.each(function(){
				if(this.setSelectionRange){
					this.focus();
					this.setSelectionRange(begin,end);
				}else if (this.createTextRange){
					var range = this.createTextRange();
					range.collapse(true);
					range.moveEnd('character', end);
					range.moveStart('character', begin);
					range.select();
				}
			});
        } else {
            if (this[0].setSelectionRange){
				begin = this[0].selectionStart;
				end = this[0].selectionEnd;
			}else if (document.selection && document.selection.createRange){
				var range = document.selection.createRange();			
				begin = 0 - range.duplicate().moveStart('character', -100000);
				end = begin + range.text.length;
			}
			return {begin:begin,end:end};
        }       
	};

	//Predefined character definitions
	var charMap={
		'9':"[0-9]",
		'a':"[A-Za-z]",
		'*':"[A-Za-z0-9]"
	};
	
	//Helper method to inject character definitions
	$.mask={
		addPlaceholder : function(c,r){
			charMap[c]=r;
		}
	};
	
	$.fn.unmask=function(){
		return this.trigger("unmask");
	};
	
	//Main Method
	$.fn.mask = function(mask,settings) {	
		settings = $.extend({
			placeholder: "",			
			completed: null
		}, settings);		
		
		//Build Regex for format validation
		var re = new RegExp("^"+	
		$.map( mask.split(""), function(c,i){		  		  
		  return charMap[c]||((/[A-Za-z0-9]/.test(c)?"":"\\")+c);
		}).join('')+				
		"$");		

		return this.each(function(){		
			var input=$(this);
			var buffer=new Array(mask.length);
			var locked=new Array(mask.length);
			var valid=false;   
			var ignore=false;  			//Variable for ignoring control keys
			var firstNonMaskPos=null; 
			
			//Build buffer layout from mask & determine the first non masked character			
			$.each( mask.split(""), function(i,c){				
				locked[i]=(charMap[c]==null);				
				buffer[i]=locked[i]?c:settings.placeholder;									
				if(!locked[i] && firstNonMaskPos==null)
					firstNonMaskPos=i;
			});		
			
			function focusEvent(){					
				checkVal();
				writeBuffer();
				setTimeout(function(){
					$(input[0]).caret(valid?mask.length:firstNonMaskPos);					
				},0);
			};
			
			function keydownEvent(e){				
				var pos=$(this).caret();
				var k = e.keyCode;
				ignore=(k < 16 || (k > 16 && k < 32 ) || (k > 32 && k < 41));
				
				//delete selection before proceeding
				if((pos.begin-pos.end)!=0 && (!ignore || k==8 || k==46)){
					clearBuffer(pos.begin,pos.end);
				}	
				//backspace and delete get special treatment
				if(k==8){//backspace					
					while(pos.begin-->=0){
						if(!locked[pos.begin]){								
							buffer[pos.begin]=settings.placeholder;
							if($.browser.opera){
								//Opera won't let you cancel the backspace, so we'll let it backspace over a dummy character.								
								s=writeBuffer();
								input.val(s.substring(0,pos.begin)+" "+s.substring(pos.begin));
								$(this).caret(pos.begin+1);								
							}else{
								writeBuffer();
								$(this).caret(Math.max(firstNonMaskPos,pos.begin));								
							}									
							return false;								
						}
					}						
				}else if(k==46){//delete
					clearBuffer(pos.begin,pos.begin+1);
					writeBuffer();
					$(this).caret(Math.max(firstNonMaskPos,pos.begin));					
					return false;
				}else if (k==27){//escape
					clearBuffer(0,mask.length);
					writeBuffer();
					$(this).caret(firstNonMaskPos);					
					return false;
				}									
			};
			
			function keypressEvent(e){					
				if(ignore){
					ignore=false;
					//Fixes Mac FF bug on backspace
					return (e.keyCode == 8)? false: null;
				}
				e=e||window.event;
				var k=e.charCode||e.keyCode||e.which;						
				var pos=$(this).caret();
								
				if(e.ctrlKey || e.altKey){//Ignore
					return true;
				}else if ((k>=41 && k<=122) ||k==32 || k>186){//typeable characters
					var p=seekNext(pos.begin-1);					
					if(p<mask.length){
						if(new RegExp(charMap[mask.charAt(p)]).test(String.fromCharCode(k))){
							buffer[p]=String.fromCharCode(k);									
							writeBuffer();
							var next=seekNext(p);
							$(this).caret(next);
							if(settings.completed && next == mask.length)
								settings.completed.call(input);
						}				
					}
				}				
				return false;				
			};
			
			function clearBuffer(start,end){
				for(var i=start;i<end&&i<mask.length;i++){
					if(!locked[i])
						buffer[i]=settings.placeholder;
				}				
			};
			
			function writeBuffer(){				
				return input.val(buffer.join('')).val();				
			};
			
			function checkVal(){	
				//try to place charcters where they belong
				var test=input.val();
				var pos=0;
				for(var i=0;i<mask.length;i++){					
					if(!locked[i]){
						buffer[i]=settings.placeholder;
						while(pos++<test.length){
							//Regex Test each char here.
							var reChar=new RegExp(charMap[mask.charAt(i)]);
							if(test.charAt(pos-1).match(reChar)){
								buffer[i]=test.charAt(pos-1);								
								break;
							}									
						}
					}
				}
				var s=writeBuffer();
				if(!s.match(re)){							
					input.val("");	
					clearBuffer(0,mask.length);
					valid=false;
				}else
					valid=true;
			};
			
			function seekNext(pos){				
				while(++pos<mask.length){					
					if(!locked[pos])
						return pos;
				}
				return mask.length;
			};
			
			input.one("unmask",function(){
				input.unbind("focus",focusEvent);
				input.unbind("blur",checkVal);
				input.unbind("keydown",keydownEvent);
				input.unbind("keypress",keypressEvent);
				if ($.browser.msie) 
					this.onpaste= null;                     
				else if ($.browser.mozilla)
					this.removeEventListener('input',checkVal,false);
			});
			input.bind("focus",focusEvent);
			input.bind("blur",checkVal);
			input.bind("keydown",keydownEvent);
			input.bind("keypress",keypressEvent);
			//Paste events for IE and Mozilla thanks to Kristinn Sigmundsson
			if ($.browser.msie) 
				this.onpaste= function(){setTimeout(checkVal,0);};                     
			else if ($.browser.mozilla)
				this.addEventListener('input',checkVal,false);
				
			checkVal();//Perform initial check for existing values
		});
	};
})(jQuery);
// Mascaras Fim ********************************************************************************************************************************* 


/*Aqui começa o plugin para swf crossbrowser*
/**
 * Flash (http://jquery.lukelutman.com/plugins/flash)
 * A jQuery plugin for embedding Flash movies.
 * 
 * Version 1.0
 * November 9th, 2006
 *
 * Copyright (c) 2006 Luke Lutman (http://www.lukelutman.com)
 * Dual licensed under the MIT and GPL licenses.
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.opensource.org/licenses/gpl-license.php
 * 
 * Inspired by:
 * SWFObject (http://blog.deconcept.com/swfobject/)
 * UFO (http://www.bobbyvandersluis.com/ufo/)
 * sIFR (http://www.mikeindustries.com/sifr/)
 * 
 * IMPORTANT: 
 * The packed version of jQuery breaks ActiveX control
 * activation in Internet Explorer. Use JSMin to minifiy
 * jQuery (see: http://jquery.lukelutman.com/plugins/flash#activex).
 *
 **/ 
	;(function(){
		
	var $$;
	
	/**
	 * 
	 * @desc Replace matching elements with a flash movie.
	 * @author Luke Lutman
	 * @version 1.0.1
	 *
	 * @name flash
	 * @param Hash htmlOptions Options for the embed/object tag.
	 * @param Hash pluginOptions Options for detecting/updating the Flash plugin (optional).
	 * @param Function replace Custom block called for each matched element if flash is installed (optional).
	 * @param Function update Custom block called for each matched if flash isn't installed (optional).
	 * @type jQuery
	 *
	 * @cat plugins/flash
	 * 
	 * @example $('#hello').flash({ src: 'hello.swf' });
	 * @desc Embed a Flash movie.
	 *
	 * @example $('#hello').flash({ src: 'hello.swf' }, { version: 8 });
	 * @desc Embed a Flash 8 movie.
	 *
	 * @example $('#hello').flash({ src: 'hello.swf' }, { expressInstall: true });
	 * @desc Embed a Flash movie using Express Install if flash isn't installed.
	 *
	 * @example $('#hello').flash({ src: 'hello.swf' }, { update: false });
	 * @desc Embed a Flash movie, don't show an update message if Flash isn't installed.
	 *
	**/
	$$ = jQuery.fn.flash = function(htmlOptions, pluginOptions, replace, update) {
		
		// Set the default block.
		var block = replace || $$.replace;
		
		// Merge the default and passed plugin options.
		pluginOptions = $$.copy($$.pluginOptions, pluginOptions);
		
		// Detect Flash.
		if(!$$.hasFlash(pluginOptions.version)) {
			// Use Express Install (if specified and Flash plugin 6,0,65 or higher is installed).
			if(pluginOptions.expressInstall && $$.hasFlash(6,0,65)) {
				// Add the necessary flashvars (merged later).
				var expressInstallOptions = {
					flashvars: {  	
						MMredirectURL: location,
						MMplayerType: 'PlugIn',
						MMdoctitle: jQuery('title').text() 
					}					
				};
			// Ask the user to update (if specified).
			} else if (pluginOptions.update) {
				// Change the block to insert the update message instead of the flash movie.
				block = update || $$.update;
			// Fail
			} else {
				// The required version of flash isn't installed.
				// Express Install is turned off, or flash 6,0,65 isn't installed.
				// Update is turned off.
				// Return without doing anything.
				return this;
			}
		}
		
		// Merge the default, express install and passed html options.
		htmlOptions = $$.copy($$.htmlOptions, expressInstallOptions, htmlOptions);
		
		// Invoke $block (with a copy of the merged html options) for each element.
		return this.each(function(){
			block.call(this, $$.copy(htmlOptions));
		});
		
	};
	/**
	 *
	 * @name flash.copy
	 * @desc Copy an arbitrary number of objects into a new object.
	 * @type Object
	 * 
	 * @example $$.copy({ foo: 1 }, { bar: 2 });
	 * @result { foo: 1, bar: 2 };
	 *
	**/
	$$.copy = function() {
		var options = {}, flashvars = {};
		for(var i = 0; i < arguments.length; i++) {
			var arg = arguments[i];
			if(arg == undefined) continue;
			jQuery.extend(options, arg);
			// don't clobber one flash vars object with another
			// merge them instead
			if(arg.flashvars == undefined) continue;
			jQuery.extend(flashvars, arg.flashvars);
		}
		options.flashvars = flashvars;
		return options;
	};
	/*
	 * @name flash.hasFlash
	 * @desc Check if a specific version of the Flash plugin is installed
	 * @type Boolean
	 *
	**/
	$$.hasFlash = function() {
		// look for a flag in the query string to bypass flash detection
		if(/hasFlash\=true/.test(location)) return true;
		if(/hasFlash\=false/.test(location)) return false;
		var pv = $$.hasFlash.playerVersion().match(/\d+/g);
		var rv = String([arguments[0], arguments[1], arguments[2]]).match(/\d+/g) || String($$.pluginOptions.version).match(/\d+/g);
		for(var i = 0; i < 3; i++) {
			pv[i] = parseInt(pv[i] || 0);
			rv[i] = parseInt(rv[i] || 0);
			// player is less than required
			if(pv[i] < rv[i]) return false;
			// player is greater than required
			if(pv[i] > rv[i]) return true;
		}
		// major version, minor version and revision match exactly
		return true;
	};
	/**
	 *
	 * @name flash.hasFlash.playerVersion
	 * @desc Get the version of the installed Flash plugin.
	 * @type String
	 *
	**/
	$$.hasFlash.playerVersion = function() {
		// ie
		try {
			try {
				// avoid fp6 minor version lookup issues
				// see: http://blog.deconcept.com/2006/01/11/getvariable-setvariable-crash-internet-explorer-flash-6/
				var axo = new ActiveXObject('ShockwaveFlash.ShockwaveFlash.6');
				try { axo.AllowScriptAccess = 'always';	} 
				catch(e) { return '6,0,0'; }				
			} catch(e) {}
			return new ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version').replace(/\D+/g, ',').match(/^,?(.+),?$/)[1];
		// other browsers
		} catch(e) {
			try {
				if(navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin){
					return (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]).description.replace(/\D+/g, ",").match(/^,?(.+),?$/)[1];
				}
			} catch(e) {}		
		}
		return '0,0,0';
	};
	/**
	 *
	 * @name flash.htmlOptions
	 * @desc The default set of options for the object or embed tag.
	 *
	**/
	$$.htmlOptions = {
		height: 240,
		flashvars: {},
		pluginspage: 'http://www.adobe.com/go/getflashplayer',
		src: '#',
		type: 'application/x-shockwave-flash',
		width: 320		
	};
	/**
	 *
	 * @name flash.pluginOptions
	 * @desc The default set of options for checking/updating the flash Plugin.
	 *
	**/
	$$.pluginOptions = {
		expressInstall: false,
		update: true,
		version: '6.0.65'
	};
	/**
	 *
	 * @name flash.replace
	 * @desc The default method for replacing an element with a Flash movie.
	 *
	**/
	$$.replace = function(htmlOptions) {
		this.innerHTML = '<div class="alt">'+this.innerHTML+'</div>';
		jQuery(this)
			.addClass('flash-replaced')
			.prepend($$.transform(htmlOptions));
	};
	/**
	 *
	 * @name flash.update
	 * @desc The default method for replacing an element with an update message.
	 *
	**/
	$$.update = function(htmlOptions) {
		var url = String(location).split('?');
		url.splice(1,0,'?hasFlash=true&');
		url = url.join('');
		var msg = '<p>This content requires the Flash Player. <a href="http://www.adobe.com/go/getflashplayer">Download Flash Player</a>. Already have Flash Player? <a href="'+url+'">Click here.</a></p>';
		this.innerHTML = '<span class="alt">'+this.innerHTML+'</span>';
		jQuery(this)
			.addClass('flash-update')
			.prepend(msg);
	};
	/**
	 *
	 * @desc Convert a hash of html options to a string of attributes, using Function.apply(). 
	 * @example toAttributeString.apply(htmlOptions)
	 * @result foo="bar" foo="bar"
	 *
	**/
	function toAttributeString() {
		var s = '';
		for(var key in this)
			if(typeof this[key] != 'function')
				s += key+'="'+this[key]+'" ';
		return s;		
	};
	/**
	 *
	 * @desc Convert a hash of flashvars to a url-encoded string, using Function.apply(). 
	 * @example toFlashvarsString.apply(flashvarsObject)
	 * @result foo=bar&foo=bar
	 *
	**/
	function toFlashvarsString() {
		var s = '';
		for(var key in this)
			if(typeof this[key] != 'function')
				s += key+'='+encodeURIComponent(this[key])+'&';
		return s.replace(/&$/, '');		
	};
	/**
	 *
	 * @name flash.transform
	 * @desc Transform a set of html options into an embed tag.
	 * @type String 
	 *
	 * @example $$.transform(htmlOptions)
	 * @result <embed src="foo.swf" ... />
	 *
	 * Note: The embed tag is NOT standards-compliant, but it 
	 * works in all current browsers. flash.transform can be
	 * overwritten with a custom function to generate more 
	 * standards-compliant markup.
	 *
	**/
	$$.transform = function(htmlOptions) {
		htmlOptions.toString = toAttributeString;
		if(htmlOptions.flashvars) htmlOptions.flashvars.toString = toFlashvarsString;
		return '<embed ' + String(htmlOptions) + '/>';		
	};
	
	/**
	 *
	 * Flash Player 9 Fix (http://blog.deconcept.com/2006/07/28/swfobject-143-released/)
	 *
	**/
	if (window.attachEvent) {
		window.attachEvent("onbeforeunload", function(){
			__flash_unloadHandler = function() {};
			__flash_savedUnloadHandler = function() {};
		});
	}
		
	})();
/*Fim ---------------------------------------------------------------------------------------------------------*/


/**
 * --------------------------------------------------------------------
 * jQuery-Plugin "pngFix"
 * Version: 1.1, 11.09.2007
 * by Andreas Eberhard, andreas.eberhard@gmail.com
 *                      http://jquery.andreaseberhard.de/
 *
 * Copyright (c) 2007 Andreas Eberhard
 * Licensed under GPL (http://www.opensource.org/licenses/gpl-license.php)
 *
 * Changelog:
 *    11.09.2007 Version 1.1
 *    - removed noConflict
 *    - added png-support for input type=image
 *    - 01.08.2007 CSS background-image support extension added by Scott Jehl, scott@filamentgroup.com, http://www.filamentgroup.com
 *    31.05.2007 initial Version 1.0
 * --------------------------------------------------------------------
 * @example $(function(){$(document).pngFix();});
 * @desc Fixes all PNG's in the document on document.ready
 *
 * jQuery(function(){jQuery(document).pngFix();});
 * @desc Fixes all PNG's in the document on document.ready when using noConflict
 *
 * @example $(function(){$('div.examples').pngFix();});
 * @desc Fixes all PNG's within div with class examples
 *
 * @example $(function(){$('div.examples').pngFix( { blankgif:'ext.gif' } );});
 * @desc Fixes all PNG's within div with class examples, provides blank gif for input with png
 * --------------------------------------------------------------------
 */

(function($) {

jQuery.fn.pngFix = function(settings) {

	// Settings
	settings = jQuery.extend({
		blankgif: 'blank.gif'
	}, settings);

	var ie55 = (navigator.appName == "Microsoft Internet Explorer" && parseInt(navigator.appVersion) == 4 && navigator.appVersion.indexOf("MSIE 5.5") != -1);
	var ie6 = (navigator.appName == "Microsoft Internet Explorer" && parseInt(navigator.appVersion) == 4 && navigator.appVersion.indexOf("MSIE 6.0") != -1);

	if (jQuery.browser.msie && (ie55 || ie6)) {

		//fix images with png-source
		jQuery(this).find("img[src$=.png]").each(function() {

			jQuery(this).attr('width',jQuery(this).width());
			jQuery(this).attr('height',jQuery(this).height());

			var prevStyle = '';
			var strNewHTML = '';
			var imgId = (jQuery(this).attr('id')) ? 'id="' + jQuery(this).attr('id') + '" ' : '';
			var imgClass = (jQuery(this).attr('class')) ? 'class="' + jQuery(this).attr('class') + '" ' : '';
			var imgTitle = (jQuery(this).attr('title')) ? 'title="' + jQuery(this).attr('title') + '" ' : '';
			var imgAlt = (jQuery(this).attr('alt')) ? 'alt="' + jQuery(this).attr('alt') + '" ' : '';
			var imgAlign = (jQuery(this).attr('align')) ? 'float:' + jQuery(this).attr('align') + ';' : '';
			var imgHand = (jQuery(this).parent().attr('href')) ? 'cursor:hand;' : '';
			if (this.style.border) {
				prevStyle += 'border:'+this.style.border+';';
				this.style.border = '';
			}
			if (this.style.padding) {
				prevStyle += 'padding:'+this.style.padding+';';
				this.style.padding = '';
			}
			if (this.style.margin) {
				prevStyle += 'margin:'+this.style.margin+';';
				this.style.margin = '';
			}
			var imgStyle = (this.style.cssText);

			strNewHTML += '<span '+imgId+imgClass+imgTitle+imgAlt;
			strNewHTML += 'style="position:relative;white-space:pre-line;display:inline-block;background:transparent;'+imgAlign+imgHand;
			strNewHTML += 'width:' + jQuery(this).width() + 'px;' + 'height:' + jQuery(this).height() + 'px;';
			strNewHTML += 'filter:progid:DXImageTransform.Microsoft.AlphaImageLoader' + '(src=\'' + jQuery(this).attr('src') + '\', sizingMethod=\'scale\');';
			strNewHTML += imgStyle+'"></span>';
			if (prevStyle != ''){
				strNewHTML = '<span style="position:relative;display:inline-block;'+prevStyle+imgHand+'width:' + jQuery(this).width() + 'px;' + 'height:' + jQuery(this).height() + 'px;'+'">' + strNewHTML + '</span>';
			}

			jQuery(this).hide();
			jQuery(this).after(strNewHTML);

		});

		// fix css background pngs
		jQuery(this).find("*").each(function(){
			var bgIMG = jQuery(this).css('background-image');
			if(bgIMG.indexOf(".png")!=-1){
				var iebg = bgIMG.split('url("')[1].split('")')[0];
				jQuery(this).css('background-image', 'none');
				jQuery(this).get(0).runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + iebg + "',sizingMethod='scale')";
			}
		});
		
		//fix input with png-source
		jQuery(this).find("input[src$=.png]").each(function() {
			var bgIMG = jQuery(this).attr('src');
			jQuery(this).get(0).runtimeStyle.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader' + '(src=\'' + bgIMG + '\', sizingMethod=\'scale\');';
   		jQuery(this).attr('src', settings.blankgif)
		});
	
	}
	
	return jQuery;

};

})(jQuery);
// Fim do plugin que carrega png para os ie 5.5 e 6


/*Plugin que adiciona teclas de atalho a funções*/
/**
 * http://www.openjs.com/scripts/events/keyboard_shortcuts/
 * Version : 2.01.A
 * By Binny V A
 * License : BSD
 */
 /*shortcut.add("Ctrl+n",function(){
		CarregarTela(2);
 });*/
shortcut = {
	'all_shortcuts':{},//All the shortcuts are stored in this array
	'add': function(shortcut_combination,callback,opt) {
		//Provide a set of default options
		var default_options = {
			'type':'keydown',
			'propagate':false,
			'disable_in_input':false,
			'target':document,
			'keycode':false
		}
		if(!opt) opt = default_options;
		else {
			for(var dfo in default_options) {
				if(typeof opt[dfo] == 'undefined') opt[dfo] = default_options[dfo];
			}
		}

		var ele = opt.target
		if(typeof opt.target == 'string') ele = document.getElementById(opt.target);
		var ths = this;
		shortcut_combination = shortcut_combination.toLowerCase();

		//The function to be called at keypress
		var func = function(e) {
			e = e || window.event;
			
			if(opt['disable_in_input']) { //Don't enable shortcut keys in Input, Textarea fields
				var element;
				if(e.target) element=e.target;
				else if(e.srcElement) element=e.srcElement;
				if(element.nodeType==3) element=element.parentNode;

				if(element.tagName == 'INPUT' || element.tagName == 'TEXTAREA') return;
			}
	
			//Find Which key is pressed
			if (e.keyCode) code = e.keyCode;
			else if (e.which) code = e.which;
			var character = String.fromCharCode(code).toLowerCase();
			
			if(code == 188) character=","; //If the user presses , when the type is onkeydown
			if(code == 190) character="."; //If the user presses , when the type is onkeydown
	
			var keys = shortcut_combination.split("+");
			//Key Pressed - counts the number of valid keypresses - if it is same as the number of keys, the shortcut function is invoked
			var kp = 0;
			
			//Work around for stupid Shift key bug created by using lowercase - as a result the shift+num combination was broken
			var shift_nums = {
				"`":"~",
				"1":"!",
				"2":"@",
				"3":"#",
				"4":"$",
				"5":"%",
				"6":"^",
				"7":"&",
				"8":"*",
				"9":"(",
				"0":")",
				"-":"_",
				"=":"+",
				";":":",
				"'":"\"",
				",":"<",
				".":">",
				"/":"?",
				"\\":"|"
			}
			//Special Keys - and their codes
			var special_keys = {
				'esc':27,
				'escape':27,
				'tab':9,
				'space':32,
				'return':13,
				'enter':13,
				'backspace':8,
	
				'scrolllock':145,
				'scroll_lock':145,
				'scroll':145,
				'capslock':20,
				'caps_lock':20,
				'caps':20,
				'numlock':144,
				'num_lock':144,
				'num':144,
				
				'pause':19,
				'break':19,
				
				'insert':45,
				'home':36,
				'delete':46,
				'end':35,
				
				'pageup':33,
				'page_up':33,
				'pu':33,
	
				'pagedown':34,
				'page_down':34,
				'pd':34,
	
				'left':37,
				'up':38,
				'right':39,
				'down':40,
	
				'f1':112,
				'f2':113,
				'f3':114,
				'f4':115,
				'f5':116,
				'f6':117,
				'f7':118,
				'f8':119,
				'f9':120,
				'f10':121,
				'f11':122,
				'f12':123
			}
	
			var modifiers = { 
				shift: { wanted:false, pressed:false},
				ctrl : { wanted:false, pressed:false},
				alt  : { wanted:false, pressed:false},
				meta : { wanted:false, pressed:false}	//Meta is Mac specific
			};
                        
			if(e.ctrlKey)	modifiers.ctrl.pressed = true;
			if(e.shiftKey)	modifiers.shift.pressed = true;
			if(e.altKey)	modifiers.alt.pressed = true;
			if(e.metaKey)   modifiers.meta.pressed = true;
                        
			for(var i=0; k=keys[i],i<keys.length; i++) {
				//Modifiers
				if(k == 'ctrl' || k == 'control') {
					kp++;
					modifiers.ctrl.wanted = true;

				} else if(k == 'shift') {
					kp++;
					modifiers.shift.wanted = true;

				} else if(k == 'alt') {
					kp++;
					modifiers.alt.wanted = true;
				} else if(k == 'meta') {
					kp++;
					modifiers.meta.wanted = true;
				} else if(k.length > 1) { //If it is a special key
					if(special_keys[k] == code) kp++;
					
				} else if(opt['keycode']) {
					if(opt['keycode'] == code) kp++;

				} else { //The special keys did not match
					if(character == k) kp++;
					else {
						if(shift_nums[character] && e.shiftKey) { //Stupid Shift key bug created by using lowercase
							character = shift_nums[character]; 
							if(character == k) kp++;
						}
					}
				}
			}

			if(kp == keys.length && 
						modifiers.ctrl.pressed == modifiers.ctrl.wanted &&
						modifiers.shift.pressed == modifiers.shift.wanted &&
						modifiers.alt.pressed == modifiers.alt.wanted &&
						modifiers.meta.pressed == modifiers.meta.wanted) {
				callback(e);
	
				if(!opt['propagate']) { //Stop the event
					//e.cancelBubble is supported by IE - this will kill the bubbling process.
					e.cancelBubble = true;
					e.returnValue = false;
	
					//e.stopPropagation works in Firefox.
					if (e.stopPropagation) {
						e.stopPropagation();
						e.preventDefault();
					}
					return false;
				}
			}
		}
		this.all_shortcuts[shortcut_combination] = {
			'callback':func, 
			'target':ele, 
			'event': opt['type']
		};
		//Attach the function with the event
		if(ele.addEventListener) ele.addEventListener(opt['type'], func, false);
		else if(ele.attachEvent) ele.attachEvent('on'+opt['type'], func);
		else ele['on'+opt['type']] = func;
	},

	//Remove the shortcut - just specify the shortcut and I will remove the binding
	'remove':function(shortcut_combination) {
		shortcut_combination = shortcut_combination.toLowerCase();
		var binding = this.all_shortcuts[shortcut_combination];
		delete(this.all_shortcuts[shortcut_combination])
		if(!binding) return;
		var type = binding['event'];
		var ele = binding['target'];
		var callback = binding['callback'];

		if(ele.detachEvent) ele.detachEvent('on'+type, callback);
		else if(ele.removeEventListener) ele.removeEventListener(type, callback, false);
		else ele['on'+type] = false;
	}
}
/* fim da shottcut teclas de atalho*/

//drag n drop de div ----------------------------------------------------
/*
<body>
<!-- esta é a div de exemplo que será movida ao clicar no p de borda azul -->
<div id='movido' style='border: 1px solid black; width: 200px; '>
<p id='movedor' style='border: 1px solid blue;'>mova</p>
sou a div lálalá
<br />
lálálá
</div>
<!-- aqui o script chamando a função que ativa o drag'n'drop -->
<script>
dragdrop('movedor','movido');
</script>
</body>
*/

var objSelecionado = null;
var mouseOffset = null;

function addEvent(obj, evType, fn) {
//Função adaptada da  original de Christian Heilmann, em
//http://www.onlinetools.org/articles/unobtrusivejavascript/chapter4.html

if (typeof obj == "string") {
  if (null == (obj = document.getElementById(obj))) {
   throw new Error("Elemento HTML não encontrado. Não foi possível adicionar o evento.");
  }
}

if (obj.attachEvent) {
  return obj.attachEvent(("on" + evType), fn);
} else if (obj.addEventListener) {
  return obj.addEventListener(evType, fn, true);
} else {
  throw new Error("Seu browser não suporta adição de eventos. Senta, chora e pega um navegador mais recente.");
}
}

function mouseCoords(ev){    
    if(typeof(ev.pageX)!=="undefined"){
      return {x:ev.pageX, y:ev.pageY};
    }else{
        return {
          x:ev.clientX + document.body.scrollLeft - document.body.clientLeft,
          y:ev.clientY + document.body.scrollTop  - document.body.clientTop
        };
    }
}

function getPosition(e, ev){
    var ev = ev || window.event;
    if(e.constructor==String){ e = document.getElementById(e);}
    var left = 0, top  = 0;    
    var coords = mouseCoords(ev);    

    while (e.offsetParent){
      left += e.offsetLeft;
      top  += e.offsetTop;
      e     = e.offsetParent;
    }
    left += e.offsetLeft;
    top  += e.offsetTop;
    return {x: coords.x - left, y: coords.y - top};
}

function dragdrop(local_click, caixa_movida, maxLeft, minLeft, maxTop, minTop) {
//local click indica quem é o cara que quando movido, move o caixa_movida
	$('#'+caixa_movida).fadeIn();
    if(local_click.constructor==String){ local_click = document.getElementById(local_click);}
    if(caixa_movida.constructor==String){ caixa_movida = document.getElementById(caixa_movida);}
    
    local_click.style.cursor = 'move';
    if(!caixa_movida.style.position || caixa_movida.style.position=='static'){
        caixa_movida.style.position='relative'
    }
    local_click.onmousedown = function(ev) {
        objSelecionado = caixa_movida;        
        mouseOffset = getPosition(objSelecionado, ev);
    };
    document.onmouseup = function() {
        objSelecionado = null;
    }
    document.onmousemove = function(ev) {
        if (objSelecionado) {
            var ev = ev || window.event;
            var mousePos = mouseCoords(ev);
            var  pai = objSelecionado.parentNode;
			// limitando o movimento do objeto
			var sTop = (mousePos.y - mouseOffset.y - pai.offsetTop) ;
			if ( sTop > maxTop ){
				sTop = maxTop;
			}
			if ( sTop < minTop ){
				sTop = minTop;
			}
			var sLeft = (mousePos.x - mouseOffset.x - pai.offsetLeft);
			if ( sLeft > maxLeft ){
				sLeft = maxLeft;
			}
			if ( sLeft < minLeft ){
				sLeft =  minLeft ;
			}
			//fim do limite de movimento
			
            objSelecionado.style.left =  sLeft+ 'px';
            objSelecionado.style.top = sTop+ 'px';
            objSelecionado.style.margin = '0px';
            return false;
        }
    }
}

/*Fim do plugin para arrastar e soltar um objeto na tela*/


