// JavaScript Document
document.write("<script type='text/javascript' src='js/hs.js'></scr"+"ipt>");

var ajax_gw = 'ajax/gw.veiculos.ajax.php';
atual=0;fila=[];ifila=0;
var xmlhttp; var CadastroInfo; var local; var acao='update'; var atualizado=false; 
try{xmlhttp=new XMLHttpRequest();}catch(ee){try{xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");}catch(e){try{xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");}catch(E){xmlhttp=false;}}}
var xmlhttp2; 
try{xmlhttp2=new XMLHttpRequest();}catch(ee){try{xmlhttp2=new ActiveXObject("Msxml2.XMLHTTP");}catch(e){try{xmlhttp2=new ActiveXObject("Microsoft.XMLHTTP");}catch(E){xmlhttp2=false;}}}
function title(value){
	document.getElementById("topodest2").innerHTML = value;
}

function ucfirst (str) {
    str += '';
    var f = str.charAt(0).toUpperCase();
    return f + str.substr(1);
}

function ajaxHTML(id,url) {
	title2 = url.split('.');
	if(title2[0]=="busca"){
		title2[0]="Estoque";	
	}
	title(ucfirst(title2[0]));
	//alert("ajaxHTML("+id+","+url+")");
    //document.getElementById(id).innerHTML="Carregando...";
	fila[fila.length]=[id,url];
    if((ifila+1)==fila.length)ajaxRun();
}
function ajaxRun(){
	loader_show();
	tmp_str = fila[ifila][1];
	while (tmp_str.indexOf("&") > -1) {
		tmp_str = tmp_str.replace(/&/,"|");	
	}
    //xmlhttp2.open("GET",tmp_str,true);
	xmlhttp2.open("GET",'contentAJAX.php?url='+encodeURI(tmp_str),true);
    xmlhttp2.onreadystatechange=function() {
        if (xmlhttp2.readyState==4){
            //retorno=unescape(xmlhttp2.responseText.replace(/\+/g," "))
            //document.getElementById(fila[ifila][0]).innerHTML=unescape(xmlhttp2.responseText.replace(/\+/g," "));
			document.getElementById(fila[ifila][0]).innerHTML=unescape(xmlhttp2.responseText);
            ifila++;
            if(ifila<fila.length)setTimeout("ajaxRun()",20)
						hs.graphicsDir = 'hs/';
						hs.outlineType = 'rounded-white';
						hs.restoreTitle = 'Clique para fechar a imagem ou arraste para mover';
						hs.loadingText = 'Carregando...';
						hs.loadingTitle = 'Clique para cancelar';
						hs.captionEval = 'this.thumb.alt';
			loader_hide();
        }
    }
    xmlhttp2.send(null)
}
function writeDIV(id,conteudo) {
	document.getElementById(id).innerHTML=conteudo;
}
function loader_show() { 
	var l  = document.getElementById('loader');
	l.style.visibility = "visible"; 
	//alert('w: '+l.style.width+' h: '+l.style.height); 
	l.style.left = ((document.body.offsetWidth)/2)-(75);
	l.style.top  = ((document.body.offsetHeight)/2)-(25);
	//document.getElementById('loader').style.top  = "110";
}
function loader_hide() { document.getElementById('loader').style.visibility = "hidden";	}
function init_ajax_combo() {
	//alert('init_ajax_combo()')
	array_request = new Object();
	array_request.totalItens = 0;
	array_request.index = 0;
	array_request.cmb = new Array();
	array_request.ra  = new Array();
	array_request.pv  = new Array();
	array_request.dv  = new Array();
	array_request.tit = new Array();
	array_request.rev = new Array();
}
function next_ajax_combo() {
	if (array_request.index < array_request.totalItens) {		
		setTimeout("preenche_combo()",20);		
	} /*else if (array_request.index == 0 && array_request.totalItens > 1) {
		init_ajax_combo();
	}*/
}
var array_request = false;
function ajax_combo(combo, remote_action, post_vars, title, default_value, id_revenda) {
	//alert("ajax_combo("+combo+", "+remote_action+", "+post_vars+", "+title+", "+default_value+");\nindex: "+array_request.index+"\ntotalItens: "+array_request.totalItens);
	if (!array_request) init_ajax_combo();
	var cc = 0;
	document.getElementById(combo).length = 0;
	document.getElementById(combo).options[0] = new Option('Carregando...','');
	array_request.cmb.push(combo);
	array_request.ra.push(remote_action);
	array_request.pv.push(post_vars);
	array_request.dv.push(((!default_value || default_value=='')?(""):(default_value)));
	array_request.tit.push(title);
	array_request.rev.push(id_revenda);
	array_request.totalItens++;
	if ((array_request.index+1) == array_request.totalItens || (array_request.index) == array_request.totalItens) {
		preenche_combo();
	} else {
		//alert('NAO INICIOU');
	}	
}
function preenche_combo() {
	//alert('preenche_combo();');
	var pp = array_request.index;
	//var combo = array_request.cmb[pp];
	var remote_action = array_request.ra[pp];
	var post_vars 	  = array_request.pv[pp];
	var title 		  = array_request.tit[pp];
	var default_value = array_request.dv[pp];
	var id_revenda = array_request.rev[pp];
	var cb 			  = document.getElementById(array_request.cmb[pp]);
	//var msg_carregando = document.getElementById('msg_carregandof');
	if (!cb) {
		alert('ComboBox Inválida !');
		array_request.index++;
		next_ajax_combo();
		return;
	}
	var str_url = ajax_gw+"?acao="+remote_action;
	if (post_vars) {
		for (var s in post_vars) {
			str_url += "&"+s+"="+post_vars[s];
		}
	}

	if (id_revenda) {
		for (var s in id_revenda) {
			str_url += "&"+s+"="+id_revenda[s];
		}
	}

	//alert('str_url: '+str_url);
	var sel_index = false;
	//msg_carregando.innerHTML='Carregando...';
	xmlhttp.open("GET", str_url, true);
	loader_show();
	xmlhttp.onreadystatechange=function() {
        if (xmlhttp.readyState==4){
			loader_hide();
			array_request.index++;
			retorno = xmlhttp.responseText;
			dataProvider = new Function("return "+retorno)();
			//alert('TotalRows: '+dataProvider.totalRows);
			if (title && title != "") {
				cb.options[0] = new Option(title,'');
			}
			if (dataProvider['totalRows']) {
				if (Number(dataProvider.totalRows) < 1) {
					reset_combo(cb);
					return;
				}
			} else {
				return false;	
			}
			for (var i=0;i<dataProvider.totalRows;i++) {
				if (title && title != "") {
					ii = i+1;
				} else {
					ii = i;
				}
				index = dataProvider.registros[i][1];
				valor = dataProvider.registros[i][0];
				if (default_value != "") {
					if ((valor.toLowerCase() == default_value.toLowerCase()) || (index.toLowerCase() == default_value.toLowerCase())) {
						sel_index = ii;
					}
				}
				if (valor.substring(0,1)=='#') {
					cb.options[ii] = new Option(valor.substring(1,valor.length),index);
					cb.options[ii].className = 'grupo';
				} else {
					cb.options[ii] = new Option(valor,index);
				}
			}
			
			if (sel_index != false) {
				//alert('sel_index: '+sel_index+'  default: '+default_value);
				cb.selectedIndex = sel_index;
			}
			next_ajax_combo();
		}
	}
	xmlhttp.send(null);
}
function reset_combo(cb_id) {
	if (!cb_id) {
		return false;	
	}
	cb_id.length = 0;
	cb_id.options[0] = new Option('-------','');
}

function deleteVeiculo (veiculo_id) {
	  hr_deleteVeiculo = false;
      if (window.XMLHttpRequest) { // Mozilla, Safari,...
         hr_deleteVeiculo = new XMLHttpRequest();
         if (hr_deleteVeiculo.overrideMimeType) {
            hr_deleteVeiculo.overrideMimeType('text/xml');
         }
      } else if (window.ActiveXObject) { // IE
         try {
            hr_deleteVeiculo = new ActiveXObject("Msxml2.XMLHTTP");
         } catch (e) {
            try {
               hr_deleteVeiculo = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {}
         }
      }
      if (!hr_deleteVeiculo) {
         alert('Cannot create XMLHTTP instance');
         return false;
      }
	  
	  var str_url = ajax_gw + "?acao=deleteVeiculo&id=" + veiculo_id;
	  
	  hr_deleteVeiculo.open("GET", str_url, true);
	  hr_deleteVeiculo.onreadystatechange = function() {
		if (hr_deleteVeiculo.readyState==4)  {
			if (hr_deleteVeiculo.responseText == "SUCCESS") {
				alert('VEÍCULO REMOVIDO COM SUCESSO!');	
				deleteVeiculo_onLoad(veiculo_id);
				return true;
			} else {
				alert("Erro: "+hr_deleteVeiculo.responseText);
				return false;
			}
		}
	  }
	  hr_deleteVeiculo.send(null);
}

function deleteImage(veiculo_id, field_image) {
	  hr_deleteImage = false;
      if (window.XMLHttpRequest) { // Mozilla, Safari,...
         hr_deleteImage = new XMLHttpRequest();
         if (hr_deleteImage.overrideMimeType) {
            hr_deleteImage.overrideMimeType('text/xml');
         }
      } else if (window.ActiveXObject) { // IE
         try {
            hr_deleteImage = new ActiveXObject("Msxml2.XMLHTTP");
         } catch (e) {
            try {
               hr_deleteImage = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {}
         }
      }
      if (!hr_deleteImage) {
         alert('Cannot create XMLHTTP instance');
         return false;
      }
	  var str_url = ajax_gw + "?acao=deleteImage&id=" + veiculo_id + "&field=" + field_image;
	  //alert("deleteImage URL: "+str_url);
	  hr_deleteImage.open("GET", str_url, true);
	  hr_deleteImage.onreadystatechange = function() {
		if (hr_deleteImage.readyState==4)  {
			if (hr_deleteImage.responseText == "SUCCESS") {
				alert('IMAGEM REMOVIDA COM SUCESSO!');	
				deleteImage_onLoad(veiculo_id);
				return true;
			} else {
				alert("Erro: "+hr_deleteImage.responseText);
				return false;
			}
		}
	  }
	  hr_deleteImage.send(null);
}
function ajaxLogin(x){
	var cPost='';
	//document.getElementById('CadastroInfo').style.display='none';
	if (x==1) {
		getCadastroInfo();
		return true;
		usuario=senha=1;
	} else {
		usuario=document.getElementById('REV_USUARIO').value;
		senha=document.getElementById('REV_SENHA').value;
		revenda = document.getElementById('REVENDA').value;
	}
	

/*
	if (usuario==''){
		alert('Favor preencher o campo Login!');
		document.getElementById('REV_USUARIO').focus();
		return false;
	}
	if (senha==''){
		alert('Favor preencher o campo Senha!');
		document.getElementById('REV_SENHA').focus();
		return false;
	}
*/
	document.getElementById('resposta').innerHTML="Aguarde...";
	//url='getCadastroInfo.php?usuario='+usuario+'&senha='+senha;
	url='ajax/gw.cadastro.ajax.php?acao=login';
	cPost='usuario='+usuario+'&senha='+senha+'&tipo=1';
	xmlhttp.open("POST",url,true);
	xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xmlhttp.onreadystatechange=function() {
        if (xmlhttp.readyState==4){
			retorno=unescape(xmlhttp.responseText);
			local=new Function("return "+retorno)();

			//document.getElementById('resposta').innerHTML=retorno;

			//alert("Status: "+local.status+' - '+local.status_text);
			//document.getElementById('resposta').innerHTML=local.status_text;

			if (local.status==0) {
				document.getElementById('resposta').innerHTML='';
				alert(local.status_text);
				return false;
			} else {
				document.getElementById('resposta').innerHTML=local.status_text;
				document.location='http://www.autolondrina.com.br/webos/extranet/';
				return true;
			}

			//document.getElementById('CadastroInfo').style.display='list-item';
			//document.getElementById('CadastroInfoNovo').style.display='none';
			//document.getElementById('CadastroInfoSenha').style.display='none';
			//CadastroInfo=local.CadastroInfo;
			//getCadastroInfo();
		}
	}
    xmlhttp.send(cPost);
}
function ajaxLoginPart(x){
	var cPost='';
	//document.getElementById('CadastroInfo').style.display='none';
	if (x==1) {
		getCadastroInfo();
		return true;
		usuario=senha=1;
	} else {
		usuario=document.getElementById('PAR_USUARIO').value;
		senha=document.getElementById('PAR_SENHA').value;
	}
	if (usuario==''){
		alert('Favor preencher o campo Login!');
		document.getElementById('PAR_USUARIO').focus();
		return false;
	}
	if (senha==''){
		alert('Favor preencher o campo Senha!');
		document.getElementById('PAR_SENHA').focus();
		return false;
	}
	document.getElementById('respostaP').innerHTML="Aguarde...";
	//url='getCadastroInfo.php?usuario='+usuario+'&senha='+senha;
	url='ajax/gw.cadastro.ajax.php?acao=login';
	cPost='usuario='+usuario+'&senha='+senha+'&tipo=3';
	xmlhttp.open("POST",url,true);
	xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xmlhttp.onreadystatechange=function() {
        if (xmlhttp.readyState==4){
			retorno=unescape(xmlhttp.responseText);
			local=new Function("return "+retorno)();
 			if (local.status==0) {
				document.getElementById('respostaP').innerHTML='';
				alert(local.status_text);
				return false;
			} else {
				document.getElementById('respostaP').innerHTML=local.status_text;
				document.location='#conteudo';
				//document.location='/webos/extranet/';
				return true;
			}
			//document.getElementById('CadastroInfo').style.display='list-item';
			//document.getElementById('CadastroInfoNovo').style.display='none';
			//document.getElementById('CadastroInfoSenha').style.display='none';
			//CadastroInfo=local.CadastroInfo;
			//getCadastroInfo();
		}
	}
    xmlhttp.send(cPost);
}

//==============================================================
   http_request = false;
   gateway_url = "ajax/gw.veiculos.ajax.php";
   function makeRequest(action, method, parameters, phpfile) {
	  //alert('makeRequest('+action+','+method+', '+parameters+')');
      http_request = false;
      if (window.XMLHttpRequest) { // Mozilla, Safari,...
         http_request = new XMLHttpRequest();
         if (http_request.overrideMimeType) {
            http_request.overrideMimeType('text/xml');
         }
      } else if (window.ActiveXObject) { // IE
         try {
            http_request = new ActiveXObject("Msxml2.XMLHTTP");
         } catch (e) {
            try {
               http_request = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {}
         }
      }
      if (!http_request) {
         alert('Cannot create XMLHTTP instance');
         return false;
      }
	  //alert("parameters: "+parameters);
	  qs = "?acao="+action;
	  if (method == 'GET') {
		  qs += parameters;
	  }
	  if (!phpfile || phpfile == '') {
		  phpfile = gateway_url;
	  }

      http_request.open(method, phpfile + qs, true);
	  http_request.onreadystatechange = function() {
		   if (http_request.readyState==4) {
			   	fonload = eval(action+"_onLoad");
				fonload(unescape(http_request.responseText));
				return true;
		   }
	  }
	  if (method == "POST") {
		http_request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	  	http_request.send(parameters);
	  } else {
		  http_request.send(null);
	  }
   }
   
   function SubmitForm(form, action, method, phpfile) {
	   if (!phpfile) phpfile='';
	  //alert('get('+obj+', '+fonload+')');
      var getstr = "&";
      for (i=0; i<form.elements.length; i++) {
		 	var type = form.elements[i].type;
			if (type) {
				var name = form.elements[i].name.replace('!','');
				//if (type != "checkbox") alert('type: '+type);
				
				if (type == "text" || type == "hidden" || type == "password" || type == "textarea") {
				   getstr += name + "=" + form.elements[i].value + "&";
				}
				
				if (type == "checkbox") {
				   if (form.elements[i].checked) {
					  getstr += name + "=" + form.elements[i].value + "&";
				   }
				}
				
				if (type == "radio") {
				   if (form.elements[i].checked) {
					  getstr += name + "=" + form.elements[i].value + "&";
				   }
				}
			  
				if (type == "select" || type == "select-one") {
					getstr += name + "=" + form.elements[i].options[form.elements[i].selectedIndex].value + "&";
				}
			}
         
      }
	  //alert(action+', '+ method+', '+ getstr);
      makeRequest(action, method, getstr, phpfile);
   }
//==============================================================
function ajaxLembraSenha(){
	var cPost='';
	document.getElementById('statussenha').innerHTML="Aguarde...";
	usuario	= document.getElementById('EMAIL_SENHA').value;
	if (usuario==''){
		alert('Favor preencher o campo email!');
		document.getElementById('statussenha').innerHTML="";
		document.getElementById('EMAIL_SENHA').focus();
		return false;	
	}
	url='ajax/gw.cadastro.ajax.php?acao=lembrete';
	cPost='usuario='+usuario;
	xmlhttp.open("POST",url,true);
	xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xmlhttp.onreadystatechange=function() {
        if (xmlhttp.readyState==4){
			retorno=unescape(xmlhttp.responseText);
			local=new Function("return "+retorno)();
			if (local.status==0) {
				alert(local.status_text);
				document.getElementById('statussenha').innerHTML="";
				return false;
			}
			alert(local.status_text);
			document.getElementById('statussenha').innerHTML="";
			document.getElementById('EMAIL_SENHA').value='';
			Expande('box_lembra_senha');
			return true;
		}
	}
    xmlhttp.send(cPost);
}
