function openAjax() {
	var ajax;
	try{
	    ajax = new XMLHttpRequest(); // XMLHttpRequest para browsers decentes, como: Firefox, Safari, dentre outros.
	}catch(ee){
	    try{
	        ajax = new ActiveXObject("Msxml2.XMLHTTP"); // Para o IE da MS
	    }catch(e){
	        try{
	            ajax = new ActiveXObject("Microsoft.XMLHTTP"); // Para o IE da MS
	        }catch(E){
	            ajax = false;
	        }
	    }
	}
	return ajax;
}


function getFormulario(pagina, alvo){
		if (confirm('Confirma o pedido?')) {
			if (validaCampos() == 0) {
				var ajax = new openAjax();
				var alvo = document.getElementById(alvo);
				elementos = document.forms[0].elements;
				nrElementos = elementos.length;
				
				var s = 0;
				var senha = new Array();
				var status = true
				var parametros = '';
				for (f = 0; f < nrElementos; f++) {
					if (elementos[f].type == 'hidden' || elementos[f].type == 'text' || elementos[f].type == 'select-one') {
						var elemento = elementos[f];
						parametros += elemento.id + "=" +elemento.value + "&";
					}
				}
				
				if (status == true) {
					ajax.open("POST", pagina + ".php", true);
					ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
					ajax.send(parametros);
					if (ajax.readyState == 1) {
						divOverLook();
						criaDiv('300', '200','Processando pedido', '');
						document.getElementById("divBase").innerHTML = '<p align="center" style="font:icon;padding-top:20px;"><img src="../permutas/imagens/ajax-loader.gif" /><br>Aguarde<br>Processando o pedido...</p>';
					}
					ajax.onreadystatechange = function(){
						if (ajax.readyState == 4 && ajax.status == 200) {
							
							if(isNaN(Number(ajax.responseText))){
								if (document.getElementById('dragme')) {
									document.body.removeChild(document.getElementById('dragme'));
								}
								document.body.removeChild(document.getElementById('divOverLook'));
								alert(ajax.responseText);
							}else{
								if (document.getElementById('dragme')) {
									document.body.removeChild(document.getElementById('dragme'));
								}
								document.body.removeChild(document.getElementById('divOverLook'));
								var url = 'formularioPdf.php?id='+ajax.responseText;
								//document.location.reload();
								if(alert("Cadastro realizado com sucesso!\nCaso sua ficha nao abra, \nentre com contato conosco pelo fone\n(44) 3518-2110\nObrigado!")){
										document.forms[0].reset();
										window.open(url);
									}
							}
						}
					
					}
				}
			}
		}
}

function divOverLook(){
	var width = document.body.scrollWidth;
	var height = document.body.scrollHeight;
	
	var iframe = document.createElement('iframe');
	var div = document.createElement('div');
	div.style.height = height+'px';
	div.style.width = width+'px';
	div.id = 'divOverLook';
	
	iframe.style.position = 'absolute';
	iframe.style.top = '0px';
	iframe.style.left = '0px';
	iframe.style.mozOpacity = 0;
	iframe.style.filter = 'Alpha(Opacity=0)';
	iframe.style.height = height+'px';
	iframe.style.width = width+'px';
	
	div.appendChild(iframe);
	
	document.body.appendChild(div);
}

function selectmouse(e)
	{
	  var fobj       = nn6 ? e.target : event.srcElement;
	  var topelement = nn6 ? "HTML" : "BODY";
	  while (fobj.tagName != topelement && fobj.className != "dragme")
	  {
	    fobj = nn6 ? fobj.parentNode : fobj.parentElement;
	  }
	
	  if (fobj.className=="dragme")
	  {
	    isdrag = true;
	    dobj = fobj;
	    tx = parseInt(dobj.style.left+0);
	    ty = parseInt(dobj.style.top+0);
		
		try {
			x = event.clientX;
			y = event.clientY;
		} 
		catch (err) {
			x = e.clientX;
			y = e.clientY;
		}
	    document.onmousemove=movemouse;
	    return false;
	  }
	
	}

function criaDiv(width,height,titulo,scroll){
	var divCorpo = document.createElement('div');
	var divTitulo = document.createElement('div');
	var divBase = document.createElement('div');
	var imgFechar = document.createElement('img');
	var titulo = document.createTextNode(titulo);
	var b = document.createElement('b');
	b.style.fontSize = '15px';
	b.style.padding = '3px';
	
	if (!document.getElementById('dragme')) {
		
		
		imgFechar.src = '../permutas/imagens/cross.png';
		imgFechar.style.cursor = 'pointer';
		imgFechar.align = 'right';
		imgFechar.onclick = function(){
			document.body.removeChild(document.getElementById('divOverLook'));
			document.body.removeChild(divCorpo);
		}
		
		divBase.style.overflowY = 'auto';
		divBase.style.height = height+'px';
		divBase.style.zIndex = 150;
		divBase.style.padding = '2px';
		divBase.id = "divBase";
		
		divTitulo.style.background = '#999999';
		divTitulo.style.cursor = 'move';
		divTitulo.id = 'divTitulo';
		divTitulo.className = 'divTitulo';
		divTitulo.style.mozOpacity = '50';
		divTitulo.style.height = '20px';
		divTitulo.style.width = '100%';
		divTitulo.style.zIndex = 120;
		divTitulo.appendChild(imgFechar);
		b.appendChild(titulo);
		divTitulo.appendChild(b);
		
		divCorpo.appendChild(divTitulo);
		
		divCorpo.appendChild(divBase);
		
		divCorpo.style.position = 'absolute';
		divCorpo.id = 'dragme';
		divCorpo.className = 'dragme';
		divCorpo.style.zIndex = 120;
		divCorpo.style.width = width+'px';
		divCorpo.style.height = height+'px';
		divCorpo.style.border = '#CCCCCC 1px solid';
		divCorpo.style.background = '#FFFFFF';
		divCorpo.style.top = '500px';
		divCorpo.style.left = '300px'; 
		
		
		document.body.appendChild(divCorpo);
	}
}

function escolheCidade(valor,elem) {
	var ajax = new openAjax();	

     //deixa apenas o elemento 1 no option, os outros são excluídos
     document.forms[0].elements[elem].options.length = 1;
     idOpcao  = document.forms[0].elements[elem];
    
     ajax.open("POST", "cidades.php", true);
     ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    
     ajax.onreadystatechange = function() {
        //enquanto estiver processando...emite a msg de carregando
        if(ajax.readyState == 1) {
           idOpcao.options[0].innerHTML = "Carregando...!";  
        }
        //após ser processado - chama função processXML que vai varrer os dados
        if(ajax.readyState == 4 ) {
           if(ajax.responseXML) {
              processXML(ajax.responseXML,idOpcao);
           }
           else {
               //caso não seja um arquivo XML emite a mensagem abaixo
               idOpcao.options[0].innerHTML = "--Selecione o Estado--";
           }
        }
     }
     //passa o código do estado escolhido
     var params = "estado="+valor;
     ajax.send(params);
}

function processXML(obj,idOpcao){
  //pega a tag cidade
  var dataArray   = obj.getElementsByTagName("cidade");
  //total de elementos contidos na tag cidade
  if(dataArray.length > 0) {
  	
	 //cria um novo option dinamicamente  
	 var novo = document.createElement("option");
	 idOpcao.options.length = 0;
	 var select =  idOpcao;

	 
	 //percorre o arquivo XML paara extrair os dados
     for(var i = 0 ; i <= dataArray.length - 1; i++) {
        var item = dataArray[i];
		var id   =  item.getElementsByTagName("id")[0].firstChild.nodeValue;
		var nome =  item.getElementsByTagName("nome")[0].firstChild.nodeValue;
		var novo = document.createElement("option");
	    novo.value = id;
	    novo.text  = nome;
		select.options.add(novo);
	 }
  }
  else {
    //caso o XML volte vazio, printa a mensagem abaixo
    idOpcao.options[0].innerHTML = "--Selecione o Estado--";
  }      
}

function add(dados,tabela,input){
	var tb = dados.parentNode.parentNode.parentNode.parentNode;
	var celulas = tb.rows[1].cells.length - 1;
	valores = new Array();
	var t = true;
	var tNew = document.getElementById(tabela);
	var tNewLinhas = document.getElementById(tabela).rows.length;
	
	var vl = 0;
	
	for(i = 0; i < celulas;i++){
		var campo = tb.rows[1].cells[i];
		for (c = 0; c < campo.childNodes.length; c++) {
			if (campo.childNodes[c].type == 'text' || campo.childNodes[c].type == 'select-one') {
				if(campo.childNodes[c].value != ''){
					if(campo.childNodes[c].id != 'false'){
						valores[vl] = campo.childNodes[c].value;
						vl++;
						campo.childNodes[c].style.background = '';
						campo.childNodes[c].style.border = '#CCCCCC 1px solid'
					}
				}else{
					campo.childNodes[c].style.background = '#FFECEC';
					campo.childNodes[c].style.border = '#FF8080 1px solid'
					t = false;
				}
			}
		}
		if(t){
			for (c = 0; c < campo.childNodes.length; c++) {
				if (campo.childNodes[c].type == 'text' || campo.childNodes[c].type == 'select-one') {
					if(campo.childNodes[c].value != ''){
						if(campo.childNodes[c].id != 'false'){
							campo.childNodes[c].value = '';
						}
					}
				}
			}
		}
	}
	if (!t) {
		alert('Existe campos em branco.\nVerifique!');
	}
	else {
		if (tNewLinhas >= 0) {
			for (tr = 0; tr < tNewLinhas; tr++) {
				var celulas = tNew.rows[tr].cells.length;
				if(tNew.rows[tr].cells[0].innerHTML == valores[0] && tNew.rows[tr].cells[1].innerHTML == valores[1]){
					t = false;
				}
			}
		}
		
		if(t){
			var rNew = tNew.insertRow(tNewLinhas);

			for (n = 0; n < valores.length; n++) {
				var cNew = rNew.insertCell(n);
				cNew.innerHTML = valores[n];
			}
			
			var cNew = rNew.insertCell(valores.length);
			cNew.onclick = function(){
				tNew.deleteRow(cNew.parentNode.rowIndex)
				varreTabela(tNew, input);
			}
			cNew.innerHTML = '<img src="../permutas/imagens/delete.png" />';
			
			varreTabela(tNew, input);
			tNew.style.display = '';
		}
	}
}

//Varre tabela e atribui seus valores ao input indicado
function varreTabela(table, input){
	var campo = document.getElementById(input);
	campo.value = '';
	var nrRow = table.rows.length;
	
	for(tr = 1;tr < nrRow;tr++){
		var nrCell = table.rows[tr].cells.length;
		for(td = 0;td < nrCell; td++){
			if(table.rows[tr].cells[td].innerHTML != ''){
				campo.value += table.rows[tr].cells[td].innerHTML+'|';
			}
		}
		campo.value += ';';
	}
}