var win = null;

function alertModal(titulo,msg)
{
  	Dialog.alert(msg, {windowParameters: {className: "alphacube",
      				 					  title: titulo , 
      				 					  width:500, 
      				 					  height:325}, okLabel: "Fechar" });
}

function openAjaxWindowModal(titulo, link, idjanela, largura, altura, funcaoRetorno) {
	 
	 win = new Window(idjanela , { 
      				 		url: link,
      				 		className: "alphacube", 
      				 		title: titulo ,
      				 		top:10, 
      				 		left:70,  
      				 		width:largura, 
      				 		height:altura, 
      				 		zIndex:150, 
      				 		opacity:1, 
      				 		resizable: true
      				 		}
      				    )
      				    
 	win.setCloseCallback(funcaoRetorno);
	win.setDestroyOnClose();
	win.show(true);	

}

var sbe_window_loaded = false;

function marcarJanelaCarregada() {
	sbe_window_loaded = true;
}

function isJanelaCarregada() {
	return sbe_window_loaded;
}

Event.observe(window, 'load', function() {marcarJanelaCarregada() }, false);

function abrirPopUp2(url){
    var janela = window.open(url, 'repdet2', 'top=95,left=145,width=795,height=478,maximized=no,toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,scrolling=no,resizable=yes');
    janela.focus();
    if (janela.document != null && janela.document.getElementById('carregando') != null) {
    	janela.document.getElementById('carregando').style.display = ''
    }
}

function abrirPopUp(url){
	var randomnumber=Math.floor(Math.random()*11);
    var janela = window.open(url, 'repdet'+randomnumber , 'top=95,left=145,width=795,height=478,maximized=no,toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,scrolling=no,resizable=yes');
    janela.focus();
    if (janela.document != null && janela.document.getElementById('carregando') != null) {
    	janela.document.getElementById('carregando').style.display = ''
    }
}

function trocaimagem(id, src){
    if (id != null) {
        $(id).src = src;
    }
}

function trocacor(id, cor){
    $(id).style.color = cor;
}

// retornar apenas numeros
function v_NR(tecla)
{
	if(typeof(tecla) == 'undefined')
		var tecla = window.event;

	var codigo = (tecla.which ? tecla.which : tecla.keyCode ? tecla.keyCode : tecla.charCode);

	// permite números, 8=backspace, 46=del, 9=tab , 45=-
	if ( (codigo == 45 ) || (codigo >= 48 && codigo <= 57) || (codigo >= 96 && codigo <= 105) || codigo == 8 || codigo == 46 || codigo == 9 )
	{ return true; }
	
	return false;
}

function setupInputDinheiro(input) {
	if (isJanelaCarregada()) {
		_setupInputDinheiro_unit(input)
	} else {
		Event.observe(window, 'load', function() {_setupInputDinheiro_unit(input) }, false);
	}
}

function _setupInputDinheiro_unit(input) {

	input.onkeypress = function (e) {
		if (typeof(e) == 'undefined') {
			e = window.event;
		}
		var codigo = (e.which ? e.which : e.keyCode ? e.keyCode : e.charCode);
		if ((codigo < 48 || codigo > 57) && !(codigo >= 35 && codigo <= 40) && (codigo != 8 && codigo != 46 && codigo != 44 && codigo != 9 ) && (codigo != 45)) {
			return false;
		}
		return true;
	}
	
	input.onfocus = function(e) {
		if (this.value == '') {
			this.value = '0,00'
		}
	}
		
	input.onchange = function(e) {
		var valor = this.value;
		
		if (valor != '') {
			valor = valor.toString().replace(/\./g,',')
		
			if (valor.match(',') == null && !isNaN(valor)) {
				valor = valor + ',00'
			} else if (valor.match(/,.$/)) {
				valor = valor + '0'
			} else if (!valor.match(/,/)) {
				this.value = '0,00'
				return;
			}
			
			while (valor != '' && !valor.match(/,..$/)) {
				valor = valor.slice(0,valor.length-1)
			}
			
			//agora que tem o valor certo, tira todas as virgulas e poe de novo em duas casas decimais depois. 
			//Isso trata quando tem várias vírgulas
			valor = valor.replace(/,/g,'');
			
			valor = valor.substring(0,valor.length-2) + ',' + valor.substring(valor.length-2,valor.length)
			
			this.value = valor
		} else {
			this.value = '0,00'
		}
	}
	input.onchange()
}

function setupInputInteiro(input) {
	if (isJanelaCarregada()) {
		_setupInputInteiro_unit(input)
	} else {
		Event.observe(window, 'load', function() {_setupInputInteiro_unit(input) }, false);
	}
}

function _setupInputInteiro_unit(input, aceitaNegativo) {

	input.onkeypress = function (e) {
		if (typeof(e) == 'undefined') {
			e = window.event;
		}
		var codigo = (e.which ? e.which : e.keyCode ? e.keyCode : e.charCode);
		if ((codigo < 48 || codigo > 57) && !(codigo >= 35 && codigo <= 40) && (codigo != 8 && codigo != 9)) {
			return false
		} 
		return true;
	}
	
	input.onfocus = function(e) {
		if (this.value == '') {
			this.value = '0'
		}
	}
		
	input.onchange = function(e) {
		var valor = this.value;
		
		if (valor != '') {
			valor = valor.toString().replace(/\./g,'')
			valor = valor.toString().replace(/\,/g,'')		
			this.value = valor
		} else {
			this.value = '0'
		}
	}	
	input.onchange()
}

function setupInputInteiroNegativo(input) {
	if (isJanelaCarregada()) {
		_setupInputInteiroNegativo_unit(input)
	} else {
		Event.observe(window, 'load', function() {_setupInputInteiroNegativo_unit(input) }, false);
	}
}

function _setupInputInteiroNegativo_unit(input) {

	input.onkeypress = function (e) {
		if (typeof(e) == 'undefined') {
			e = window.event;
		}
		var codigo = (e.which ? e.which : e.keyCode ? e.keyCode : e.charCode);
		if ((codigo < 48 || codigo > 57) && !(codigo >= 35 && codigo <= 40) && (codigo != 8 && codigo != 9 && codigo != 45)) {
			return false
		} 
		return true;
	}
	
	input.onfocus = function(e) {
		if (this.value == '') {
			this.value = '0'
		}
	}
		
	input.onchange = function(e) {
		var valor = this.value;
		
		if (valor != '') {
			valor = valor.toString().replace(/\./g,'')
			valor = valor.toString().replace(/\,/g,'')		
			this.value = valor
		} else {
			this.value = '0'
		}
	}	
	input.onchange()
}

function setupInputData(input) {
	if (isJanelaCarregada()) {
		_setupInputData_unit(input)
	} else {
		Event.observe(window, 'load', function() {_setupInputData_unit(input) }, false);
	}
}

function _setupInputData_unit(input) {

	input.onkeypress = function (e) {
		if (typeof(e) == 'undefined') {
			e = window.event;
		}
		var codigo = (e.which ? e.which : e.keyCode ? e.keyCode : e.charCode);
		if ((codigo < 47 || codigo > 57) && !(codigo >= 35 && codigo <= 40) && (codigo != 8 && codigo != 46 && codigo != 32 && codigo != 58 && codigo != 9)) {
			return false;
		}
		return true;
	}
		
	input.onchange = function(e) {
		if (this.value != '' && this.value.match(/..\/..\/..../) == null) {
		
			if (this.value.length == 8 && !isNaN(parseInt(this.value))) {
				this.value = this.value.substr( 0, 2 ) + '/' + this.value.substr( 2, 2 ) + '/' + this.value.substr( 4, 4 );	
			} else {
				var msg = "Data incorreta! Utilize o formato de data 'dd/mm/yyyy'. \n"
				msg += "Por exemplo: '21/10/1994'."
				alert(msg)
			}
		}
	}
}

/* Working with the cursor position
   http://parentnode.org/javascript/working-with-the-cursor-position/ 
   http://javascript.nwbox.com/cursor_position/
   */
function setCaretTo(obj, pos) { 
    if(obj.createTextRange) { 
        /* Create a TextRange, set the internal pointer to
           a specified position and show the cursor at this
           position
        */ 
        var range = obj.createTextRange(); 
        range.move("character", pos); 
        range.select(); 
    } else if(obj.selectionStart) { 
        /* Gecko is a little bit shorter on that. Simply
           focus the element and set the selection to a
           specified position
        */ 
        obj.focus(); 
        obj.setSelectionRange(pos, pos); 
    } 
} 

function getSelectionStart(obj) {
	if (obj.createTextRange) {
		var r = document.selection.createRange().duplicate()
		r.moveEnd('character', obj.value.length)
		if (r.text == '') return obj.value.length
		return obj.value.lastIndexOf(r.text)
	} else return obj.selectionStart
}

function getSelectionEnd(obj) {
	if (obj.createTextRange) {
		var r = document.selection.createRange().duplicate()
		r.moveStart('character', -obj.value.length)
		return r.text.length
	} else return obj.selectionEnd
}

/* funcoes de formatacao de data e valor */

// Formata data no padr?o DDMMAAAA
function formataData(campo){
	campo.value = filtraCampo(campo);
	vr = campo.value;
	tam = vr.length;

	if ( tam > 2 && tam < 5 )
		campo.value = vr.substr( 0, tam - 2  ) + '/' + vr.substr( tam - 2, tam );
	if ( tam >= 5 && tam <= 10 )
		campo.value = vr.substr( 0, 2 ) + '/' + vr.substr( 2, 2 ) + '/' + vr.substr( 4, 4 ); 

}

// limpa todos os caracteres especiais do campo solicitado
function filtraCampo(campo){
	var s = "";
	var cp = "";
	vr = campo.value;
	tam = vr.length;
	for (i = 0; i < tam ; i++) {  
		if (vr.substring(i,i + 1) != "/" && vr.substring(i,i + 1) != "-" && vr.substring(i,i + 1) != "."  && vr.substring(i,i + 1) != "," ){
		 	s = s + vr.substring(i,i + 1);}
	}
	campo.value = s;
	return cp = campo.value
}

// input type="text" name="cep" id="cep" onkeypress="return formata_keypress(this, '999.999.999-99', (event ? event : Event))"> // formata o campo para cep
// O caracter '9' define que só será permitido números
// O caracter '?' define que é permitido qualquer caracter
function formata_keypress(campo, mask, evt) 
{
	var evt = evt ? evt : window.event;
    var key = (evt.keyCode ? evt.keyCode : (evt.which ? evt.which : evt.charCode));
	
	if (key == 8 || key == 13 || key == 37 || key == 38 || key == 39 || key == 40 || key == 9) 
	{
		return true;
	}

 	string = campo.value;  
 	i = string.length;

 	if(i < mask.length)
 	{
  		if (mask.charAt(i) == '9') 
  		{
       		return (key > 47 && key < 58);
      	} 
      	else 
      	{
       		if (mask.charAt(i) == '?') 
       		{  
       			return true;  
       		}
          	
          	for (c = i; c < mask.length; c++) 
          	{
         		if (mask.charAt(c) != '9' && mask.charAt(c) != '?')
         			campo.value = campo.value + mask.charAt(c);
      			else if (mask.charAt(c) == '?')
      			{
               		return true;
       			} 
       			else 
       			{
         			return (key > 47 && key < 58);
          		}
       		}
    	}
	} 
  	else 
  		return false;
}

function formata_blur(campo, mask) 
{
    var valortemp = campo.value;
    campo.value='';
    if(valortemp.length > 0 && valortemp.length <= mask.length)
    {  	
       	var posicaomascara = mask.length-1;
    	for(i = valortemp.length-1; i >= 0  ; i--)
    	{
	    	var atualizado = false;
	    	var caracteratual = valortemp.charAt(i);
	    	
	    	while((mask.charAt(posicaomascara) != '9' && mask.charAt(posicaomascara) != '?')
	    		  && (posicaomascara >= 0)) 
	      	{
	      		campo.value += mask.charAt(posicaomascara);  
	      		posicaomascara--;
	      	}
	  		 
	  		while((mask.charAt(posicaomascara) == '9')
	    		  && (posicaomascara >= 0 && atualizado==false)) 
	      	{
	      		if(caracteratual >= '0' && caracteratual <= '9')
	      		{
		      		campo.value += caracteratual;
		      		atualizado=true;
		      	}  
	      		posicaomascara--;
	      	}
	      	
	    	while((mask.charAt(posicaomascara) == '?')
	    		  &&(posicaomascara >= 0 && atualizado==false)) 
	      	{
	      		campo.value += caracteratual;  
	      		posicaomascara--;
	      		atualizado=true;
	      	}    	
		}
	}
	else
	{
	 	campo.value=valortemp;
	}
}

function consolidarImagem(nomeImagem) {
	$(nomeImagem).style.display = 'none'
}
