
	/**
	 **
	 *
	 * Inicialização do Script
	 *
	 **
	 */
	var xml = xmlRequest();
	var xml2 = xmlRequest();
	var tabela = new Tabela;
	xml.open("GET","../xml/jsonPrecos.php",true);
	xml.send(null);
	xml.onreadystatechange = function() {
		if (xml.readyState == 4 && xml.status == 200) {
			window.jsonPrecos = eval("("+xml.responseText+")");
		}
	}

	xml2.open("GET","../xml/jsonFretes.php",true);
	xml2.send(null);
	xml2.onreadystatechange = function() {
		if (xml2.readyState == 4 && xml2.status == 200) {
			window.jsonFretes = eval("("+xml2.responseText+")");
		}
	}


	/**
	 **
	 *
	 * Funções do script
	 *
	 **
	 */
	
	/**
	 * Behavior do select de estado
	 */
	
	function trocaEstado() {
		if (document.getElementById('estado')) {
			document.getElementById('estado').onchange = function() {
				calculaPrecos();
			}
		}
	}
	
	/**
	 * Monta todos os onclicks e onkeyups ;)
	 */
	function geraBotoes() {
		if (!document.getElementById("table"))
			return false;
		var inputs = document.getElementById('table').getElementsByTagName('input');
		for (i=0; i<inputs.length; i++) {
			
			var input = inputs[i];
			
			// Caso seja uma checkbox
			if (input.type == "checkbox") {
				input.onclick = function() {
					var idAtual = parseInt(this.id.replace('check',''));
					var textField = document.getElementById('quantidade'+idAtual);
					if (this.checked) {
						textField.disabled = false;
						textField.style.backgroundColor = "#FFF";
						if (textField.value == "")
							textField.value = "1";
					} else {
						textField.disabled = true;
						textField.style.backgroundColor = "#CCC";
					}
					calculaPrecos();
				}
			}
			
			// Caso seja um text field
			else if (input.type == "text") {
				input.onkeyup = function(e) {
					calculaPrecos();
				}
			}
		}
	}
	
	/**
	 * Calcula o total de preços
	 */
	function calculaPrecos() {
		tabela.limpar();
		var inputs = document.getElementById('table').getElementsByTagName('input');
		for (i=0; i<inputs.length; i++) {
			var input = inputs[i];
			if (input.type == "checkbox") {
				if (input.checked) {
					id = parseInt(input.id.replace('check',''))

					var prodNome = window.jsonPrecos[id].nome;
					var prodQtd = document.getElementById('quantidade'+id).value;
					var prodVal = window.jsonPrecos[id].preco;
					
					tabela.adicionarProduto(prodNome,prodQtd,prodVal);
				}
			}
		}
		tabela.imprimir();
	}
	
	/**
	 **
	 *
	 * Objeto tabela
	 *
	 **
	 **
	 */
	 
	function Tabela() {
		this.precos = document.createElement('tbody');
		this.total = 0;
	}

	Tabela.prototype.limpar = function() {
		this.table = document.getElementById('pedido');

		tbody = this.table.getElementsByTagName('tbody')[0];
		tfoot = this.table.getElementsByTagName('tfoot')[0];
		
		if (tbody)
			this.table.removeChild(tbody);
		if (tfoot)
			this.table.removeChild(tfoot);
		
		this.precos = document.createElement('tbody');
		
		this.totalCarrinho = 0;
	}
	
	Tabela.prototype.adicionarProduto = function(nome,quantidade,valor) {
		if (!this.table)
			this.table = document.getElementById('pedido');

		var preco = document.createElement("tr");
		
		var td1 = document.createElement("td");
		var td2 = document.createElement("td");
		var td3 = document.createElement("td");
		td1.innerHTML = nome;
		
		var quantidade = parseInt(quantidade);
		if (isNaN(quantidade))
			quantidade = 0;
		td2.innerHTML = quantidade;
		
		var total = parseFloat(parseFloat(quantidade) * parseFloat(valor));
		this.totalCarrinho += total;
		total = total.toFixed(2);
				
		td3.innerHTML = "R$"+total;
		
		preco.appendChild(td1);
		preco.appendChild(td2);
		preco.appendChild(td3);
		
		this.precos.appendChild(preco);
	}
	
	Tabela.prototype.imprimir = function() {
		var estado = document.getElementById('estado');
		if (estado.value == "na") {
			alert('Você deve selecionar um estado para que o frete seja calculado corretamente!');
			return false;
		}
		
		var frete = parseInt(eval("window.jsonFretes."+estado.value));
		
		var freteTr = document.createElement("tr");
		var freteTd1 = document.createElement("td");
		var freteTd2 = document.createElement("td");
		var freteTd3 = document.createElement("td");
		
		freteTd1.innerHTML = "Frete";
		freteTd2.innerHTML = "&nbsp;";
		freteTd3.innerHTML = "R$"+frete.toFixed(2);
		
		freteTr.appendChild(freteTd1);
		freteTr.appendChild(freteTd2);
		freteTr.appendChild(freteTd3);
		
		var totalTr = document.createElement("tr");
		var totalTd1 = document.createElement("td");
		var totalTd2 = document.createElement("td");
		var totalTd3 = document.createElement("td");
		
		this.totalCarrinho += frete;
		
		totalTd1.innerHTML = "<strong>Total</strong>";
		totalTd2.innerHTML = "&nbsp;";
		totalTd3.innerHTML = "<strong>R$"+this.totalCarrinho.toFixed(2)+"</strong>";
		
		totalTr.appendChild(totalTd1);
		totalTr.appendChild(totalTd2);
		totalTr.appendChild(totalTd3);
		
		this.precos.appendChild(freteTr);
		var totalFoot = document.createElement('tfoot');
		totalFoot.appendChild(totalTr);

		this.table.appendChild(this.precos);
		this.table.appendChild(totalFoot);

	}

	 
	/**
	 **
	 *
	 * Funções auxiliares
	 *
	 **
	 **
	 */

	/**
	 * Função que insere os flashs
	 */
	function flash(arquivo, id, largura, altura) {
		var id = document.getElementById(id);
		if(id != null){
			var so = new SWFObject(arquivo, id, largura, altura, "7", "#FFFFFF", true, "high", "http://www.torcello.com.br");
			so.addParam("wmode", "transparent");
			so.write(id);
		}
	}
	
	/**
	 * Função que chama os flashs da página
	 */
	function chamaFlash() {
		flash('../flash/topo.swf', 'topo', 774, 322);
		flash('../flash/menu.swf', 'flashmenu', 100, 255);
	}
	
	/**
	 * Ajax
	 */
	function xmlRequest() {
		if (window.XMLHttpRequest) {
			return new XMLHttpRequest();
		} else if (window.ActiveXObject) {
			return new ActiveXObject("Microsoft.XMLHTTP");
		} else {
			return new ActiveXObject("Msxml2.XMLHTTP");
		}
	}
	
	function validaForm() {
		if (document.getElementById('formPedido')) {
			document.getElementById('formPedido').onsubmit = function() {
				var f = document.formPedido;
				if (f.nome.value == "" ||
					f.cidade.value == "" ||
					f.endereco.value == "" ||
					f.cpfCnpj.value == "" ||
					f.fone.value == "" ||
					f.email.value == "" ||
					f.cep.value == "" ||
					f.estado.value == "") {
					alert("Você deve preencher seus dados básicos!");
					return false;
				}
			}
		}
	}
	
	/**
	 * OnLoad da página
	 */
	window.onload = function() {
		chamaFlash();
		geraBotoes();
		trocaEstado();
		validaForm();
	}