// JavaScript Document

function selection(obj, set_text_default){   
    /* @author Bernardo Rufino  
     * @license Creative Commons Developing Nations: http://creativecommons.org/licenses/devnations/2.0/  
     * @description Function to manipulate the actual selection  
     * @returns It returns an object with an attribute *text* with the current selection text and  
     *        a method *setText()* that receives one argument, the text to be set in the selection.  
     * @parameters The first is the object where you want the selection (DOM or String with id), and  
     *           the second (optional), a boolean, if is true then the *setText()* method will  
     *           append the text if there's no way to replace the selection.  
     *  
     *     !Nao retire essas informacoes!  
     *     !Do not drop this information!  
    */  
    if(obj.constructor == String){
	
		obj = document.getElementById(obj);
	
	}   
	
    var set_text = (set_text_default) ? function(text){obj.value += text;} : function(){return false;};   
    var selection = {text: null, setText: set_text};   
    if(document.selection){   
        
		var range = document.selection.createRange();   
		if (range.text !=""){
		
		selection.text = range.text;   
		selection.setText = function(text){   
		range.text = text.replace(/\\r?\\n/g, "\\r\\n");   
			
		}
		}
    } else if(typeof(obj.selectionStart) != "undefined"){   
        
		selection.text = obj.value.substring(obj.selectionStart, obj.selectionEnd);   
        selection.setText = function(text){   
			if(text != null && text != ""){
            obj.value = obj.value.substring(0, obj.selectionStart) + text + obj.value.substring(obj.selectionEnd);   
			}
        }   
    } else if(window.getSelection){   
        selection.text = window.getSelection().toString();   
		 
    }   
	
    return selection;   
}  

function handleEnter (field, event) {
        var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
        if (keyCode == 13) {
            field.value += "<br>"
        } 
    }      




function ajaxInit() {
	var req;
	try {
		 req = new ActiveXObject("Microsoft.XMLHTTP");
	} catch(e) {
		 try {
			  req = new ActiveXObject("Msxml2.XMLHTTP");
		 } catch(ex) {
		 try {
		   req = new XMLHttpRequest();
	     } catch(exc) {
	 		  alert("Esse browser não tem recursos para uso do Ajax");
	  		 req = null;
	     }
	 }
}
return req;
}

function carregaCombo(id,codigo,campo) {
	ajax = ajaxInit();
	if(ajax) {
		ajax.open("GET","combo_tamanho.asp?codigo=" + codigo + "&indice=" + campo, true);
		ajax.onreadystatechange = function() {
			if(ajax.readyState == 4) {
				if(ajax.status == 200) {
					document.getElementById(id).innerHTML = ajax.responseText;					
				}else{	
					alert(ajax.statusText)
				}
			}
		}
		ajax.send(null);		
	}
}

function carregaComissao(id,codigo) {
	ajax = ajaxInit();
	if(ajax) {
		ajax.open("GET","combo_comissao_emp.asp?codigo="+codigo, true);
		ajax.onreadystatechange = function() {
			if(ajax.readyState == 4) {
				if(ajax.status == 200) {
					document.getElementById(id).innerHTML = ajax.responseText;					
				}else{	
					alert(ajax.statusText)
				}
			}
		}
		ajax.send(null);		
	}
}

function carregaCalculo(id,valor,emp,corret) {
	ajax = ajaxInit();	
	alert("calculo_comissao.asp?valor="+valor + "&cod_emp=" + emp + "&cod_corret=" + corret)
	if(ajax) {
		ajax.open("GET","calculo_comissao.asp?valor="+valor + "&cod_emp=" + emp + "&cod_corret=" + corret, true);
		ajax.onreadystatechange = function() {
			if(ajax.readyState == 4) {
				if(ajax.status == 200) {
					document.getElementById(id).innerHTML = ajax.responseText;					
				}else{	
					alert(ajax.statusText)
				}
			}
		}
		ajax.send(null);		
	}
}
function gerarUsuarios(id,idUsuario,idEmp,idCorret)
{
	num_usuario = document.getElementById(idUsuario)
	comissaoEmp = document.getElementById(idEmp)
	comissaoCorret = document.getElementById(idCorret)

	carregaCalculo(id,num_usuario.value,comissaoEmp.value,comissaoCorret.value);	
	
}

function PreviewPanel(texto) {
	ajax = ajaxInit();
	
	if(ajax) {
			ajax.open("GET","PreviewPanel.asp?texto=" + texto, true);
			ajax.onreadystatechange = function() {
				if(ajax.readyState == 4) {
					if(ajax.status == 200) {
						
						document.getElementById("PreviewPanel").innerHTML = ajax.responseText;
						
					}else{	
						alert(ajax.statusText)
					}
				}
			}
			ajax.send(null);
		
	}
}

function verificaEmail(email) {
	ajax = ajaxInit();
	if(ajax) {
		ajax.open("GET","verifica_email.asp?email=" + email, true);
		ajax.onreadystatechange = function() {
			if(ajax.readyState == 4) {
				if(ajax.status == 200) {
					
					document.getElementById("alerta").value = ajax.responseText;
					if(document.getElementById("alerta").value == 'N'){
						document.getElementById("textoAlerta").style.display = "";
					}
					
				}else{	
					alert(ajax.statusText)
				}
			}
		}
		ajax.send(null);		
	}
}

function Confirm(text, url) {
	var answer = confirm(text)
	if (answer){
		location.href = url;
		
	}
	else{
		
	}
}

var win = null;
function NewWindowPanel(valor){
	
	LeftPosition = (screen.width) ? (screen.width-400)/2 : 0;
	TopPosition = (screen.height) ? (screen.height-300)/2 : 0;
	settings =
	'height=300,width=400,top='+TopPosition+',left='+LeftPosition+',scrollbars=Yes,resizable'
	win = window.open("PreviewPanel.asp?texto="+valor,"",settings)
}

var win = null;
function NewWindow(mypage,myname,w,h,scroll){
	LeftPosition = (screen.width) ? (screen.width-w)/2 : 0;
	TopPosition = (screen.height) ? (screen.height-h)/2 : 0;
	settings =
	'height='+h+',width='+w+',top='+TopPosition+',left='+LeftPosition+',scrollbars='+scroll+',resizable'
	win = window.open(mypage,myname,settings)
}

function sizeFont (elem, acao){    // tamanho inicial da fonte (em px)
    var tamInic = 11;    // Tamanho mínimo da [b]fonte (em px)
	var tamMin = 9;    // Tamanho máximo da fonte (em px)    
	var tamMax = 24;    // Pega o tamanho da fonte. Se não foi setada ainda (primeira vez que a função é executada) terá como tamanho padrão 'tamInic'.
	el = elem.split(",");
	for (x = 0 ; x <= el.length-1; x++){
		if (document.getElementById(el[x]).style.fontSize == "") {            
			var tamFonte = tamInic;
		}else{            
			var tamFonte = parseInt(document.getElementById(el[x]).style.fontSize);            
		}            
		switch (acao){                // Aumenta o tamanho, enquanto foi menor que 'tamMax'                
			case '+':                        
				if (tamFonte < tamMax)
					document.getElementById(el[x]).style.fontSize = (tamFonte + 2) + "px";
			break;                // Diminui o tamanbo, enquanto for maior que 'tamMin'                
			case '-':                        
				if (tamFonte > tamMin)                                
					document.getElementById(el[x]).style.fontSize = (tamFonte - 2) + "px";
			break;
		}
	}
}

function apagarValue(controle, obj){
	if(controle.value == "0"){
		obj.value = ""
		controle.value = "1"
	}
}

//funções para menu suspenso
function pegaDados(codigo,controle,submenu,menu){
	conter = document.getElementById(controle).value;
	if (conter=="1"){
		h=100;
		document.getElementById(controle).value="0";
		document.getElementById(submenu).padding="0px";
		document.getElementById(submenu).style.lineHeight="0px";
		document.getElementById(submenu).style.display="none";
		
	}else{
		h=0;
		document.getElementById(controle).value="1";
		document.getElementById(submenu).style.lineHeight="normal";
		document.getElementById(submenu).style.display="";
		document.getElementById(controle).value="1";
	}
}

function checado(name, cod, id){
	
	novoCod="";
	if(document.getElementById(name).checked){
		document.getElementById(id).value += cod+"|"; 
	}
	if(document.getElementById(name).checked==false){
		valores = document.getElementById(id).value;
		document.getElementById(id).value="";
		codigos = valores.split("|");
		
		for (i=0;i<=codigos.length-2;i++){
			
			if(codigos[i] != cod){
				novoCod = novoCod+codigos[i]+"|";
				document.getElementById(id).value=novoCod;
			}
		}
	}
}
function tipoPessoa()
{
	if(document.getElementById("pessoaF").checked == true)
	{
		document.getElementById("idade").style.visibility = "visible";
		document.getElementById("idade_v").style.visibility = "visible";
		//document.getElementById("vida").style.visibility = "hidden";
		document.getElementById("vida").style.display = "none";
	}
	if(document.getElementById("pessoaJ").checked == true)
	{
		document.getElementById("idade").style.visibility = "hidden";
		document.getElementById("idade_v").style.visibility = "hidden";
		//document.getElementById("vida").style.display = "visible";
		document.getElementById("vida").style.display = "";
	}
}
function isInt(id)
{
   	element = document.getElementById(id)
	var str = /^\d+$/;
	if (str.test(element.value) == false)
	{
		alert("Valor inválido, digite somente números");
		element.focus();
	}
}

function criarElement()
{
	posicao = document.getElementById("posicao").value;	
	
	var geral = document.getElementById("principal");	
	
	var principal = document.createElement("div");
	principal.className = "item_conteudo";
	principal.id = "cont_"+posicao;
	
	
	geral.appendChild(principal);
	
	div = document.createElement("div");
	div.id = "d"+posicao;
	div.className = "contatos_list_data";	
	
	item_ped = document.createElement("input");
	item_ped.type = "text";
	item_ped.name = "data_"+posicao;
	item_ped.id = "data_"+posicao;
	item_ped.className = "caixa_data";
	item_ped.maxLength = 10;
	item_ped.onkeyup = function(){formatar('data_'+posicao,'##/##/####');}
	//item_ped.onkeypress = function(){insNumeric(item_ped,'event');}
	div.appendChild(item_ped);
	principal.appendChild(div);
	
	
	div = document.createElement("div");
	div.id = "d"+posicao;
	div.className = "contatos_list_hora";	
	
	item_ped = document.createElement("input");
	item_ped.type = "text";
	item_ped.name = "hora_"+posicao;
	item_ped.id = "hora_"+posicao;
	item_ped.maxLength = 5;
	item_ped.className = "caixa_data";
	item_ped.onkeyup = function(){formatar('hora_'+posicao,'##:##');}
		
	div.appendChild(item_ped);
	principal.appendChild(div);
	
	div = document.createElement("div");
	div.id = "d"+posicao;
	div.className = "contatos_list_descricao";	
		
	item_desc = document.createElement("input");
	item_desc.type = "text";
	item_desc.name = "desc_"+posicao;
	item_desc.id = "desc_"+posicao;
	item_desc.className = "caixa_descricao";
	item_desc.onblur = function(){adicionar();} 
	
	
	div.appendChild(item_desc);
	principal.appendChild(div);
	
	aux = parseInt(posicao) - 1;
	item_anterior = document.getElementById("desc_"+aux);
	item_anterior.onblur = "";
	document.getElementById("data_"+posicao).focus();
		
}
function adicionar()
{	
	var posicao = document.getElementById("posicao").value;
	aux = parseInt(posicao) - 1;
	nome = document.getElementById("desc_"+aux);
	data = document.getElementById("data_"+aux);
	if( (nome.value != "") && (data.value != "") )
	{
		criarElement();
		document.getElementById("posicao").value = parseInt(posicao) + 1;
	}
	else
	{
		if ( ( nome.value != "") && (data.value == "") )
		{
			alert("Preencha o campo data")
			data.focus();
		}
		else
		{
			
			if ( ( data.value != "") && (nome.value == "") )
			{
				alert("Preencha o campo descrição")
				nome.focus();	
			}	
		}
	}
					
}

//Insercao de Campos Formulario de Vendas
function criarElementUsuario()
{
	posicao = document.getElementById("posicao").value;	
	
	var geral = document.getElementById("principal");	
	
	var principal = document.createElement("div");
	principal.className = "item_conteudo";
	principal.id = "cont_"+posicao;
	
	
	geral.appendChild(principal);
	
	div = document.createElement("div");
	div.id = "d"+posicao;
	div.className = "usuario_list_nome";	
		
	item_desc = document.createElement("input");
	item_desc.type = "text";
	item_desc.name = "nome_"+posicao;
	item_desc.id = "nome_"+posicao;
	item_desc.className = "caixa_descricao";	
	
	div.appendChild(item_desc);
	principal.appendChild(div);
	
	div = document.createElement("div");
	div.id = "d"+posicao;
	div.className = "usuario_list_data";	
	
	item_ped = document.createElement("input");
	item_ped.type = "text";
	item_ped.name = "data_"+posicao;
	item_ped.id = "data_"+posicao;
	item_ped.className = "caixa_data";
	item_ped.maxLength = 10;
	item_ped.onkeyup = function(){formatar('data_'+posicao,'##/##/####');}
	//item_ped.onkeypress = function(){insNumeric(item_ped,'event');}
	div.appendChild(item_ped);
	principal.appendChild(div);
	
	
	div = document.createElement("div");
	div.id = "d"+posicao;
	div.className = "usuario_list_valor";	
	
	item_ped = document.createElement("input");
	item_ped.type = "text";
	item_ped.name = "valor_"+posicao;
	item_ped.id = "valor_"+posicao;
	item_ped.className = "caixa_data";
	item_ped.onblur = function(){adicionarUsuario();} 
		
	div.appendChild(item_ped);
	principal.appendChild(div);	
	
	aux = parseInt(posicao) - 1;
	item_anterior = document.getElementById("valor_"+aux);
	item_anterior.onblur = "";
	document.getElementById("nome_"+posicao).focus();
	vendaCalcula = false;
		
}
function adicionarUsuario()
{	
	var posicao = document.getElementById("posicao").value;
	aux = parseInt(posicao) - 1;
	nome = document.getElementById("nome_"+aux);
	data = document.getElementById("data_"+aux);
	valor = document.getElementById("valor_"+aux);
	if( (nome.value != "") && (data.value != "") && (valor.value != "") )
	{
		criarElementUsuario();
		document.getElementById("posicao").value = parseInt(posicao) + 1;
	}
	else
	{
		if ( ( nome.value != "") && (data.value == "") )
		{
			alert("Preencha o campo data de nascimento")
			data.focus();
		}
		else
		{
			if ( ( nome.value != "") && (valor.value == "") )
			{
				alert("Preencha o campo valor")
				valor.focus();	
			}
			else
			{
				if ( ( data.value != "") && (nome.value == "") )
				{
					alert("Preencha o campo nome")
					valor.focus();	
				}
				else
				{
					if( ( data.value != "") && (valor.value == "") )
					{
						alert("Preencha o campo valor")
						valor.focus();	
					}
					else
					{
						if( ( valor.value != "") && (nome.value == "") )
						{
							alert("Preencha o campo nome")
							valor.focus();	
						}
						else
						{
							if ( ( valor.value != "") && (data.value == "") )
							{
								alert("Preencha o campo data de nascimento")
								valor.focus();	
							}
						}
					}
				}
			}
		}
	}
					
}


function formatar(id, mask)
{
	src = document.getElementById(id);
	var i = src.value.length;
  	var saida = mask.substring(0,1);
  	var texto = mask.substring(i)
	if (texto.substring(0,1) != saida)
  	{
    	src.value += texto.substring(0,1);
  	}
}

function insNumeric(obj,event)
{
    var tecla = event.charCode;
    var ie = event.keyCode;
    if (!event) event = window.event;
    var code;
    if (event.keyCode) code = event.keyCode;
    else if (event.which) code = event.which; // Netscape 4.?
//se nao for número nem parentesis ou espaço
    if ((code < 48 || code > 59) && (code != 8 ) ){
      event.returnValue = false;
      if (event.which){
        event.preventDefault();
      }
      return false;
    }else{
      event.returnValue = true;
      return true;
    }
 }

function isFloat(valor)
{
	var valor_text = valor;
	var str = /^[+-]?((\d+|\d{1,3}(\.\d{3})+)(\,\d*)?|\,\d+)$/;
	return str.test(valor_text);
}
function mostraMotivo()
{
	if (document.getElementById("pos_negociacao").value == "negociacao")
	{
		document.getElementById("motivoCampo").style.visibility = "visible";
		document.getElementById("motivoInput").style.visibility = "visible";
	}
	else
	{
		document.getElementById("motivoCampo").style.visibility = "hidden";
		document.getElementById("motivoInput").style.visibility = "hidden";	
	}
	
}


var vendaCalcula = true;
function alterar(controle)
{
	contrat = document.getElementById("cont")
	usuar = document.getElementById("usu")
	if (controle == 1)
	{
		document.getElementById('contratante').style.display='block';
		document.getElementById('usuario').style.display='none';
		contrat.className = "imagem_borda_azul";
		usuar.className = "imagem_borda_branco";
	}
	else
	{
		document.getElementById('contratante').style.display='none';
		document.getElementById('usuario').style.display='block';
		contrat.className = "imagem_borda_branco";
		usuar.className = "imagem_borda_azul";
		
	}
	

}
function tipoPessoaVenda()
{
	if(document.getElementById("pessoaF").checked == true)
	{
		document.getElementById("fisica").style.display = "block";
		document.getElementById("juridica").style.display = "none";
	}
	if(document.getElementById("pessoaJ").checked == true)
	{
		document.getElementById("fisica").style.display = "none";
		document.getElementById("juridica").style.display = "block";
	}
}
function validaUsuarios()
{
	posicao = document.getElementById("posicao").value;
	erro = 0;
	for(i=0;i < posicao;i++)
	{
		nome = document.getElementById("nome_"+i);
		data = document.getElementById("data_"+i);
		valor = document.getElementById("valor_"+i);
		if( (nome.value != "") || (data.value != "") || (valor.value != "") )
		{
			if(nome.value == "")
			{
				alert("Preencha o campo nome do usuário");
				nome.focus();
				erro = 1 
				break;
			}
			if(data.value == "")
			{
				alert("Preencha o campo data de nascimento");
				data.focus();
				erro = 1 
				break;
			}
			if( (data.value != "") && (validaData(data.value) == false) )
			{
				alert("Data de nascimento inválida");
				data.focus();
				erro = 1 
				break;
			}
			if(valor.value == "")
			{
				alert("Preencha o valor");
				valor.focus();
				erro = 1 
				break;
			}
			if(valor.value == "")
			{
				alert("Preencha o valor");
				valor.focus();
				erro = 1 
				break;
			}	
			if (valor.value != "")
			{
				valor_aux = valor.value.replace(".","")	
				valor.value = valor_aux
				if(isFloat(valor_aux) == false)				
				{
					alert("Valor inválido");
					valor.focus()
					erro = 1
					break;
					
				}			
					
			}
		}
		
	}
	if(erro == 0)
	{
		return true
	}
	else
	{
		return false	
	}
	
}
function calcularComissao()
{
	total = calculaTotal();
	if ((total != "erro") && (total !=0) )
	{
		empresa = document.getElementById("empresaPlano");
		var comissaoCorret = document.getElementById("comissaoCorret")
		var comissao = document.getElementById("comissaoEmp");
		if (validaUsuarios())
		{
			if(empresa.value == "0")
			{
				alert("Selecione uma empresa");
				empresa.focus();
			}
			else
			{
				if(comissao.value == "0")
				{
					alert("Selecione uma comissão de empresa");
					comissao.focus();
				}
				else
				{
					if(comissaoCorret.value == "0")
					{
						alert("Selecione uma comissão de corretor");
						comissaoCorret.focus();
					}
					else
					{
						document.getElementById("total_venda").value = parseFloat(total);
						carregaCalculo('comissao',total,comissao.value,comissaoCorret.value);
						vendaCalcula = true;
					}
				}
			}
		}	
			
		
	}
}
function recalcular(tipo,id)
{
	total = calculaTotal();
	if ((total != "erro") && (total !=0) )
	{
		empresa = document.getElementById("empresaPlano");
		var comissao = document.getElementById("comissaoEmp");
		var comissaoCorret = document.getElementById("comissaoCorret")
		if(tipo == "empresa")
		{
			
				if(empresa.value == "0")
				{
					alert("Selecione uma empresa");
					empresa.focus();
				}
				else
				{
					if(comissao.value == "0")
					{
						alert("Selecione uma comissão de empresa");
						comissao.focus();
					}
					else
					{
						carregaCalculo(id,total,comissao.value,'');
						document.getElementById("total_venda").value = parseFloat(total);
					}
				}		
			
		}
		if(tipo == "corretor")
		{
			
				if(comissaoCorret.value == "0")
				{
					alert("Selecione uma comissão de corretor");
					comissaoCorret.focus();
				}
				else
				{
					carregaCalculo(id,total,'',comissaoCorret.value);
					document.getElementById("total_venda").value = parseFloat(total);
				}
			
		}
	}
}
function calculaTotal()
{
	pos = document.getElementById("posicao").value;
	total = 0;
	cont = 0;
	if (validaUsuarios())
	{
		for(i=0;i < pos;i++)
		{
			valor = document.getElementById("valor_"+i);		
			if (valor.value != "")
			{
				valor_aux = valor.value.replace(".","")	
				valor.value = valor_aux
				if(isFloat(valor_aux))
				{
					
					total = total + parseFloat(valor_aux.replace(",","."));	
					
				}
				else
				{
					alert("Valor inválido");
					valor.focus()
					total = "erro"
					break;
					
				}			
					
			}
		}
		return total;
	}
	else
	{
		total = "erro"
		return total
	}
	

}

function calculaPorcetagem()
{
	total = 0
	valor = 0
	for (i=1;i<=5;i++)
	{
		element = document.getElementById("v_"+i)
		valor = element.value;
		if (valor == "")
		{
			valor = 0;
			element.value = valor;
		}
		if(isFloat(valor) == false)
		{
			alert("Valor inválido");
			total = false
			element.focus();
			break
		}
		else
		{
			valor = valor.replace(",",".");
			total = total + parseFloat(valor);
		}
	}
	return total;
}




//fim