//===============================================================================
//= FORMULÁRIOS E BUSCAS ========================================================
//===============================================================================
var tipo = 0;

function FaleConosco() {
	tipo = 1;
	document.form1.action = "mail.asp";
	document.form1.method = "post";
}

function Busca() {
	tipo = 2;
	document.form1.action = "";
	document.form1.method = "get";
}

function BuscaInt() {
	tipo = 3;
	document.form1.action = "";
	document.form1.method = "get";
}

function Carrinho() {
	tipo = 4;
	document.form1.action = "../orcamento/orcamento-upd.asp";
	document.form1.method = "post";
}

function EnviaOrc() {
	tipo = 5;
	document.form1.action = "mail.asp";
	document.form1.method = "post";
}

function EnviaFormulario() {
	switch(tipo) {
		case 1: return VFaleConosco(); break;
		case 2:	if (VBusca()) { 
			var url;
			
			if (document.form1.tipo.value == '1'){
				url = "producao"
			}
			else{
				url = "loja"
			};		
			document.location.href=""+url+"/busca.asp?busca=" + document.form1.busca.value; 
		} break;
		case 3: 	if (VBusca()) { 
			var url;
			
			if (document.form1.tipo.value == '1'){
				url = "producao"
			}
			else{
				url = "loja"
			};
			document.location.href="../"+url+"/busca.asp?busca=" + document.form1.busca.value; 
		} break;
		case 4: return Carrinho();
		case 5: return VEnviaOrc();
	}
	return false;
}

function VEnviaOrc() {
  if (!document.form1.nome.value) { alert("Por favor, informe seu nome."); document.form1.nome.focus(); return false; };
  if (!VEmail( document.form1.email.value)) { alert("O seu e-mail não é válido!\nVerifique-o novamente."); document.form1.email.focus(); return false; };
  if (!document.form1.telefone.value) { alert("Por favor, informe o telefone."); document.form1.telefone.focus(); return false; };
  if (!document.form1.empresa.value) { alert("Por favor, informe a empresa."); document.form1.empresa.focus(); return false; };
  if (!document.form1.cidade.value) { alert("Por favor, informe a cidade."); document.form1.cidade.focus(); return false; };
  if (!document.form1.estado.value) { alert("Por favor, informe o estado."); document.form1.estado.focus(); return false; };
  return true;
}

function VFaleConosco() {
	if (!document.form1.nome.value) { alert("Por favor, informe seu nome."); document.form1.nome.focus(); return false; };
  if (!VEmail( document.form1.email.value)) { alert("O seu e-mail não é válido!\nVerifique-o novamente."); document.form1.email.focus(); return false; };
  if (!document.form1.telefone.value) { alert("Por favor, informe o telefone."); document.form1.telefone.focus(); return false; };
  if (!document.form1.empresa.value) { alert("Por favor, informe a empresa."); document.form1.empresa.focus(); return false; };
  if (!document.form1.cidade.value) { alert("Por favor, informe a cidade."); document.form1.cidade.focus(); return false; };
  if (!document.form1.estado.value) { alert("Por favor, informe o estado."); document.form1.estado.focus(); return false; };
  if (!document.form1.mensagem.value) { alert("Você deve escrever a mensagem."); document.form1.mensagem.focus(); return false; };
  return true;
}

function VBusca() {
	if (document.form1.busca.value == 'Buscar por produto:') { alert("Informe um conteúdo para busca."); document.form1.busca.focus(); return false; };
	if (document.form1.tipo.value == '-') { alert("Selecione um setor para efetuar a busca."); document.form1.tipo.focus(); return false; };	
	return true;
}

 
//===============================================================================
//= REDIMENSIONA AS IMAGENS CASO SEJAM MAIORES QUE A LARGURA PERMITIDA DO SITE ==
//===============================================================================
window.onload = function() {
	RedimensionaImagens(350);
}

function RedimensionaImagens(tamanhoimg) {
  var obj = document.getElementsByTagName("div");
  for(var i = 0;i<obj.length;i++) {
    if (obj[i].className == "imgstyle") {
      var img = obj[i].getElementsByTagName("img");
      if (img[0].width > tamanhoimg) { obj[i].innerHTML = '<img src="' + img[0].src + '" width="'+ tamanhoimg +'">' + '<br><a href="' + img[0].src + '" target="_blank">Veja a imagem no tamanho original</a>'; }
    }
  }
}


//===============================================================================
//= ABRE POP-UP CENTRALIZADO ====================================================
//===============================================================================
var win = null;
function NewWindow(mypage,myname,w,h,scroll){
	LeftPosition = parseInt((screen.width) ? (screen.width-w)/2 : 0);
	TopPosition = parseInt((screen.height) ? (screen.height-h)/2 : 0);
	settings = 'width='+w+',height='+h+',top='+TopPosition+',left='+LeftPosition+',scrollbars='+scroll+',noresizable,status=yes'
	win = window.open(mypage,myname,settings)
}


//===============================================================================
//= REDIMENSIONA POP-UP =========================================================
//===============================================================================
function Redimensiona(w, h) {
	//Corrige o tamanho da janela
	if (navigator.appName == "Microsoft Internet Explorer") {
		w = parseInt(w) + 10;
		h = parseInt(h) + 60;
	} else {
		w = parseInt(w) + 6;
		h = parseInt(h) + 60;
	};
	// IE 7
	var nversao = navigator.userAgent;
	var nresult = nversao.search(/\bMSIE 7.0\b/g);
	if (nresult > 0) {
		h = parseInt(h) + 35;
	};
	//
	// IE 8
	var nversao = navigator.userAgent;
	var nresult = nversao.search(/\bMSIE 8.0\b/g);
	if (nresult > 0) {
		h = parseInt(h) + 35;
	};
	//
	// FIREFOX 3
	var nversao = navigator.userAgent;
	var nresult = nversao.search(/\bFirefox\/3\b/g);
	if (nresult > 0) {
		h = parseInt(h) + 35;
	};
	//
	// SAFARI / CHROME
	var nversao = navigator.userAgent;
	var nresult = nversao.search(/\bSafari\b/g);
	if (nresult > 0) {
		h = parseInt(h) + 25;
		w = parseInt(w) + 7;
	};
	//
	window.resizeTo(w, h);
	LeftPosition =  parseInt((screen.width) ? (screen.width-w)/2 : 0);
	TopPosition =  parseInt((screen.height) ? (screen.height-h)/2 : 0);
	window.moveTo(LeftPosition,TopPosition);
	window.focus();
}


//===============================================================================
//= EXIBE FLASHS ================================================================
//===============================================================================
function ExibeFlash(movie,w,h,wmode,bg) {
	if(wmode == "transparent") { ftransp = true; wmode = "wmode='transparent'"; } else { ftransp = false; wmode = ""; };

	document.write('<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" width="'+w+'" height="'+h+'">');
	if(ftransp) { document.write('<param name="wmode" value="transparent"/>'); };
	document.write('<param name="quality" value="high"/>');
	document.write('<param name="movie" value="'+movie+'"/>');
	document.write('<embed src="'+movie+'" quality="high" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" '+wmode+' width="'+w+'" height="'+h+'"></embed>');
	document.write('</object>');
}


//===============================================================================
//= VERIFICA NAVEGADORES ========================================================
//===============================================================================
var ua = navigator.userAgent;
var ver = parseInt( navigator.appVersion );
var opera = /opera [56789]|opera\/[56789]/i.test(ua);
var ie = !opera && /MSIE/.test(ua);
var ie6 = ie && /MSIE [0123456]/.test(ua);
var ie7 = ie && /MSIE [789]/.test(ua);
var ieBox = ie && (document.compatMode == null || document.compatMode != "CSS1Compat");
var moz = !opera && /gecko/i.test(ua);
var nn6 = !opera && /netscape.*6\./i.test(ua);


//===============================================================================
//= FUNÇÃO DE CONVERSÃO DE MAIUSCULAS/MINUSCULAS ================================
//===============================================================================
function smallCaps(obj, type) {
		type = ((typeof type != "number") || (type > 3) || (type < 1)) ? 3 : type;
		var except = ['de','do','da','das','dos','em'];
		var tam = obj.value.length;
		var txt = obj.value;
		switch (type) {
			case 1: txt = txt.toLowerCase(); break;
			case 2: txt = txt.toUpperCase(); break;
			case 3: if (tam > 0) {
								txt = txt.toLowerCase().split(' ');
								for (var x = 0; x < txt.length; x++)
									if (!inArray(txt[x],except) && (txt[x].length > 1))
										txt[x] = txt[x].substring(0,1).toUpperCase() + txt[x].substring(1,txt[x].length);
								txt = txt.join(' ');
							}; break;
		};
		obj.value = txt;
}

function inArray(txt, array) {
	var ret = false;
	for (var x=0; x<array.length; x++)
		if (array[x] == txt)
			ret = true;
	return ret;
}


// MENSAGEM NA BARRA DE STATUS
// ----------------------------------------------------------------------------
function MM_displayStatusMsg(msgStr) { //v1.0
  status=msgStr;
  document.MM_returnValue = true;
}



//===============================================================================
//= MASCARAS ====================================================================
//===============================================================================
/* 
	Mascara para Campos.
	"#" - Numeros
	"A" - Letras UpperCase
	"a" - Letras LowerCase
	"Z" - Letras
	"*" - Qualquer Caracter
	"/", ".", "-", " ", ":" - Caracteres Fixos

	USO:
	somente números
		onKeyPress="if (event.keyCode < 48 || event.keyCode > 57) event.returnValue = false;"
		
		onKeyUp="mascara_hora(this.value)"
*/

function Mascara(objeto, evt, mask) {
	var LetrasU = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
	var LetrasL = 'abcdefghijklmnopqrstuvwxyz';
	var Letras 	= 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
	var Numeros = '0123456789';
	var Fixos 	= '().-:/ '; 
	var Charset = " !\"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_/`abcdefghijklmnopqrstuvwxyz{|}~";
	
	evt = (evt) ? evt : (window.event) ? window.event : "";
	var value = objeto.value;
	if (evt) {
		var ntecla = (evt.which) ? evt.which : evt.keyCode;
		tecla = Charset.substr(ntecla - 32, 1);
		if (ntecla < 32) return true;

		var tamanho = value.length;
		if (tamanho >= mask.length) return false;

		var pos = mask.substr(tamanho,1); 
		while (Fixos.indexOf(pos) != -1) {
			value += pos;
			tamanho = value.length;
			if (tamanho >= mask.length) return false;
			pos = mask.substr(tamanho,1);
		}

		switch (pos) {
				case '#' : if (Numeros.indexOf(tecla) == -1) return false; break;
				case 'A' : if (LetrasU.indexOf(tecla) == -1) return false; break;
				case 'a' : if (LetrasL.indexOf(tecla) == -1) return false; break;
				case 'Z' : if (Letras.indexOf(tecla) == -1) return false; break;
				case '*' : objeto.value = value; return true; break;
				default : return false; break;
		}
	}
	objeto.value = value; 
	return true;
}

/// VERIFICA E-MAIL
// ----------------------------------------------------------------------------
function VEmail( strEmail ) {
     var filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
     return (filter.test(strEmail));
}

// ----------------------------------------------------------------------------
function ajaxInit() {
	var req;
	
	try {
		req = new ActiveXObject("Microsoft.XMLHTTP");
	} catch(e) {
		try {
			req = new ActiveXObject("Msxml2.XMLHTTP");
		} catch(ex) {
			try {
				req = new XMLHttpRequest();
			} catch(exc) {
				alert("Esse browser não tem recursos para uso do Ajax");
				req = null;
			}
		}
	}
	return req;
};


function LoadAjax(metodo, url, send, destino, loadshow, loadcontent, loaddestino, janela) {
	var ajax = ajaxInit();	
	if(ajax) {  
		if(metodo == "post") {  
				ajax.open("POST", url, true);  
				ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");  
		} else {
				ajax.open("GET", url + "?rnd="+ Math.random() +"&"+ send, true);  
		}
		ajax.onreadystatechange = function() { 
																if (ajax.readyState == 1) {
																	if (loadshow == 2) {
																		document.getElementById(loaddestino).innerHTML = loadcontent;
																	};
																}
																if (ajax.readyState == 4) {
																	if (ajax.status == 200) {
																		var resultado = ajax.responseText; // Coloca o retornado pelo Ajax nessa variável 
																		resultado = resultado.replace(/\+/g," "); // Resolve o problema dos acentos (saiba mais aqui: http://www.plugsites.net/leandro/?p=4) 
																		resultado = unescape(resultado); // Resolve o problema dos acentos 
																		if (loadshow == 2) {
																			document.getElementById(loaddestino).innerHTML = '';
																		};
																		if (janela != 2) {
																			document.getElementById(destino).innerHTML = resultado;
																		} else {
																			opener.document.getElementById(destino).innerHTML = resultado;
																			setTimeout("window.close()", 1000);
																		};
																	};
																}
															}  
			
		if(metodo == "post") {  
			ajax.send(send);  
		} else {  
			ajax.send(null);  
		}  
	}  
}

// FUNÇÃO DE CARREGAR CLIENTES COM AJAX
// ----------------------------------------------------------------------------
function LoadClientes(estado) {
	var url = 'lista.asp';
	var send = 'uf=' + estado;
	var destino = 'clienteestado'; //local de retorno do conteúdo
	var loadshow = 1; //2 = exibe    <> de 2 = não exibe loading
	var loadcontent = ''; //conteúdo de loading
	var loaddestino = ''; //destino do conteúdo de loading
	var janela = 1; //1 = mesma janela    2 ou > = janela opener	
	LoadAjax("get", url, send, destino, loadshow, loadcontent, loaddestino, janela);
}

//FUNÇÃO DE CARREGAR AS FOTOS DOS PRODUTOS
//-----------------------------------------------------------------------------
function MostraImagens(codigo,categoria) {
	var url = 'ajx_imagens.asp';
	var send = 'cod='+codigo+'&cat='+categoria;
	var destino = 'ajx-produtosFotos'; //local de retorno do conteúdo
	var loadshow = 2; //2 = exibe    <> de 2 = não exibe loading
	var loadcontent = '<img src="../imagens/ajax-loader.gif" alt=""/>'; //conteúdo de loading
	var loaddestino = 'ajx-produtosFotos'; //destino do conteúdo de loading
	var janela = 1; //1 = mesma janela    2 ou > = janela opener
	LoadAjax("get", url, send, destino, loadshow, loadcontent, loaddestino, janela);
}

/// MOSTRA/ESCONDE SUBCATEGORIA
// ----------------------------------------------------------------------------
function EscondeSubcat(id) {
	document.getElementById(id).style.display = (document.getElementById(id).style.display == 'none') ? '' : 'none';
}

function MaskQtde(objeto, evt) { 
	return Mascara(objeto, evt, '####');
}
function SubmitForm() {
	document.form1.submit();
}
// FORMS
/*

CUSTOM FORM ELEMENTS

Created by Ryan Fait
www.ryanfait.com

The only thing you need to change in this file is the following
variables: checkboxHeight, radioHeight and selectWidth.

Replace the first two numbers with the height of the checkbox and
radio button. The actual height of both the checkbox and radio
images should be 4 times the height of these two variables. The
selectWidth value should be the width of your select list image.

You may need to adjust your images a bit if there is a slight
vertical movement during the different stages of the button
activation.

Visit http://ryanfait.com/ for more information.

*/

var checkboxHeight = "25";
var radioHeight = "25";
var selectWidth = "119";

/* No need to change anything after this */

document.write('<style type="text/css">input.styled { display: none; } select.styled { position: relative; width: ' + selectWidth + 'px; opacity: 0; filter: alpha(opacity=0); z-index: 5; }</style>');

var Custom = {
	init: function() {
		var inputs = document.getElementsByTagName("input"), span = Array(), textnode, option, active;
		for(a = 0; a < inputs.length; a++) {
			if((inputs[a].type == "checkbox" || inputs[a].type == "radio") && inputs[a].className == "styled") {
				span[a] = document.createElement("span");
				span[a].className = inputs[a].type;

				if(inputs[a].checked == true) {
					if(inputs[a].type == "checkbox") {
						position = "0 -" + (checkboxHeight*2) + "px";
						span[a].style.backgroundPosition = position;
					} else {
						position = "0 -" + (radioHeight*2) + "px";
						span[a].style.backgroundPosition = position;
					}
				}
				inputs[a].parentNode.insertBefore(span[a], inputs[a]);
				inputs[a].onchange = Custom.clear;
				span[a].onmousedown = Custom.pushed;
				span[a].onmouseup = Custom.check;
				document.onmouseup = Custom.clear;
			}
		}
		inputs = document.getElementsByTagName("select");
		for(a = 0; a < inputs.length; a++) {
			if(inputs[a].className == "styled") {
				option = inputs[a].getElementsByTagName("option");
				active = option[0].childNodes[0].nodeValue;
				textnode = document.createTextNode(active);
				for(b = 0; b < option.length; b++) {
					if(option[b].selected == true) {
						textnode = document.createTextNode(option[b].childNodes[0].nodeValue);
					}
				}
				span[a] = document.createElement("span");
				span[a].className = "select";
				span[a].id = "select" + inputs[a].name;
				span[a].appendChild(textnode);
				inputs[a].parentNode.insertBefore(span[a], inputs[a]);
				inputs[a].onchange = Custom.choose;
			}
		}
	},
	pushed: function() {
		element = this.nextSibling;
		if(element.checked == true && element.type == "checkbox") {
			this.style.backgroundPosition = "0 -" + checkboxHeight*3 + "px";
		} else if(element.checked == true && element.type == "radio") {
			this.style.backgroundPosition = "0 -" + radioHeight*3 + "px";
		} else if(element.checked != true && element.type == "checkbox") {
			this.style.backgroundPosition = "0 -" + checkboxHeight + "px";
		} else {
			this.style.backgroundPosition = "0 -" + radioHeight + "px";
		}
	},
	check: function() {
		element = this.nextSibling;
		if(element.checked == true && element.type == "checkbox") {
			this.style.backgroundPosition = "0 0";
			element.checked = false;
		} else {
			if(element.type == "checkbox") {
				this.style.backgroundPosition = "0 -" + checkboxHeight*2 + "px";
			} else {
				this.style.backgroundPosition = "0 -" + radioHeight*2 + "px";
				group = this.nextSibling.name;
				inputs = document.getElementsByTagName("input");
				for(a = 0; a < inputs.length; a++) {
					if(inputs[a].name == group && inputs[a] != this.nextSibling) {
						inputs[a].previousSibling.style.backgroundPosition = "0 0";
					}
				}
			}
			element.checked = true;
		}
	},
	clear: function() {
		inputs = document.getElementsByTagName("input");
		for(var b = 0; b < inputs.length; b++) {
			if(inputs[b].type == "checkbox" && inputs[b].checked == true && inputs[b].className == "styled") {
				inputs[b].previousSibling.style.backgroundPosition = "0 -" + checkboxHeight*2 + "px";
			} else if(inputs[b].type == "checkbox" && inputs[b].className == "styled") {
				inputs[b].previousSibling.style.backgroundPosition = "0 0";
			} else if(inputs[b].type == "radio" && inputs[b].checked == true && inputs[b].className == "styled") {
				inputs[b].previousSibling.style.backgroundPosition = "0 -" + radioHeight*2 + "px";
			} else if(inputs[b].type == "radio" && inputs[b].className == "styled") {
				inputs[b].previousSibling.style.backgroundPosition = "0 0";
			}
		}
	},
	choose: function() {
		option = this.getElementsByTagName("option");
		for(d = 0; d < option.length; d++) {
			if(option[d].selected == true) {
				document.getElementById("select" + this.name).childNodes[0].nodeValue = option[d].childNodes[0].nodeValue;
			}
		}
	}
}
window.onload = Custom.init;

function MaskTelefone(objeto, evt) { 
	return Mascara(objeto, evt, '(##) ####-####');
}
