	var utils = utils ? utils : {};
	
	//Funções utilitárias de número 
	utils.numero = utils.numero ? utils.numero : {};
	utils.numero.VALOR_PADRAO_DECIMAIS = 2;	
	
	/**
	 * verifica se um número é valido ou não 
	 * @param {Number} numero
	 */
	utils.numero.isNumeroValido = function(numero) {
		if (numero == null || numero == '' || isNaN(numero)){ 
			return false;
		}		
		return true;
	};
	/**
	 * Verifica se o número tem decimais
	 * @param {Number} numero
	 */
	utils.numero.temDecimais = function(numero) {
		var valorFormatado =  formatDecimalBr(numero);
		var retorno = parseFloat(retornaNumerosDepoisDaVirgula(valorFormatado));
		return retorno > 0;		
	};

	/**
	 * Cria uma nova janela maximizada
	 * 
	 * @param url
	 * @param sName
	 *            Nome da nova Janela
	 */
	function openNewWindow(url, sName){
		if (sName == null) {
			sName = "_blank";
		}
		var height = screen.availHeight - screen.availHeight * 0.08; // Diminui 8% da altura da tela
		var width = screen.availWidth - screen.availHeight * 0.02;  // Diminui 2% da largura da tela

		//evita maximizar quando o usuario possuir telas muito grandes		
		if (height > 768) {
			height= 768;
		}
		if (width > 1024) {
			width = 1024;
		}
		
		var left = (screen.width - width) / 2;
		var top = ( (screen.height - height) / 2 ) -  screen.availHeight * 0.10; // Posiciona a janela no topo a 10% (barra Iniciar)
	    var w = window.open(url,sName,"width=" + width + "px, height=" + height + "px, top=" + top + "px, left=" + left + "px, scrollbars, resizable, status=1");
		w.moveTo(0,0);
		
		w.focus();
		return w;
	}
	
	/**
	 * Cria uma nova janela e faz post do formul‡rio passado por parametro nela.
	 * @param formId ID do Formulario
	 */
	function openNewWindowWithForm(formId){
		var newWindowId = 'bluesoftWindow' + Math.floor(Math.random()*50000);
		formId = '#' + formId;
		var w = openNewWindow('',newWindowId);
		jQuery(formId).get(0).target = newWindowId;
		jQuery(formId)[0].submit();
		w.focus();
	}

	function openNewWindowResizeable(url, sName, width, height) {
		
		if (sName == null || new String(sName).length == 0) {
			sName = '_blank';
		}
		
		var left = (screen.width - width) / 2;
		var top = (screen.height - height) / 2;
		var parametros = "width=" + width + "px, height=" + height + "px, top=" + top + "px, left=" + left + "px, scrollbars, resizable, status=1";
		var w = window.open(url, sName, parametros);
		w.focus();
		return w;
	}	
	
	
	/**
	 * Função para expandir/retrair um div - se não passar width nem height, assume-se o tamanho da div (div começando visível)
	 * passando altura e largura assume-se esses valores (div começando escondida) 
	 */
	
	function showHide(img,idDiv, width, height) {
		var $div = $('#'+idDiv);
		if (parseInt($div.height()) != 0){
			if (width == 'undefined' || width == null){
				$.data(document.body, "larguraDiv"+idDiv, $div.width());
			} else {
				$.data(document.body, "larguraDiv"+idDiv, width);
			}
			if (height == 'undefined' || height == null){
				$.data(document.body, "alturaDiv"+idDiv, $div.height());
			} else {
				$.data(document.body, "alturaDiv"+idDiv, height);
			}
		}
		
		if ($div.is(":visible")){
			$div.animate({
					height: 0
				}, 1000 , function (){
					$(img).attr('src',"/cdn/commons/icons/"+"mostrar_filtros.gif");
					$div.hide();
			});
		}else{
			$div.show();
			$div.animate({
				width: $.data(document.body, 'larguraDiv'+idDiv),
				height: $.data(document.body, 'alturaDiv'+idDiv)
			}, 1000, function (){
				$(img).attr('src',"/cdn/commons/icons/"+"esconder_filtros.gif");
			});
		}
	}
	
	
	/**
	 * Transforma um numero no formato brasileiro em um float
	 */
	function parseFloatBr(valor, casas){
		if (valor == null || new String(valor).length == 0) { 
			return 0.0;
		}
		
		if(isNaN(valor)){
			valor = new String(valor);
			while(valor.indexOf('.') > -1){
				valor = valor.replace('.','');
			}
			valor = valor.replace(',','.')
			valor = parseFloat(valor);
		}
		
		if (casas != null) {
			valor = arredondar(valor, casas);
		}
		
		if (isNaN(valor)) {
			return parseFloat(0);
		} else {
			return parseFloat(valor);
		}
	}
	
	/**
	 * Formata um numero para o padrao brasileiro
	 * @param valor
	 */
	function formatDecimalBr(valor, casas){
		
		var inteiro, decimal, ultimoPonto, isNegativo;
		if (casas == null || isNaN(casas)) 
			casas = 2;
		
		if (valor == null)
			valor = '0';
		
		
		valor = new String(valor);
		
		isNegativo = valor.charAt(0) == "-";	
		if (isNegativo) {
			valor = valor.substring(1);
		}
		
		if (ehFormatoBrasileiro(valor)) {
			valor = tirarPontos(valor);
		}else {
			valor =  tirarVirgulas(valor);
		}
		valor =  valor.replace(',','.');
		valor = new String( arredondar(valor, casas));
		
		ultimoPonto = valor.lastIndexOf('.');
		if (ultimoPonto > 0) {
			inteiro = valor.substring(0, ultimoPonto);
			decimal = valor.substring(ultimoPonto + 1);
			if (decimal.length < casas) {
				if(decimal == '1' && valor.substring((ultimoPonto + 1), (ultimoPonto + 2)) == '9'){
					inteiro = parseFloat(inteiro) + 1;
					inteiro = new String(inteiro);
					decimal = replicar(0, casas);
				} else {
					decimal = decimal +  replicar(0, (casas - decimal.length));
				}
			}	
		} else {
			decimal = replicar(0, casas);
			inteiro = valor;
		}		  
		
		var cont = 0;
		var novoInteiro = new String();
		if (casas == 0) {
			novoInteiro = inteiro;
		} else {
			for (var i = inteiro.length; i > 0; i--) {
				novoInteiro = inteiro.charAt(i-1) + novoInteiro;
				cont++; 
				if (cont != inteiro.length && i > 1 && cont % 3 == 0){ 
					novoInteiro = '.' + novoInteiro;
					cont = 0;
				}	
			}
			inteiro = novoInteiro;
		}
		
		if (casas > 0) {
			return (isNegativo ? '-' : '') + inteiro  + ',' + decimal;
		}else {
			return (isNegativo ? '-' : '') + inteiro;
		}
	}
	
	function tirarPontos(valor) {
		return  valor.replace(/\.+/g,'');
	}
	
	function tirarVirgulas(valor) { 
		return  valor.replace(/,/g,'');
	}
	
	function ehFormatoBrasileiro(valor) {
		var temVirgula = valor.lastIndexOf(',') > -1;
		var oPontoEstaAntesDaVirgula = valor.lastIndexOf('.') < valor.lastIndexOf(',');
		var pontos = valor.split('.').length;
		var temMaisDeUmPonto = pontos > 2;
		
		if ((temVirgula && oPontoEstaAntesDaVirgula) || temMaisDeUmPonto) {
			return true;
		}
		
		return false;
	}
	
	/**
	 *	Formata numero quando for necessario
	 *Ex: 
	 *	2,12 ficaria 2,12
	 *	50,00 ficaria 50
	 * 
	 */
	function formatDecimalBrQuandoNecessario(numero, casasDecimais){
		var numeroASerRetornado = null;
		if (!utils.numero.isNumeroValido(casasDecimais)){ 
			casasDecimais = utils.numero.VALOR_PADRAO_DECIMAIS;
		}
		
		if (!utils.numero.isNumeroValido(numero)){ 
			numero = 0;
		}
		
		if(utils.numero.temDecimais(numero)){
			numeroASerRetornado = formatDecimalBr(numero, casasDecimais);
		}else{
			numeroASerRetornado = formatDecimalBr(numero, 0);
		}
		
		return numeroASerRetornado;
		
	}
	
	
	/**
	 * Retorna apenas os valores decimais em número no formato brasileiro
	 * @param {Object} valor( valor em formato brasileiro)
	 */
	function retornaNumerosDepoisDaVirgula(valor) {
		var resultado = "";
		for (var i = valor.length - 1; i != 0; i--) {
			var caracterAtual = valor.charAt(i);
			if(caracterAtual == ','){
				break;
			}else{
				resultado = caracterAtual + resultado;
				
			}
		}
		
		return resultado;
	}

	
	
	/**
	 * Arrendonda um numero
	 */
	function arredondar(numero, casas) {
		var number= new Number(numero);
		if (casas == null) {
			return parseFloat(numero);
		} 
		return parseFloat(number.toFixed(casas));
	}
	
	/**
	 * Converte uma String para Date
	 */
	function strToDate(str) {
		var data = null;
		var array = str.split('\/');
		if (array.length < 3) {
			return data;
		}
		try {
			var dia = array[0];
			var mes = array[1] - 1;
			var ano = array[2];
			data = new Date(ano, mes, dia, 3, 0, 0, 0); //adiciona 3 horas para contornar o problema do horario de verao
			return data;
		} catch(e) {
			return data;
		}
	}

	/**
	 * Retorna true se a diferena entre data inicial e final for maior que o
	 * perido.
	 * 
	 * @param data1
	 * @param data2
	 * @param numeroMaximoDeDias:
	 *            nœmero m‡ximo em dias em que a diferena entre as datas
	 */
	function maxDifferenceBetweenDates(dataInicial, dataFinal, numeroMaximoDeDias) {
		  var retorno = false;
		  if( dataFinal - dataInicial > 86400000* numeroMaximoDeDias){
		       retorno = true;
		  }
	      return retorno;
	}
	
	/**
	 * Retorna true se a data inicial for maior que a data final
	 * 
	 * @param data1
	 * @param data2
	 */
	function verificaSeUmaDataEMaiorQueOutra(dataInicial, dataFinal) {
		var retorno = false;  
		if( dataInicial  *86400000 > dataFinal * 86400000){
		      retorno = true;
		}
		return retorno;
	}
	
	/**
	 * Retorna true se a data inicial for maior que a data final
	 * 
	 * @param data1
	 * @param data2
	 */
	function verificaSeUmaDataEMenorQueOutra(dataInicial, dataFinal) {
		var retorno = false;  
		if( dataInicial  *86400000 < dataFinal * 86400000){
		      retorno = true;
		}
		return retorno;
	}
	
	/**
	 * Funcao para ser adicionada no onclick do checkbox de selecionar todos.
	 * Ex: <input type='checkbox' onclick='checkHandler(this,"codigo")'>
	 * 
	 * @param combo
	 *            elemento check
	 * @param target
	 *            nome dos elementos check que devem ser checados ou deschecados
	 */
	function checkHandler(combo, target){
		var isComboChecked = $(combo).is(':checked');
		$('input[name^="' + target + '"]').each(function(i, el){
			if (isComboChecked) {
				$(el).prop('checked',true);
			} else {
				$(el).prop('checked',false);
			}
		}).click(function(){
			if (!$(this).prop('checked')){
				$(combo).prop('checked', true);
			};
		});
	}
	
	
	/**
	 * Funcao para ser adicionada no onclick do checkbox de selecionar todos.
	 * Ex: <input type='checkbox' onclick='checkHandler(this,"codigo")'>
	 * @param combo elemento check 
	 * @param target class dos elementos check que devem ser checados ou deschecados
	 */
	function checkHandlerByClass(combo, target){
		$("." + target).each(function(i, el){
			el.checked = combo.checked;			
		}).click(function(){
			if (!this.checked){
				combo.checked = false; 
			};
		});
	}
	
	/**
	 * Remove Zeros a Esquerda
	 */
	function tirarZerosEsquerda(s){
		while(s.substring(0,1) == 0) {
			s = s.substring(1);
		}
		return s;
	}
	
	function tirarZerosDireita(s) {
		for (i = s.length; i != 0; i--) {
			if (s[i-1] == 0) {
				s = s.substring(0,i-1);
			} else {
				break;
			}
		}
		return s;
	}
	
	function preencheComZerosAEsquerda(str, size){
		if (str.length < size) {
			return replicar('0', size - str.length) + str;
		} else {
			return str;
		}
	}
	
	function preencheComZerosADireita(str, size){
		if (str.length < size) {
			return str + replicar('0', size - str.length);
		} else {
			return str;
		}
	}
	
	function retirarCaracteresNaoNumericos(s) {
		return new String(s).replace(/[^0-9]/g,"");
	}
	
	
	function retirarCaracteresNaoNumericosExcetoPontoEVirgula(s) {
		return new String(s).replace(/[^0-9\\.,]*/g,"");
	}
	/**
	 * Repete uma string um determinado numero de vezes
	 * 
	 * @param str String
	 * @param vezes Numero de vezes a repetir
	 */	 
	function replicar(str, vezes){
		var out = str;
		for (i = 1; i < vezes; i++) {
			out += new String(str);
		}
		return out;
	}
	
	/**
	 * Formata valores numericos decimais
	 */ 
	function formatarValorComDecimalObrigatorio(str, decimalDigits){
		if (decimalDigits < 1) { decimalDigits = 1; }
		var decimal, inteiro;
	 	var i,count;
		STR = tirarZerosEsquerda(new String(str));
	 	inteiro='';
	
		if (STR.length == decimalDigits){
			inteiro = '0';
	 		decimal = STR;
	 	} else if (STR.length < decimalDigits){
			inteiro = '0';
	 		var diferenca = decimalDigits - STR.length;
	 		decimal = replicar('0', diferenca) + STR;
		} else {
			decimal = STR.substring(STR.length-decimalDigits, STR.length);
			i=decimalDigits+1;
			count=0;
			while (i <= STR.length){
				if (count==3) {
					inteiro = '.' + inteiro;
					count = 0;
				}
				inteiro = STR.charAt(STR.length-i) + inteiro;
				count++;
				i++;
			}
		}
	
	 	if (inteiro == '') {
	 		inteiro = '0';
	 	}
	
	 	if (decimal == '') {
	 		decimal = replicar('0', decimalDigits);
	 	}
	
	 	return inteiro + ',' + decimal;
	}
	
	/* Permite apenas entrada (por teclado) de valores numericos */		
	var soNumero = function(event){
		var k = document.all? window.event.keyCode: event.which;
		// Bloqueia shift
		if (k == 16) {
			return false;
		}
		
		var wasHomeOrEnd = k == 35 || k == 36;
		var wasNumpadKeys = (k >= 96 && k <= 105);
		var wasNumbersKeys = (k >= 48 && k <= 57);
		var wasBackspace = k == 8 || k == 46;
		var wasTab = k == 9;
		var wasCtrl = k == 17;
		var wasReturnOrEnter = k == 13;
		var wasArrows = (k >= 37 && k <= 40);
		var wasPageDown = k == 34;
		var wasPageUp = k == 33;
		
		if ( wasNumpadKeys || wasNumbersKeys || wasBackspace || wasTab || wasArrows || wasCtrl || wasHomeOrEnd  || wasReturnOrEnter || wasPageDown || wasPageUp) {
			return true;
		} else {
			return false;
		}
	};
	
	/**
	 * Substitui a tecla enter pela tecla tab
	 * @param {Object} event
	 */
	function substituiEnterPorTab(campo, event) {
	 	if (window.event) {
		 	if (event.keyCode ==13) {
		 		event.keyCode = 9;
			}
		 }else {
		 	 if (event.which ==13) {
			 	var $campos = $("input").not("[disabled='disabled']"); 
				for(var i=0; i < $campos.size(); i++) {
					var el = $campos.get(i);
					if (el.id == campo.id) {
						var $proximoCampo = $campos.eq(i+1);
						if ($proximoCampo) {
							$proximoCampo.focus();
							break;							
						}
					}
				}
			 } 
			 	 
		 }	
 	}

	
	
	function temVirgula(value){
		return value.match(',') != null;
	}
		
	$(function(){
		
		
		/*
		 * Cria a funcao maskAsDecimal no jQuery
		 */
		jQuery.fn.extend({
			maskAsDecimal: function(maxDigits, minDigits, converterParaFormatoBr){
				
				/*
				 * Nao permite que se digite caracteres nao numericos e converte
				 * ponto em virgula
				 */
				this.keypress(function(event) {
					var k = null;
					if ($.browser.msie) {
						k = event.keyCode;
					} else {
						k = event.charCode;
					}
					var wasPontoOuVirgula = k == 44 || k == 46;
					var wasANumberOrSpecialKey = (k >= 48 && k <= 57) || k == 0;
					var valorAtual = $(this).val();
					
					if (wasPontoOuVirgula) {
						if (!temVirgula(valorAtual)) {
							$(this).val(valorAtual + ",");
						}
						return false;
					}
					
					return wasANumberOrSpecialKey;
				});
				 
				/*
				 * Retira decimais que excederem o valor maximo (maxDigits)
				 */ 
				var cortarDecimais = function(){
					var valorAtual = this.value;
					if (obterQuantidadeDecimais(valorAtual) > maxDigits) {
						$(this).val(valorAtual.substring(0,valorAtual.indexOf(',') + maxDigits+1));
					}
				};
				
				this.keyup(cortarDecimais);			
				/*
				 * Completa com zeros os decimais caso esteja baixo do minimo
				 * (minDigits)
				 */
				var adicionaDecimais = function(){
					var valorAtual = this.value;
					
					if (valorAtual !=null && valorAtual.length > 0) {
						var novoValor = valorAtual;
						
						if (novoValor.indexOf(',') == 0) {
							novoValor = '0' + novoValor;
						}
						var quantidadeDecimais = obterQuantidadeDecimais(novoValor);
						
						if (quantidadeDecimais < minDigits) {
							if (!novoValor.match(',')) {
								novoValor += ',';
							}
							novoValor += replicar('0', minDigits - quantidadeDecimais);
						}
					
						$(this).val(novoValor);
						cortarDecimais();
					}
				};
				this.change(adicionaDecimais);
				
				/**
				 * Se necessario converte o numero do padrao americano para o
				 * brasileiro
				 */
				if (converterParaFormatoBr) {
					$(this).each(function(i, el){
						$(el).val(formatDecimalBr($(el).val(), maxDigits));
					});
				}
				adicionaDecimais();
				this.css('align', 'right');
			},
			
			maskAsInteger: function(valorPadraoInformado){
				
				var valorPadrao = 0;
				if (valorPadraoInformado || valorPadraoInformado == '') {
					valorPadrao = valorPadraoInformado;
				}
				
				if (isNaN(parseFloatBr($(this).val()))) {
					$(this).val(valorPadrao);
				}
				this.css('align', 'right');
				this.keydown(soNumero);
				this.change(function(){
					var $this = $(this);
					var valor = new String($this.val()).replace(/[^0-9]/g,'');
					if ($.trim(valor) == '' || isNaN(valor)) {
						$this.val(valorPadrao);
					}else {
						$this.val(valor);
					}
				});
			}
		});		
	});	
	
	function maskAsDecimalKeyPress(campo, maxDigits, minDigits, converterParaFormatoBr){
		window.status = 'keyUp';
		$(campo).keypress(function(event) {
			var k = null;
			if ($.browser.msie) {
				k = event.keyCode;
			} else {
				k = event.charCode;
			}
			var wasPontoOuVirgula = k == 44 || k == 46;
			var wasANumberOrSpecialKey = (k >= 48 && k <= 57) || k == 0;
			var valorAtual = $(this).val();
			
			if (wasPontoOuVirgula) {
				if (!temVirgula(valorAtual)) {
					$(this).val(valorAtual + ",");
				}
				return false;
			}
			
			return wasANumberOrSpecialKey;
		});
	}
	
	function maskAsDecimalKeyUp(campo,  maxDigits, minDigits, converterParaFormatoBr){
		
		var cortarDecimais = function(){
			var valorAtual = $(this).val();
			if (obterQuantidadeDecimais(valorAtual) > maxDigits) {
				$(this).val(valorAtual.substring(0,valorAtual.indexOf(',') + maxDigits+1));
			}
		};
		$(campo).keyup(cortarDecimais);
	}
	
	function maskAsDecimalChange(campo,  maxDigits, minDigits, converterParaFormatoBr){
		var cortarDecimais = function(){
			var valorAtual = $(this).val();
			if (obterQuantidadeDecimais(valorAtual) > maxDigits) {
				$(this).val(valorAtual.substring(0,valorAtual.indexOf(',') + maxDigits+1));
			}
		};
		
		var adicionaDecimais = function(){
			var valorAtual = $(this).val();
			
			if (valorAtual !=null && valorAtual.length > 0) {
				var novoValor = valorAtual;
				
				if (novoValor.indexOf(',') == 0) {
					novoValor = '0' + novoValor;
				}
				
				var quantidadeDecimais = obterQuantidadeDecimais(novoValor);
				
				if (quantidadeDecimais < minDigits) {
					if (!novoValor.match(',')) {
						novoValor += ',';
					}
					novoValor += replicar('0', minDigits - quantidadeDecimais);
				}
			
				$(this).val(novoValor);
				cortarDecimais();
			}
		};
		$(campo).change(adicionaDecimais);
		
		if (converterParaFormatoBr) {
			$(campo).val(formatDecimalBr($(campo).val(), maxDigits));
		}
		$(campo).css('align', 'right');
	}	
				
	
	// Funcao para estilizar tabela com linhas zebradas
	$(function() {
		jQuery.fn.extend({
			zebra: function(){
				$(this).find('tr').removeClass('even').removeClass('odd');
				$(this).find('tr:even').addClass('even');
				$(this).find('tr:odd').addClass('odd');
			}
		});		
	});

	// Funcao para destacar linha da tabela quando passar o mouse sobre ela 
	$(function() {
		jQuery.fn.extend({
			mouseOverEffect: function(){
				$(this).find('tr').mouseover(function() { $(this).addClass("over");	   });
				$(this).find('tr').mouseout(function()  { $(this).removeClass("over"); });
			}
		});		
	});
	
	// Funcao para possibilitar que o usuario digite somente valores numericos
	$(function() {
		jQuery.fn.extend({
			soValoresNumericos: function(){
				this.css('align', 'right');
				this.keydown(soNumero);
			}
		});		
	});
	
	/*
	 * Exibe um dialogo de cofirmacao @param id @param message @param
	 * yesCallback funcao a ser chamada ao clicar no botao sim @param noCallback
	 * funcao a ser chamada ao clicar no botao nao
	 */
	function showConfirmModal(message, yesCallback, noCallback, onOpen, onClose) {
		
		var id = "divModal" + Math.ceil(Math.random()*1000);
		
		// Cria div para exibicao do modal

		var divMensagem = $("<div id='"+id+"'>"+message+"</div>");  
		divMensagem.dialog({
			title: "Atenção",
			height: 170,
			modal: true, 
		    overlay: { 
		        opacity: 0.5, 
		        background: "black" 
		    },  
		    open: function() {
		    	if ($.isFunction(onOpen)) {
					onOpen.apply();
				} 
		    },
		    close: function() {
		    	if ($.isFunction(onClose)) {
					onClose.apply();
				}
		    },
		    buttons: { 
		        "Não": function() { 
			    	$(this).dialog("close");
		            if ($.isFunction(noCallback)) {
						noCallback.apply();
					}	
		            $('#'+id).remove();
		        },
		        "Sim": function() { 
		        	$(this).dialog("close");
		            if ($.isFunction(yesCallback)) {
						yesCallback.apply();
					}		
		            $('#'+id).remove(); 
		        }
		    } 
		});
		darNomeAosBotoesParaUsarNosTestesDeAceitacao();
		return divMensagem;
	}
	
	function darNomeAosBotoesParaUsarNosTestesDeAceitacao() {
		var $buttons = $('.ui-dialog-buttonpane');
		$buttons.find("button:contains('Sim')").addClass('sim');
		$buttons.find("button:contains('Não')").addClass('nao');
	}
	
	/**
	 * Retorna a diferena em dias entre data inicial e final
	 * 
	 * @param data1
	 * @param data2
	 */  
	function differenceBetweenDates(dataInicial, dataFinal) {
		  return (dataFinal - dataInicial) / 86400000;
	}
	
	/**
	 * Retorna a quantidade de decimais de um numero
	 * @param numero
	 * @param separadorDecimal se nulo assume virgula
	 */
	function obterQuantidadeDecimais(numero, separadorDecimal){
		if (separadorDecimal == null) {
			separadorDecimal = ',';
		}
		if (typeof(numero) != 'string'){
			numero = new String(numero);
		}
		var posicaoVirgula = numero.indexOf(',');
		if (posicaoVirgula > 0) {
			return numero.length - posicaoVirgula -1;
		} else {
			return 0;
		}
		
	}

	/*
	 * Exibe um dialogo de aviso 
	 */
	function showAlertModal(message, okCallback, onOpen, onClose) {
		
		var id = "divModal" + Math.ceil(Math.random()*1000);
		
		// Cria div para exibicao do modal

		var divMensagem = $("<div id='"+id+"'>" + message + "</div>");  
		divMensagem.dialog({
			title: "Atenção",
			height: 150,
			modal: true, 
		    overlay: { 
		        opacity: 0.5, 
		        background: "black" 
		    },  
		    open: function() {
		    	if ($.isFunction(onOpen)) {
					onOpen.apply();
				} 
		    },
		    close: function() {
		    	if ($.isFunction(onClose)) {
					onClose.apply();
				}
		    },
		    buttons: { 
		        "Ok": function() { 
		            if ($.isFunction(okCallback)) {
		            	okCallback.apply();
					}	
		            $(this).dialog("close"); 
		            $('#'+id).remove();
		        }
		    } 
		});
		return divMensagem;
	}

	 
	/**
	 * Adiciona uma mensagem no errorBox padrao da tag <bluetags:errorBox>
	 */
	function addError(msg, timeInSeconds) {
		var newError = $('<li>' + msg + '</li>');
		$('.errorBox ul').append(newError);
		if (timeInSeconds) {
			$(newError).oneTime(timeInSeconds * 1000, function(){ 
				newError.remove();
				if ($('.errorBox li').length == 0) {
					$('.errorBox').hide();
				}  
			});
			
		}
		$('.errorBox').show();
	}
	
	function cleanErrors() {
		$('.errorBox ul li').remove();
		$('.errorBox').hide();
	}
	
	function hideSuccess(timeInSeconds) {
		if (!timeInSeconds) {
			timeInSeconds=5;
		}
		$('.successBox').oneTime(timeInSeconds * 1000, function(){ $('.successBox').hide(); });
    }
       
	function hideErrors(timeInSeconds) {
           if (!timeInSeconds) {
                   timeInSeconds=10;
           }
           
           $('.errorBox').oneTime(timeInSeconds * 1000, 
           function(){ 
        	   $('.errorBox').hide();	
        	   $('.errorBox li').remove(); 
           });
	}

	/**
	 * Adiciona uma mensagem no successBox padrao da tag <bluetags:successBox>
	 */
	function setSuccess(msg, timeInSeconds) {
		var newMessage = $('<li>' + msg + '</li>');
		$('.successBox ul').html(newMessage);
		if (timeInSeconds) {
			$(newMessage).oneTime(timeInSeconds * 1000, function(){ newMessage.remove(); $('.successBox').hide() });
		}
		$('.successBox').show();
	}

	$(function(){
		try {
			ajaxBlockConfig();
		} catch(e){}
		
	});
	
	function ajaxBlockConfig() {
		$.blockUI.defaults.message = '<h1 style="color:#fff">Aguarde...</h1>', 
		$.blockUI.defaults.css.border = 'none'; 
        $.blockUI.defaults.css.padding = '15px'; 
        $.blockUI.defaults.css.backgroundColor = '#000'; 
        $.blockUI.defaults.css['-webkit-border-radius'] = '10px'; 
        $.blockUI.defaults.css['-moz-border-radius'] = '10px'; 
        $.blockUI.defaults.css.opacity = '.4'; 
        $.blockUI.defaults.css.color = '#fff';
        $.blockUI.defaults.fadeIn = 0;
        $.blockUI.defaults.fadeOut = 0;
	}
	
	/**
	 * Intercepta todas os request ajax e exibe uma mensagem de aguarde enquanto
	 * o request nao for finalizado.
	 */
	function ajaxBlock(){
        //$().ajaxStart($.blockUI).ajaxStop($.unblockUI);
	}
	
	function ajaxUnblock() {
		$.unblockUI();
		$().ajaxStart($.unblockUI);
		$().ajaxStop($.unblockUI);
	}
	
	function toDateBr(str) {
		if (str.length == 10) {
			return new Date(str.substring(6,10), str.substring(3,5)-1, str.substring(0,2));
		} else {
			return null;
		}
	}	
	
	/**
	 * converte um data para string 
	 * @param date
	 * @return
	 */
	function dateToString(date) {
		if (date == null) {
			date = getHoje();
		}
		return date.getDate() + '/' + (date.getMonth()+1) + '/' + date.getFullYear();
	}
	
	function getHoje() {
		var dataAtual = new Date();
		var data = new Date(dataAtual.getFullYear(), dataAtual.getMonth(), dataAtual.getDate());
		return data;	
	}
	
	/*
	 * Verifica se um c—digo de barras Ž v‡lido
	 */
	function validarEan(ean) {
		if (isNaN(ean)) {
			return false ;
		}
		if(parseInt(ean) > 0 && parseInt(ean) < 10000000 ) {
		    return true;
		}
		var i = 0;
		while ( i < ean.length ) {
			somapar = somapar + parseInt(new String(ean).substr(i,1));
		    i = i + 2;
		}
		i = 0;
		i = ean.length;
		
		var OrigNumber = "00000000000000000".concat(ean).substring(i);
		var dv          = new String(OrigNumber).charAt(16);
		ean = new String(OrigNumber).substr(0, 16);	// - 16 bytes
		var somapar   =  0 ;
		var somaimpar =  0 ;
		var subtotal  =  0 ;
		var i = 1 ;
		while (i < 17 ) {
			somapar = somapar + parseInt(new String(ean).substr(i,1));
		    i = i + 2;
		}
		i = 0;
		while (i < 16 )  {
			somaimpar = somaimpar + parseInt(new String(ean).substr(i,1));
		    i = i + 2;
		}
		var soma3 = ( somapar * 3 + somaimpar ) ;
		var soma4 = (Math.floor(soma3/10)*10 ) +10 ;
		var soma5 = soma4 - soma3  ;
		if ( soma5 == 10 )  soma5 = 0 ;
		if (soma5 == parseInt(dv) ) {
			return true ;
		} else {
			return false;
		}
	}
	 
	function getDocumentDimension(){
		  var myWidth = 0, myHeight = 0;
		  if( typeof( window.innerWidth ) == 'number' ) {
		    // Non-IE
		    myWidth = window.innerWidth;
		    myHeight = window.innerHeight;
		  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
		    // IE 6+ in 'standards compliant mode'
		    myWidth = document.documentElement.clientWidth;
		    myHeight = document.documentElement.clientHeight;
		  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
		    // IE 4 compatible
		    myWidth = document.body.clientWidth;
		    myHeight = document.body.clientHeight;
		  }
		  return {width: myWidth, height: myHeight};
	}
	
	function getMovie(movieName) {
	    if (navigator.appName.indexOf("Microsoft") != -1) {
	        return window[movieName];
	    } else {
	        return document[movieName];
	    }
	}
	
	function flexLoad(grid, path, parametros) {
		var grid = getMovie(grid);
		grid.load(path,parametros);	
	}
	
	// Esse metodo foi criado para abrir dialog no IE que abria-o com uma dimensao errada.
	function openDialog(id, width, height) {
		var $dialog = null;
		if (id instanceof jQuery) {
			$dialog = id;
		} else {
			$dialog = $("#" + id);
		}
		
		$dialog.dialog('option', 'bgiframe', true);
		$dialog.dialog("open");
		if (width) {
			$dialog.dialog('option', 'width', width);
		}
		if (height) {
			$dialog.dialog('option', 'height', height);
		}
		$dialog.css('height', '100%');
		$dialog.css('min-height', '100%');
		$dialog.dialog('option', 'position', 'center');
	}
	
	/**
	 * 
	 * @param id
	 * @param title
	 * @param width
	 * @param height
	 * @return
	 */
	function createDialog(id, title, width, height) {
		var optionsDialogModal = {
			autoOpen: false,
			modal: true,
			title: title,
			width: width,
			height: height
		};
		
		$('#'+id).dialog(optionsDialogModal);
	}
	
	window.validacaoEmErrorBox = { 
			errorContainer: ".errorBox",
			errorLabelContainer: ".errorBox ul",
			wrapper: 'li'
	};
	
	/**
	 * Coloca unidade monet‡ria brasileira junto ao valor
	 * @param valor
	 * @param casas
	 * @return
	 */
	function formataParaMoeda(valor, casas){
		valor = parseFloatBr(valor, casas);
		return 'R$ '+formatDecimalBr(valor, casas);
	}
	
	/**
	 * Coloca simbolo de percentual junto ao valor
	 */
	function formataParaPercentual(valor, casas){
		valor = parseFloatBr(valor, casas);
		return formatDecimalBr(valor, casas)+' %';
	}
	
	/**
	 * Exibe uma notifica›es no estilo Growl.
	 * Se passado apenas um String, exibe a mensagem com o titulo atencao
	 * Se passado duas Strings, a primeira eh o titulo, a segunda o texto
	 * Se passado um objeto, simplesmenta passa-o para o gritter
	 * Essa funcao eh uma tentativa de reduzir o acomplamento o plugin gritter, 
	 * 		porque no futuro podemos muda-lo em virtude de haver diversos plugins 
	 * 		com esse objetivo, e nenhum ter ganhado grande destaque ate agora.
	 */
	function addNotification(s1, s2) {
		
		var addNotificationWithTitle = function(title, text){
			$.gritter.add({
					'title': new String(title),
					'text': new String(text),
					'time': 4000
				});
		};
		
		var addNotificationWithoutTitle = function(text){
			$.gritter.add({
					'title': 'Atenção',
					'text': new String(text),
					'time': 4000
			});
		};
		
		if (arguments.length == 1) {
			if (typeof(s1) == 'string') {
				addNotificationWithoutTitle(s1);
			} else {
				//passa o objeto todo
				$.gritter.add(s1);
			}
		} else {
			addNotificationWithTitle(s1,s2);
		} 
	}
	
	/**
	 * Remove todas as notifica›es no estilo Growl
	 */
	function removeNotifications() {
		$.gritter.removeAll();
	}
	
	
	
	//Icon On and Off - BluesoftIcon jQuery Plugin
	$.fn.bluesoftIcon = function(settings){
		var config = {
			on: true
		};
		
		if (settings) 
			$.extend(config, settings);
		
		return this.each(function(){
			if (config.on) {
				$(this).removeClass('iconOff');
				$(this).addClass('iconOn');
			} else {
				$(this).removeClass('iconOn');
				$(this).addClass('iconOff');	
			}
		});
	};

	//Plugin para exibir videos e fotos
	$.fn.mediaBox = function(settings){
		var config = {
			showTitle: true ,
			theme: 'facebook',
			default_width: 900,
			default_height: 700,
			autoplay:true
		};
		if (settings) 
			$.extend(config, settings);
		return this.prettyPhoto(config);
	};
	
	//Função para escolher option de um select
	$.fn.hideOption = function() {
	    this.each(function() {
	        if ($(this).is('option') && (!$(this).parent().is('span'))) {
	            $(this).wrap('<span>').hide();
	        }
	    });
	}
	
	//Função para exibir option de um select
	$.fn.showOption = function() {
	    this.each(function() {
	        if (this.nodeName.toLowerCase() === 'option') {
	            var p = $(this).parent(),
	                o = this;
	            $(p).replaceWith(o);
	            $(o).show();
	        } else {
	            var opt = $('option', $(this));
	            $(this).replaceWith(opt);
	            opt.show();
	        }
	    });
	}
	
	/**
	 * Retira ou adiciona dias em uma data
	 * @param strDate
	 * @param dias
	 * @return
	 */
	function addDays(strDate, dias){
		var date = strToDate(strDate);
		date.setTime(date.getTime()+dias*86400000);
		return dateToString(date);
	}

	var bluesoft = bluesoft ? bluesoft : {}; 
	bluesoft.util = {
		htmlRowsToArray: function (htmlRows) {
			var existingRowsHtml = new String(htmlRows).replace(/(\f)|(\n)|(\r)|(\t)|(\v)/gmi,'');
			var oldRows = existingRowsHtml.match(/<tr.*?<\/tr>/gi);
			return oldRows ? oldRows : new Array();
		},
		
		goTo: function(url) {
			window.location.href = url;
		},
		
		fixTable:function(selector, tableHeight, tableWidth){
			var $table = $(selector);
			if (!tableHeight) {
				$table.hide();
				tableHeight = this.getAvailableHeight();
				$table.show();
			} 
			if (!tableWidth) {
				tableWidth = ($(document).width() * 0.99);
			}
			
			if($table.height() < tableHeight){
				$table.find('tbody').css('height','');
			}else{
				scrollable = $table.Scrollable(tableHeight, tableWidth);
			}
		},
		
		fixDiv:function(selector, height, width){
			var $div = $(selector);
			if (!height) {
				$div.hide();
				height = this.getAvailableHeight();
				$div.show();
			} 
			if (!width) {
				width = ($(document).width() * 0.99);
			}
			
			if($div.height() < height){
				$div.find('tbody').css('height','');
			}else{
				$div.height(height);
				$div.width('98%');
				$div.css('overflow','scroll');
				$div.css('margin','auto');
			}
		},

		//pega a altura do espaco disponivel na pagina (em branco, sem elementos)
		getAvailableHeight: function() {
			$tmp = $('<div/>');
			$tmp.css({'height':'100%'});
			$('body').append($tmp);
			
			var espacoNecessarioParaFuncionarEmTodosOsBrowsers = 28;
			var top = $tmp.offset().top;
			var tableHeight = $(window).height() - top - espacoNecessarioParaFuncionarEmTodosOsBrowsers;
			$tmp.remove();
			return tableHeight;
		},
		
		fixDivAtTheTop: function (divId){
			
			var $divToFix = $('#'+divId);
			
			var pageContentHeight = $(window).height() - $divToFix.height() - 25;
			var $body = $('body');
			
			var $children = $divToFix.nextAll().not('script');
			
			var $pageContent = $('<div id="pageContent">');
			$children.appendTo($pageContent);
			
			$body.append($pageContent);
			$pageContent.height(pageContentHeight);
			$pageContent.css('overflow','auto');
			
			$(window).resize(function(){
				var pageContentHeight = $(window).height() - $divToFix.height() - 25;
				$pageContent.height(pageContentHeight);
			});
			
		},
		
		validaCampoData: function(data, $campo){
		    
		    if(!isDataValida(data)){
				var dataDefault = $campo.prop('defaultValue'); 
				data = dataDefault;
				$campo.val(dataDefault);
			}
		    
			return data;
	    },
	    //Toggle do icone usado na tag <bluetag:icon/>
    	toggle : function(icone) {
			var $icone = $(icone);
			var srcIcon = $icone.attr("src");
			var normalIcon = $icone.attr("normalIcon");
			var toggleIcon = $icone.attr("toggleIcon");
			if (toggleIcon == "") {
				return;
			} 
			
			if (srcIcon == normalIcon) {
				$icone.attr("src", toggleIcon);
			}else {
				$icone.attr("src", normalIcon);
			}
    	},
    	
    	isNotEmpty: function(valor){
    		return valor != undefined;
    	}
	};
	
	/**
	 * Função invocada para trocar o ícone quando usada a tag <bluetag:icon/>
	 */
		
	
	$.fn.iframeSettings = function(settings) {
		return this.each(function(){
			var $this = $(this);
			$this.wrap("<div/>");
			var $parent = $this.parent();
			$this.remove();
			var src = $this.attr('src');
			var id = $this.attr('id');
			var name = $this.attr('name');
			var height = bluesoft.util.getAvailableHeight() - 10;
			
			var options = {
				frameBorder: '0',
				marginLeft: 0,
				marginHeight: 0,
				width: '100%',
				height: height,
				src: src,
				id: id,
				name: name
			};
			
			if (settings) {
				$.extend(options, settings);
			}
			var strIframe = "<iframe ";
			for(option in options) {
				strIframe+= (option+"='"+options[option]+"' ");
			}		
			strIframe+="></iframe>";
			$parent.html(strIframe);
		});	
	};	


	/**
	 * verifica se uma data é valida
	 * @param {String} data
	 */
	function isDataValida(data) {
		var array = new String(data).split('\/');
		var day = array[0];
		var monthStartWithOne = array[1];
		var year = array[2];
		
		if  (isNaN(day) || isNaN(monthStartWithOne) || isNaN(year)) {
			return false;
		}
		
		if (year < 1900) {
			return false;
		}
		
		var month = arredondar(monthStartWithOne, 0)-1;
		day = arredondar(day,0);
		year = arredondar(year, 0);
		
		var hora = 01; // Para evitar problemas com horário de verão, passamos uma hora a mais.
		var minuto = 00;
		var segundo = 00;
		var date = new Date(year, month, day, hora, minuto, segundo);
		
		if (day == 29 && monthStartWithOne == 2) {
			if (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) {
				return true;
			}
			else {
				return false;
			}
		} else if (monthStartWithOne == (date.getMonth() + 1) && day == date.getDate() && year == date.getFullYear()) {
			return true;
		} else {
			return false;
		}
	};
	
	function isCpfValido(cpf){

	    if(cpf == "")
		  return true;

	    var i = 0
		var tmpPos = 0;
	    while (i != -1){
	      i = cpf.indexOf(".", tmpPos);
	      if (i > 0){
	    	  cpf = cpf.substring(0,i) + cpf.substring(i + 1, cpf.length);
	      }
	    }

	    i = 0;
	    while (i != -1){
	      i = cpf.indexOf("-", tmpPos);
	      if (i > 0){
	    	  cpf = cpf.substring(0,i) + cpf.substring(i + 1, cpf.length);
	      }
	    }

		var i = cpf.length;
		var OrigNumber = "000000000000000000".concat(cpf).substring(i);
		var FirstDigit = OrigNumber.charAt(16);
		var SecondDigit = OrigNumber.charAt(17);

		cpf = OrigNumber.substring(0, 16);
		var FirstCalc = calculoCpfOuCnpj(cpf, 15, 10);

		cpf = OrigNumber.substring(0, 17);
		var SecondCalc = calculoCpfOuCnpj(cpf, 16, 11);

		return ( (FirstCalc == FirstDigit) && (SecondCalc == SecondDigit) );

	}

	function calculoCpfOuCnpj(cpfOuCnpj, FirstIndex, MaxWeight){
		var Sum = 0;		
		var Weight = 2;
		var i = 0;

		for (i = FirstIndex; i >= 0; i--){
			Sum += (cpfOuCnpj.charAt(i) - '0') * Weight;
			if (Weight == MaxWeight){
	           Weight = 1;
			}
			Weight++;
		}

		i = Sum % 11;
		if ( (i == 0) || (i == 1) ){
	       i = 11;
		}

		return String(11 - i);

	}

	function isCnpjValido(cnpj) {

	    if(cnpj == "")
		  return true;

	    var i = 0
		var tmpPos = 0;
	    while (i != -1){
	      i = cnpj.indexOf(".", tmpPos);
	      if (i > 0){
	    	  cnpj = cnpj.substring(0,i) + cnpj.substring(i + 1, cnpj.length);
	      }
	    }

	    i = 0;
	    while (i != -1){
	      i = cnpj.indexOf("-", tmpPos);
	      if (i > 0){
	    	  cnpj = cnpj.substring(0,i) + cnpj.substring(i + 1, cnpj.length);
	      }
	    }

	    i = 0;
	    while (i != -1){
	      i = cnpj.indexOf("/", tmpPos);
	      if (i > 0){
	    	  cnpj = cnpj.substring(0,i) + cnpj.substring(i + 1, cnpj.length);
	      }
	    }

		var FirstDigit = cnpj.substring(12, 13);
		var SecondDigit = cnpj.substring(13, 14);
	    var FirstCalc = calculoCpfOuCnpj(cnpj, 11, 9);
		var SecondCalc = calculoCpfOuCnpj(cnpj, 12, 9);
		return ((FirstCalc == FirstDigit) && (SecondCalc == SecondDigit));
	}
	
	function formatInteiroComSeparadorDeMilhar(num){	
		x = 0;   
		if(num < 0){
			num = Math.abs(num);
			x = 1;
		}
		if(isNaN(num)) num = "0";
		num = Math.floor((num*100+0.5)/100).toString();
		for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
		num = num.substring(0,num.length-(4*i+3))+'.'+num.substring(num.length-(4*i+3));
		ret = num;
		if (x == 1) ret = ' - ' + ret;
		return ret;	
	}

	/**
	 *	Formata numero quando for necessario mantendo o separador de milhates
	 *Ex: 
	 *	2,12 ficaria 2,12
	 *	1550,00 ficaria 1.550
	 *  22,0 ficaria 22
	 */
	function formatDecimalBrComSeparodorDeMilharQuandoNecessario(numero, casasDecimais){
		var numeroASerRetornado = null;
		if (!utils.numero.isNumeroValido(casasDecimais)){ 
			casasDecimais = utils.numero.VALOR_PADRAO_DECIMAIS;
		}
		
		if (!utils.numero.isNumeroValido(numero)){ 
			numero = 0;
		}
		
		if(utils.numero.temDecimais(numero)){
			numeroASerRetornado = formatDecimalBr(numero, casasDecimais);
		}else{
			numeroASerRetornado = formatInteiroComSeparadorDeMilhar(numero);
		}
		
		return numeroASerRetornado;
	}
	
