// JavaScript Document
var ajax_gw = 'ajax/gw.loja.ajax.php';
atual=0;fila=[];ifila=0;
var xmlhttp2;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;}}}
try{xmlhttp2=new XMLHttpRequest();}catch(ee){try{xmlhttp2=new ActiveXObject("Msxml2.XMLHTTP");}catch(e){try{xmlhttp2=new ActiveXObject("Microsoft.XMLHTTP");}catch(E){xmlhttp2=false;}}}
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();
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 ajaxHTML(id,url) {
	//alert("ajaxHTML("+id+","+url+")");
    //document.getElementById(id).innerHTML="Carregando...";
	fila[fila.length]=[id,url];
    if((ifila+1)==fila.length)ajaxRun();
}
/*
FUNÇÕES ADICIONAIS (FATUM)
por RICHARD
*/
//-------------------------------------------------------------------------------------
function loader_show(str_msg) {
	
	if (!str_msg)
		str_msg = "Aguarde...";
	
	loaderObj = document.getElementById('loader');
	loaderObj.style.display = 'block';
	
	document.getElementById('loader_txt').innerHTML = str_msg;
	
	centerLoader(loader);
}

function loader_hide() {
	
	loaderObj = document.getElementById('loader');
	loaderObj.style.display = 'none';
	
}
//-------------------------------------------------------------------------------------
function centerLoader(domObj) {
	width  = domObj.offsetWidth
	height = domObj.offsetHeight;
	viewPort = getViewPort();
	scrollObj = getScrollXY();
	domObj.style.left = ((viewPort.width/2)-(width/2)+scrollObj[0])+'px';
	domObj.style.top = (scrollObj[1])+'px';
}

function getScrollXY() {
  var scrOfX = 0, scrOfY = 0;
  if( typeof( window.pageYOffset ) == 'number' ) {
    //Netscape compliant
    scrOfY = window.pageYOffset;
    scrOfX = window.pageXOffset;
  } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
    //DOM compliant
    scrOfY = document.body.scrollTop;
    scrOfX = document.body.scrollLeft;
  } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
    //IE6 standards compliant mode
    scrOfY = document.documentElement.scrollTop;
    scrOfX = document.documentElement.scrollLeft;
  }
  return [ scrOfX, scrOfY ];
}

function getViewPort () {
	var viewportwidth;
    var viewportheight;
	 if (typeof window.innerWidth != 'undefined') {
	      viewportwidth = window.innerWidth,
	      viewportheight = window.innerHeight
	 } else if (typeof document.documentElement != 'undefined'
	     && typeof document.documentElement.clientWidth !=
	     'undefined' && document.documentElement.clientWidth != 0) {
	       viewportwidth = document.documentElement.clientWidth,
	       viewportheight = document.documentElement.clientHeight
	 } else {
	       viewportwidth = document.getElementsByTagName('body')[0].clientWidth,
	       viewportheight = document.getElementsByTagName('body')[0].clientHeight
	 }
	 viewPort = new Object();
	 viewPort.width  = viewportwidth;
	 viewPort.height = viewportheight;
	 return viewPort;
}

function blocodireito_refresh() {
	var dt = new Date();
	ajaxHTML('bloco_direito','direito.index.inc.php?'+encodeURI(Math.random() + "_" + dt.getTime()));
}

var conteudo_direito = false;
var conteudo_direito = "detalhe";
var categoria_ativa = false;
function abrirConteudoExt(link_externo) {
	ajaxHTML('conteudo_interno', link_externo);
	if (conteudo_direito == "detalhe") {
//		ajaxHTML('bloco_direito','direito.index.inc.php');
		blocodireito_refresh();
		conteudo_direito = "detalhe";
	}
}
function abrirConteudo(id) {
	ajaxHTML('conteudo_interno','conteudo.loja.inc.php?cat='+id);
	if (conteudo_direito == "detalhe") {
//		ajaxHTML('bloco_direito','direito.index.inc.php');
		blocodireito_refresh();
		conteudo_direito = "detalhe";
	}
}
function abrirProduto(prodid) {
//	ajaxHTML('bloco_direito','direito.index.inc.php');
	blocodireito_refresh();
	ajaxHTML('conteudo_interno','produto.show.inc.php?id='+prodid);
	conteudo_direito = "detalhe";
}
function Click_MenuCategoria(catid) {
	
/*	  var obj=document.getElementsByName("menu_scateg");
	  for (i=0;i<obj.length;i++)
		{
		obj[i].style.display='none';
		}
	 document.getElementById('menuscat_'+catid).style.display = "block";		
*/
var c=1;
for (c=1;c<=200;c++) { // TESTE VER MELHOR OPÇÃO
	if (document.getElementById('menuscat_'+c)) {
			document.getElementById('menuscat_'+c).style.display = "none";
	}

}
	if (document.getElementById('menuscat_'+catid)) {
		document.getElementById('menuscat_'+catid).style.display = "block";
	}
/*	if (document.getElementById('menuscat_'+catid)) {
		if (document.getElementById('menuscat_'+catid).style.display == "block") {
			document.getElementById('menuscat_'+catid).style.display = "none";
		} else {
			document.getElementById('menuscat_'+catid).style.display = "block";
		}
	}
*/	abrirCategoria(catid);
}
function abrirCategoria(catid) {
	ajaxHTML('conteudo_interno','produtos.lista.inc.php?pcat='+catid);
	if (conteudo_direito == "detalhe") {
//		ajaxHTML('bloco_direito','direito.index.inc.php');
		blocodireito_refresh();
		conteudo_direito = "detalhe";
	}
}
function abrirSubcategoria(catid,scatid) {
	ajaxHTML('conteudo_interno','produtos.lista.inc.php?pcat='+catid+'&scat='+scatid);
	if (conteudo_direito == "detalhe") {
//		ajaxHTML('bloco_direito','direito.index.inc.php');
		blocodireito_refresh();
		conteudo_direito = "detalhe";
	}
}
function cartstatus_refresh() {
	ajaxHTML('bloco_cart_status','cart.status.inc.php');
}
/*
FIM DE FUNÇÕES ADICIONAIS (FATUM)
*/
function writeDIV(id,conteudo) {
	document.getElementById(id).innerHTML=conteudo;
}
function ajaxRun(){
	loader_show();
    xmlhttp2.open("GET",fila[ifila][1],true);
    xmlhttp2.onreadystatechange=function() {
	if (xmlhttp2.readyState==4){
            //retorno=unescape(xmlhttp2.responseText.replace(/\+/g," "))
			retorno=unescape(xmlhttp2.responseText);
            document.getElementById(fila[ifila][0]).innerHTML=retorno;
            ifila++;
            if(ifila<fila.length)setTimeout("ajaxRun()",20)
			loader_hide();
        }
    }
	xmlhttp2.send(null);
}

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();	
}
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) {
	//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.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 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];
		}
	}
	//alert('str_url: '+str_url);
	var sel_index = false;
	//msg_carregando.innerHTML='Carregando...';
	xmlhttp.open("GET", str_url, true);
	xmlhttp.onreadystatechange=function() {
        if (xmlhttp.readyState==4){
			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 < 1) {
				reset_combo(cb);
				return;
			}
			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 || cb_id == "") {
		return false;	
	}
	var cb = document.getElementById(cb_id);
	cb.length = 0;
	cb.options[0] = new Option('-------','');
}
//==============================================================
   http_request = false;
   gateway_url = ajax_gw;
   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);
	  loader_show();
	  http_request.onreadystatechange = function() {
		   if (http_request.readyState==4) {
			     loader_hide();
			   	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 ajaxLogoff(){
	url=ajax_gw+'?acao=logoff';
	xmlhttp.open("GET",url,true);
    xmlhttp.onreadystatechange=function() {
        if (xmlhttp.readyState==4){
			retorno=new Function("return "+xmlhttp.responseText)();
			if (retorno.status == "success") {
				alert('Usuário Desconectado !');
				MM_goToURL("window","index.php");
				return true;
			}
		}
	}
    xmlhttp.send(null);
}
//==============================================================
function cart_delItem(itemid) {
	if (!xmlhttp2) { alert('ERRO: Componente nao iniciou !'); return false; }
	document.getElementById('cart_status').style.display = "block";
	writeDIV('cart_status','Removendo o produto. Aguarde...');
	url =  ajax_gw+"?acao=cart_del&PRODUTO="+itemid;
	xmlhttp2.open("GET",url,true);
	xmlhttp2.onreadystatechange=function() {
		if (xmlhttp2.readyState==4) {
			document.getElementById('cart_status').style.display = "none";
			retorno=new Function("return "+xmlhttp2.responseText)();
			if (retorno.status == "success") {
				ajaxHTML('conteudo_interno','cart.inc.php');
				cartstatus_refresh();
				return false;
			} else {
				alert(retorno.msg);
				return false;
			}
		}
	}
	xmlhttp2.send(null);
}
function cart_qtde(itemid, qtde) {
	if (!xmlhttp2) { alert('ERRO: Componente nao iniciou !'); return false; }
	document.getElementById('cart_status').style.display = "block";
	writeDIV('cart_status','Atualizando a quantidade. Aguarde...');
	url = ajax_gw+"?acao=cart_qtde&PRODUTO="+itemid+"&QTDE="+qtde;
	xmlhttp2.open("GET",url,true);
	xmlhttp2.onreadystatechange=function() {
		if (xmlhttp2.readyState==4) {
			document.getElementById('cart_status').style.display = "none";
			retorno=new Function("return "+xmlhttp2.responseText)();
			if (retorno.status == "success") {
				ajaxHTML('conteudo_interno','cart.inc.php');
				cartstatus_refresh();
				return false;
			} else {
				alert(retorno.msg);
				return false;
			}
		}
	}
	xmlhttp2.send(null);
}

