//
function getHTTPObject() 
{
		if(typeof(XMLHttpRequest)!='undefined')
		{
			return new XMLHttpRequest();
		}
        var axO=['Microsoft.XMLHTTP','Msxml2.XMLHTTP','Msxml2.XMLHTTP.6.0','Msxml2.XMLHTTP.4.0','Msxml2.XMLHTTP.3.0'];
        for(var i=0;i<axO.length;i++)
		{
			try
				{ 
					return new ActiveXObject(axO[i]);
				}
			catch(e)
				{
				} 
		}
		return null;
}

//Declara Variável
//var http;

//*** Código base do Ajax
function abreAjax(url, div , method)
{
	var http;	
	//Variável
	http = getHTTPObject();
	
	//Tratamento de URL
	url = antiCacheRand(url);
	
	//Variáveis de Ajuda para envio GET ou POST
	var sendvars = null;	
	
	// se conectar, executa...
	http.onreadystatechange = function()
	{
		// chama a função que colocará o conteúdo
		conteudoPagina(http , div);
	};
	
	//Verifica se Existe Parâmetros
	//True = POST
	//False = GET
	
	
	
	if (method == "GET") {
		method = 'GET';
		sendvars = null;
	}
	else
	{
		method = 'POST';
		sendvars = url;
	}
	
	http.open(method, url, true);
	
	//Limpeza do Cash ,  Header para MEthod POST
	http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=iso-8859-1");
	http.setRequestHeader("Cache-Control", "no-store, no-cache, must-revalidate");
	http.setRequestHeader("Cache-Control", "post-check=0, pre-check=0");
	http.setRequestHeader("Pragma", "no-cache");
	
	http.send(sendvars);
	
}

//*** função para exibição da página
function conteudoPagina(http, div)
{

	// se estiver carregando...
	if(http.readyState == 1)
	{
			// Quando estiver carregando, exibe: carregando...
			//document.getElementById(div).innerHTML = "<center><font color='red'>Carregando...</font></center>";
			document.getElementById(div).innerHTML = "<center><table><tr><td valign='middle'><img src=imagens/ajax-loader.gif></td><td valign='middle'><span style='color:blue;font-size:11px;'>Carregando ...</span></td></tr></table></center>";
			//addItem(document.form.cidades,"Carregando...","",false,0)
			//document.getElementById(div).options[0] = new Option("Carregando...","");
	}

	// quando tiver terminado de carregar
	if (http.readyState == 4)
	{
			// checagem de status
			if (http.status == 200)
			{

				// Aqui é onde se mostra a página carregada
				// Conteúdo da página chamada
				var resultado = http.responseText;

				// Resolve o problema dos acentos
				resultado = resultado.replace(/\+/g," ");
				resultado = unescape(resultado);
				extraiScript(resultado);
				// Coloca na página atual o conteúdo da página requisitada pelo AJAX
				document.getElementById(div).innerHTML = resultado;
			}

			// se checagem de status falhar...
			else
			{
				//alert('ERRO!' + httpStatus(http.status));//Descrição do Erro
				document.getElementById(div).innerHTML = 'ERRO!' + httpStatus(http.status);
			}
	}

}

/////////////////////////////////////////////////////////////////////////////////////////////
//Função Padrão de Chamada do AJAX
function fnPadrao(id,url,div,method){
	//Mostra DIV Caso Esteja Oculta
	try
	{
		document.getElementById(id).style.display = '';
	}
	catch(e)
	{
		//ERRO
	}
	//Chama Ajax	
	setTimeout("abreAjax('" + url + "','" + div + "' , '" + method + "')",100);
}

/////////////////////////////////////////////////////////////////////////////////////////////
//Função Que Limpa Conteúdo da DIV
function fnLimpa_Div(id)
{
	//Limpa Conteúdo da Div
	document.getElementById(id).innerHTML = "";
	//Esconde a Div
	document.getElementById(id).style.display = 'none';
}

/////////////////////////////////////////////////////////////////////////////////////////////
//Função Que Verifica Descrição do Erro
function httpStatus(erro){ //retorna o texto do erro http
        switch(erro){
            case 0: return "Erro Desconhecido";
            case 400: return "400: Solicitação incompreensível"; break;
            case 403: return "403: Você Não tem permissão para acessar essa página"; break;
			case 404: return "404: Não foi encontrada a URL solicitada"; break;
            case 405: return "405: O servidor não suporta o método solicitado"; break;
            case 500: return "500: Erro desconhecido de natureza do servidor"; break;
            case 503: return "503: Capacidade máxima do servidor alcançada"; break;
            default: return "Erro: " + erro + ". Mais informações em http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html"; break;
        }
    }
	
/////////////////////////////////////////////////////////////////////////////////////////////
//Função Que Permite Uso de JS no AJAX
function extraiScript(texto){
    // Início
    var inicio = 0;
    // loop enquanto achar um script
    while (inicio!=-1){
        // procura uma tag de script
        inicio = texto.indexOf('<script', inicio);
        // se encontrar
        if (inicio >=0){
            // define o inicio para depois do fechamento dessa tag
            inicio = texto.indexOf('>', inicio) + 1;
            // procura o final do script
            var fim = texto.indexOf('</script>', inicio);
            // extrai apenas o script
            codigo = texto.substring(inicio,fim);
            // executa o script
            //eval(codigo);
            novo = document.createElement("script")
            novo.text = codigo;
            document.body.appendChild(novo);
        }
    }
}	

/////////////////////////////////////////////////////////////////////////////////////////////
//Função Que Evita Parâmetros Repetidos no CACHÊ
function antiCacheRand(url)
{
	var data = new Date();
	//Verifica se o Link(URL) possui parâmetros
	if(url.indexOf("?")>=0)
	{// já tem parametros
		return url + "&" + encodeURI(Math.random() + "_" + data.getTime());
	}
	else
	{ 
		return url + "?" + encodeURI(Math.random() + "_" + data.getTime());
	}
}
	
/////////////////////////////////////////////////////////////////////////////////////////////	
//Função Para Inserção de Varios Options em um Select
	function addItem(obj,strText,strValue,blSel,intPos)
	{
    	var newOpt,i,ArTemp,selIndex; 
		selIndex = (blSel)?intPos:obj.selectedIndex; 
		newOpt = new Option(strText,strValue); 
		Len = obj.options.length+1 
		if (intPos > Len) return 
		obj.options.length = Len 
		if (intPos != Len)
		{ 
        	ArTemp = new Array(); 
			for(i=intPos;i<obj.options.length-1;i++) 
            	ArTemp[i] = Array(obj.options[i].text,obj.options[i].value); 
			for(i=intPos+1;i<Len;i++) 
				obj.options[i] = new Option(ArTemp[i-1][0],ArTemp[i-1][1]); 
		} 
		obj.options[intPos] = newOpt; 
		if (selIndex > intPos) 
        	obj.selectedIndex = selIndex+1; 
		else if (selIndex == intPos)  
        	obj.selectedIndex = intPos; 
	}
	
var xmlHttp;

function fnMuda_Quantidade(strQuantidade,codprod,valorunit,intJ,qtdeantiga)
{
	xmlHttp=GetXmlHttpObject()
	if (xmlHttp==null)
		{
			alert ("Este browser não suporta HTTP Request")
			return
		}
	var url="atualizaQuantidade.asp"
	url=url+"?quantidade=" + document.getElementById(strQuantidade).value + "&codprod=" + codprod
	
	if(document.getElementById("quantidadeantiga" + intJ).value != "")
	{
		qtdeantiga = parseFloat(document.getElementById("quantidadeantiga" + intJ).value);
		document.getElementById("quantidadeantiga" + intJ).value = document.getElementById(strQuantidade).value;
	}
	else
	{
		document.getElementById("quantidadeantiga" + intJ).value = document.getElementById(strQuantidade).value;
	}
	
	if(parseFloat(document.getElementById(strQuantidade).value) > qtdeantiga)
	{
		var valortotal = parseFloat(document.getElementById(strQuantidade).value) * parseFloat(valorunit);
		document.getElementById("valortotal"+intJ).innerHTML=fnFormata_Moeda(valortotal);
	}
	else
	{
		var valortotal = (parseFloat(qtdeantiga) - parseFloat(document.getElementById(strQuantidade).value)) * parseFloat(valorunit);
		document.getElementById("valortotal"+intJ).innerHTML=fnFormata_Moeda(parseFloat(document.getElementById(strQuantidade).value) * parseFloat(valorunit));
	}
	
	var aux = document.getElementById("subtotal").value.replace("R$ ","");
	if(parseFloat(document.getElementById(strQuantidade).value) > qtdeantiga)
	{
		var subtotal = (parseFloat(aux.replace(",",".")) - (parseInt(qtdeantiga) * parseFloat(valorunit))) + valortotal;
	}
	else
	{
		var subtotal = (parseFloat(aux.replace(",","."))) - valortotal;
	}
	
	//alert("Qtde Atual: " + document.getElementById(strQuantidade).value);
	//alert("Qtde Antiga: " + qtdeantiga);
	//alert("ValorUnit: " + valorunit);
	//alert("ValorTotal: " + valortotal);
	//alert("Subtotal: " + subtotal);
	document.getElementById("subtotal").value = fnFormata_Moeda(subtotal);
	
	xmlHttp.onreadystatechange=stateChanged
	xmlHttp.open("GET",url,true)
	xmlHttp.send(null)
}

function stateChanged()
{
	if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
		{
			//document.location.reload();
			//document.getElementById("valortotal").innerHTML=
		}
}

function GetXmlHttpObject()
{
	var objXMLHttp=null
	if (window.XMLHttpRequest)
		{
			objXMLHttp=new XMLHttpRequest()
		}
	else if (window.ActiveXObject)
		{
			objXMLHttp=new ActiveXObject("Microsoft.XMLHTTP")
		}
	return objXMLHttp
}

/***********************************************************************
FUNCAO QUE COLOCA NO FORMATO DE MOEDA
-------------------------------------------------------------------
Função: fn_formata_moeda
Processamento: Recebe um valor numérico (1.00) e coloca no
formato moeda (R$ 1,00)

Responsavél: Maikel Finck <maikel@logicadigital.com.br>
Data: 17.Ago.2006
************************************************************************/
function fnFormata_Moeda ( num )
{
	// verifica se a string e um 'tipo nao numerico'
	if(isNaN(num))
		// zera a string nesse caso
		num = "0";
	// contas
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents<10)
		cents = "0" + cents;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
		num = num.substring(0,num.length-(4*i+3))+'.'+
	num.substring(num.length-(4*i+3));
	// finaliza o codigo estranho e retorna a string em formato real
	return (((sign)?'':'-') + 'R$ ' + num + ',' + cents);
}	

function fnCalculaFrete(url)
{
	xmlHttp=GetXmlHttpObject()
	if (xmlHttp==null)
		{
			alert ("Este browser não suporta HTTP Request")
			return
		}
	
	xmlHttp.onreadystatechange=stateChanged2
	xmlHttp.open("GET",url,true)
	xmlHttp.send(null)
}

function stateChanged2()
{
	if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
		{
			//document.location.reload();
			//document.getElementById("divTarifa").innerHTML=xmlHttp.responseText
		}
}