// JavaScript Document
function AjaxRequest() {
  Ajax = false;
  if (window.XMLHttpRequest) { // Mozilla, Safari,...
        Ajax = new XMLHttpRequest();
		if(Ajax.overrideMimeType) {
		   Ajax.overrideMimeType('text/xml'); }
   } else if (window.ActiveXObject) { // IE
          try {
               Ajax = new ActiveXObject("Msxml2.XMLHTTP");
              } catch (e) {
	                try {
	                    Ajax = new ActiveXObject("Microsoft.XMLHTTP");
		                } catch (e) {}
             }
   }		
} 

// BUSCA AVANÇADA -------------------------------------

function pisca(nObj) {
    oObj=document.getElementById(nObj);
    tCor=oObj.style.backgroundColor;
    oObj.style.backgroundColor="#ffff00";
    p = setTimeout("oObj.style.backgroundColor=tCor", 500);
    
}

function buscaAv(oForm,oCampo) {
	oGat=oCampo;
	acion=oForm;
	AjaxRequest();
	if(!Ajax) {
		alert('[Erro]');
		return false;
	}
	if(oForm=='t') {  	// primeira busca
		param="?tp";
        oForm=document.getElementById('fbuscaav');
	} else {  			// busca com interação
		param="?";
	}
		qtf=oForm.elements.length;
		for(i=0; i<qtf; i++) {
			oC=oForm.elements[i];
			vrc=oC.value;
			tpc=oC.type;
			nc=oC.name;
			if (tpc=='select-one' && vrc!='' && nc!='c_modelo' && param!='?tp') {
				tpar=vrc.replace('_', '=')+'&';
				param+=tpar;  // parâmetros GET do php
			}
			else if (tpc=='select-one' && vrc=='' && nc!='c_modelo') {
                 while(oC.options.length>0) oC.options[0]=null;  // limpa campos não afetados
			}
			else if (tpc=='select-one' && param=='?tp') {
                 while(oC.options.length>0) oC.options[0]=null;  // limpa campos não afetados
			}

		}   // fim do for i

	endxml="loja/consulta.php";
	arqui=endxml+param;  // arquivo PHP + get
	//arqui="loja/consulta_testes.xml";  // TESTES //////////////////
    
	Ajax.onreadystatechange = atualizaBusca;
    Ajax.open("GET", arqui, true);
	Ajax.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); 
	Ajax.setRequestHeader("Cache-Control", "no-store, no-cache, must-revalidate");
	Ajax.setRequestHeader("Pragma", "no-cache");
    Ajax.send(null);

}


function atualizaBusca() {
	if (Ajax.readyState == 4) {
       	if (Ajax.status == 200) {
			xmlDoc = Ajax.responseXML;
			nos  = xmlDoc.getElementsByTagName('produtos')[0].childNodes;
			qtn = nos.length;

			for (x=0; x<qtn; x++) {
			if (nos[x].nodeType == 1) {
				nom=nos[x].nodeName;
				nCampo = "c_"+nom;
				if(nom=="modelo") {
					oAt=false;
					oId="codin";
				} else {
					oAt=true;
					oId="id";
				}
			  // Limpando campo select
			  c=document.getElementById(nCampo);
              if(c.value=="") {
                while(c.options.length>0) c.options[0]=null;
				c.options[0]=new Option("-- Selecione --","");
				if (c.id!='c_modelo') {  // cor do 1º option
					//c.options[0].style.backgroundColor="#efefef";
					c.options[0].style.color="#777700"; 
				}
				oNo=nos[x].getElementsByTagName(oId);
                qtv=oNo.length;

				for(y=0; y<qtv; y++) {
                    if(oNo[y].nodeType==1) {
						if(oAt) {  // outros nos
							nome= oNo[y].childNodes[0].nodeValue;
							valor=oNo[y].attributes[0].nodeValue;
							
						} else  {  // nó modelo
							valor=oNo[y].childNodes[0].nodeValue;
							nome=oNo[y].attributes[0].nodeValue;
						}
						c.options[c.options.length]=new Option(valor,nome); // cria novo option
						newOpt=c.options[c.options.length-1];
						if(newOpt.value==oGat) newOpt.selected=true;  // seleciona o option
					}
				}  // fim do for y
               }
              }
			} // fim do for x
			pisca('c_modelo');
		}
	}
}

function verModelo(sMod) {
	if(sMod!="") {
		var loc="loja/index.php?produto="+sMod;
        	window.location=loc;
     } else {
          alert("Por favor, escolha um dos produtos disponíveis!");
     }
}


// SELECIONAR PRODUTOS -------------------------------------

function adicionar(texto) {
		quebra=texto.split('***');
		document.getElementById('carro').value = quebra[1];
		if (quebra[0]!="") alert(quebra[0]);
}

function alteraLabel(obj,texto,stat) {
	if(texto=='') texto=oldVal;
	obj.value=texto;
	obj.disabled=stat
}

function processaResposta() {  // para AJAX assíncrono
		if (Ajax.readyState == 4) {
			if (Ajax.status==200) {
				adicionar(Ajax.responseText);  
				alteraLabel(obj,'',false);
          	} else alert('Erro: '+Ajax.statusText+'.\nPor favor, tente novamente ou recarregue a página');
		}
}

function processaResposta2() {  // para AJAX síncrono
	tempo=setTimeout("msgErro()", 7000);
		if (Ajax.readyState == 4) {
			if (Ajax.status==200) {
				clearTimeout(tempo);
				adicionar(Ajax.responseText);  
				alteraLabel(obj,'',false);
				return true;
          	} else  { 
				alert('Erro: '+Ajax.statusText+'.\nPor favor, tente novamente ou recarregue a página');
				alteraLabel(obj,'',false);
				return false;
			}
		} else processaResposta2;
}

function msgErro() {
	alert('Não foi possivel selecionar esse produto.\nPor favor, tente novamente');
	alteraLabel(obj,'',false);
	return false;
}

function confirmact(oact) {
	resp = confirm('Tem certeza que deseja '+oact+'?');
	return resp;
}

function comprar(prod,qtd,oBt,c) {
	qt=document.getElementById('carro').value;
	if(c=='Ver' && qt=='0') {
		alert("Não existem produtos selecionados!");
		return false;
	}
	if(c=='Ver' && qt!='0') {
		oForm=oBt.form;
		oForm.action=ender+"/loja/index.php";
		//oForm.method="POST";
		return true;
	}
	if(c=='Selecionar'||c=='Comprar'||c=='Atualizar') {
		if(isNaN(qtd)||qtd<=0||qtd.indexOf('.')>0||qtd.indexOf(',')>0) {
			alert("Por favor, defina um valor válido para quantidade de produtos");
			return false;
		}
	}
	if(c=='Excluir') {
		ret=confirmact('REMOVER esse produto da seleção');
		if(ret==false) return ret;
	}
	obj = oBt;
	oldVal=obj.value;
	alteraLabel(oBt,'Aguarde',true);
	param="c="+c+"&p="+prod+"&q="+qtd+"&js=true";
	aurl=ender+"/loja/comprar.php?"+param;
	AjaxRequest();	   
	//Ajax.onreadystatechange = processaResposta2;
	Ajax.open('GET', aurl, false);
	Ajax.send(null);
	processaResposta2();
	if(c=='Excluir') {
		nurl=ender+"/loja/index.php?c=Ver";
		window.location=nurl;
	}
	return false;
}
