var nav = navigator.userAgent.toLowerCase();
var larg1 = 0;
var alt1 = 0;
var larg2 = 0;
var alt2 = 0;
var mouseX = 0;
var mouseY = 0;
var aberto = false;
var aberto2 = false;

function limparSearch(){
	var search = document.getElementById('search');
	search.value = 'Buscar';
}

function followmouse1(evnt){
	var tipo;	
	var obj = document.getElementById('apDiv1');
	var objW = 0;
	var objH = 0;
	if(nav.indexOf('msie') != -1){ // Internet Explorer
		mouseX = event.clientX; // posX Mouse
		mouseY = event.clientY; // posY Mouse
		larg1 = document.body.clientWidth; // largura Interna
		alt1 = document.body.clientHeight; // altura Interna
		larg2 = window.screen.width; // largura Screen
		alt2 = window.screen.height; // altura Screen	
		objW = obj.clientWidth; // largura Objeto
		objH = obj.clientHeight; // altura Objeto
		tipo = "IE";
	} else{ // Firefox ( Outros )
		mouseY = evnt.pageY // posX Mouse
		mouseX = evnt.pageX; // posY Mouse
		larg1 = window.innerWidth; // largura Interna
		alt1 = window.innerHeight; //altura Interna
		larg2 = window.screen.width; // largura Screen
		alt2 = window.screen.height; // altura Screen
		objW = obj.clientWidth; // largura Objeto
		objH = obj.clientHeight; // altura Objeto
		tipo = "FIREFOX";
	}
	if(aberto == true){
		if(mouseX < (larg1 - objW) || mouseY < 125 || mouseY > (125 + objH)){
			if(mouseY < 125){
				if(mouseX < (larg1 - 120)){	
					closeObj();
				}
			} else{
				closeObj();
			}
		}
	}
	
	if(aberto2 == true){
		var obj2 = document.getElementById('apDiv2');
		var largDiv2 = obj2.clientWidth;
		var altDiv2 = obj2.clientHeight;
		var pXDiv2 = obj2.offsetLeft;
		var pYDiv2 = obj2.offsetTop;
		if(mouseX < pXDiv2 || mouseX > (pXDiv2 + largDiv2) || mouseY < pYDiv2 || mouseY > (pYDiv2 + altDiv2)){
			closeCategoria();
		}
	}
}

function openObj(){
	var obj = document.getElementById('apDiv1');
	obj.className = "showPopCar";
	aberto = true;
}

function closeObj(){
	var obj = document.getElementById('apDiv1');
	obj.className = "hidePopCar";
	aberto = false;
}
document.onmousemove = followmouse1;

function openCategoria(){
	var obj = document.getElementById('apDiv2');
	obj.className = "showPopCar";
	aberto2 = true;
}

function closeCategoria(){
	var obj = document.getElementById('apDiv2');
	obj.className = "hidePopCar";
	aberto2 = false;
}

function changeCategoria(cat, id){
	var obj = document.getElementById('categoria');
	obj.innerHTML = "<table width='0' cellspacing='0' cellpadding='0'><td><td width='100%' height='41' align='center' valign='middle'>"+cat+"</td></tr></table>";
	var obj2 = document.getElementById('cat');
	obj2.value = id;
	closeCategoria();
}




function openPop(){
	var pop = document.getElementById('popCarrinho');
	pop.className = "showPop";
}

function closePop(){
	var pop = document.getElementById('popCarrinho');
	pop.className = "hidePop";
}

function pFisica(){
	var juridica = document.getElementById('pessoajuridica');
	juridica.className = "hidePessoa";
}

function pJuridica(){
	var juridica = document.getElementById('pessoajuridica');
	juridica.className = "showPessoa";
}

function confirmIdentidade(){
	var cad1 = document.getElementById('cadastro1');
	var cad2 = document.getElementById('cadastro2');
	var form = document.getElementById('identidade');
	if(cad1.checked == true){
		var cep = document.getElementById('cep_cadastro');
		if(cep.value == ""){
			cep.focus();
			alert("O Campo Cep é Obrigatório!");
		} else{			
			form.submit();
		}
	} else{
		var email = document.getElementById('email_cadastro');
		var senha = document.getElementById('senha_cadastro');
		if(email.value == ""){			
			email.focus();
			alert("O Campo E-mail é Obrigatório!");
		} else{
			if(senha.value == ""){
				senha.focus();
				alert("O Campo Senha é Obrigatório!");
			} else{
				form.submit();
			}
		}
	}
}

function formatar(mascara, documento){
	var i = documento.value.length;
	var saida = mascara.substring(0,1);
	var texto = mascara.substring(i);
	if(texto.substring(0,1) != saida){
		documento.value += texto.substring(0,1);
	}
}

function alertMessage(mensagem){
	if(mensagem == "loginInvalido"){
		alert("E-mail ou Senha Invalido!");
	}
	if(mensagem == "cepInvalido"){
		alert("Cep Invalido!");
	}
	if(mensagem == "endIncompleto"){
		alert("Preencha os Campos Numero e Completo nos Dados de Contato!");
	}
}

function disableIE(){
	var isento = document.getElementById('isento');
	var ie = document.getElementById('ie_cadastro');
	if(isento.checked){
		ie.disabled = "disabled";
		ie.className = "disableInput";
		ie.value = "ISENTO";
	} else{
		ie.disabled = "";
		ie.className = "";
		ie.value = "";
	}
}

function confirmCadastro(){
	var pessoa = document.getElementById('pessoa1_cadastro');
	var confirmEmpresa = "NO";
	var confirmDados = "NO";
	var confirmContato = "NO";
	var confirmLogin = "NO";
	
	var razao = document.getElementById('razao_cadastro');
	var fantasia = document.getElementById('fantasia_cadastro');
	var cnpj = document.getElementById('cnpj_cadastro');
	var ie = document.getElementById('ie_cadastro');
	
	if(pessoa.checked){
		confirmEmpresa = "YES";
	} else{
		if(razao.value == ""){
			alert("O campo Razão Social é Obrigatório!");
		} else{
			if(fantasia.value == ""){
				alert("O campo Nome Fantasia é Obrigatório!");
			} else{
				if(cnpj.value == ""){
					alert("O campo CNPJ é Obrigatório!");
				} else{
					if(ie.value == ""){
						alert("O campo Inscrição Estadual é Obrigatório!");
					} else{
						confirmEmpresa = "YES";
					}
				}
			}
		}
	}
	
	var apelido = document.getElementById('apelido_cadastro');
	var nome = document.getElementById('nome_cadastro');
	var cpf = document.getElementById('cpf_cadastro');
	var nascimento = document.getElementById('nascimento_cadastro');
	
	if(confirmEmpresa == "YES"){
		if(apelido.value == ""){
			alert("O campo Apelido é Obrigatório!");
		} else{
			if(nome.value == ""){
				alert("O campo Nome é Obrigatório!");
			} else{				
				if(cpf.value == ""){
					alert("O campo CPF é Obrigatório!");
				} else{
					if(nascimento.value == ""){
						alert("O campo Data de Nascimento é Obrigatório!");
					} else{
						confirmDados = "YES";
					}					
				}
			}
		}
	}		
	
	var cep = document.getElementById('cep_cadastro');
	var rua = document.getElementById('rua_cadastro');
	var numero = document.getElementById('numero_cadastro');
	var compl = document.getElementById('compl_cadastro');
	var bairro = document.getElementById('bairro_cadastro');
	var cidade = document.getElementById('cidade_cadastro');
	var estado = document.getElementById('estado_cadastro');
	
	var ddd1 = document.getElementById('ddd1_cadastro');
	var ddd2 = document.getElementById('ddd2_cadastro');
	var ddd3 = document.getElementById('ddd3_cadastro');
	var ddd4 = document.getElementById('ddd4_cadastro');
	var telefone1 = document.getElementById('telefone1_cadastro');
	var telefone2 = document.getElementById('telefone2_cadastro');
	var telefone3 = document.getElementById('telefone3_cadastro');
	var telefone4 = document.getElementById('telefone4_cadastro');
	
	if(confirmDados == "YES"){
		if(cep.value == ""){
			alert("O campo CEP é Obrigatório!");
		} else{
			if(rua.value == ""){
				alert("O campo Endereço é Obrigatório!");
			} else{
				if(numero.value == ""){
					alert("O campo Numero é Obrigatório!");
				} else{
					if(bairro.value == ""){
						alert("O campo Bairro é Obrigatório!");
					} else{
						if(cidade.value == ""){
							alert("O campo Cidade é Obrigatório!");
						} else{
							if(telefone1.value == "" && telefone2.value == "" && telefone3.value == "" && telefone4.value == ""){
								alert("O campo Telefone ou Celular é Obrigatório!");
							} else{
								if(ddd1.value == "" && ddd2.value == "" && ddd3.value == "" && ddd4.value == ""){
									alert("O campo DDD é Obrigatório!");
								} else{
									confirmContato = "YES";	
								}								
							}
						}
					}
				}
			}
		}
	}
	
	var email1 = document.getElementById('email1_cadastro');
	var email2 = document.getElementById('email2_cadastro');
	
	var senha1 = document.getElementById('senha1_cadastro');
	var senha2 = document.getElementById('senha2_cadastro');
	
	if(confirmContato == "YES"){
		if(email1.value != email2.value || email1.value == "" || email2.value == ""){
			alert("Email não Confere. Por Favor Corrija o campo E-mail!");
		} else{
			if(senha1.value != senha2.value || senha1.value == "" || senha2.value == ""){
				alert("Senha não Confere. Por Favor Corrija o campo E-mail!");
			} else{
				confirmLogin = "YES";
			}
		}
	}
	
	var cadastro = document.getElementById('form_cadastro');
	
	if(confirmLogin == "YES"){
		cadastro.submit();
	}
}

function number_only(myfield, e, dec){
	var key;
    var keychar;
    var field = myfield;
 
    if (window.event)
        key = window.event.keyCode;
    else if (e)
        key = e.which;
    else
        return true;
                   
    if ((key == null) || (key==37) || (key==39) || (key==8) || (key==46) || (key==27) )
    {
        if (((key==46) || (key==8))) 
        {
            if (field.value.indexOf('0') > 0)
            {
                field.value = '1';
                return false;
            }
        }
        return true;
    }
	
   if ((key > 47 && key < 58) || (key > 95 && key < 106))
   {
        if ((key == 48 || key == 96) && field.value > 0)
        {
            if (field.value > 998)
                return false;
                
            field.value += '0';
            return false;
        }
        else if ((key == 48 || key == 96) && field.value == '')
        {
            return false;
        }
        
        return true;
       
    }
    else
    {
        return false;
    }
}

String.PAD_LEFT  = 0;
String.PAD_RIGHT = 1;
String.PAD_BOTH  = 2;

String.prototype.pad = function(size, pad, side) {
  var str = this, append = "", size = (size - str.length);
  var pad = ((pad != null) ? pad : " ");
  if ((typeof size != "number") || ((typeof pad != "string") || (pad == ""))) {
    throw new Error("Wrong parameters for String.pad() method.");
  }
  if (side == String.PAD_BOTH) {
    str = str.pad((Math.floor(size / 2) + str.length), pad, String.PAD_LEFT);
    return str.pad((Math.ceil(size / 2) + str.length), pad, String.PAD_RIGHT);
  }
  while ((size -= pad.length) > 0) {
    append += pad;
  }
  append += pad.substr(0, (size + pad.length));
  return ((side == String.PAD_LEFT) ? append.concat(str) : str.concat(append));
}

Number.prototype.format = function(d_len, d_pt, t_pt) {
	  var d_len = d_len || 0;
	  var d_pt = d_pt || ".";
	  var t_pt = t_pt || ",";
	  if ((typeof d_len != "number")
	    || (typeof d_pt != "string")
	    || (typeof t_pt != "string")) {
	    throw new Error("wrong parameters for method 'String.pad()'.");
	  }
	  var integer = "", decimal = "";
	  var n = new String(this).split(/\./), i_len = n[0].length, i = 0;
	  if (d_len > 0) {
	    n[1] = (typeof n[1] != "undefined") ? n[1].substr(0, d_len) : "";
	    decimal = d_pt.concat(n[1].pad(d_len, "0", String.PAD_RIGHT));
	  }
	  while (i_len > 0) {
	    if ((++i % 3 == 1) && (i_len != n[0].length)) {
	      integer = t_pt.concat(integer);
	    }
	    integer = n[0].substr(--i_len, 1).concat(integer);
	  }
	  return (integer + decimal);
}

function somarValor(num, total){
	var vSubTotal = 0;	
	var q = 0;
	for(var i=0; i<total; i++){
		var quant = document.getElementById("quant_"+i);
		var valor = document.getElementById("valor_"+i);		
		var vTotal = quant.value * valor.value;
		vSubTotal = vSubTotal + vTotal;
		if(i == num){
			var objTotal = document.getElementById("total_"+num);
			objTotal.innerHTML = vTotal.format(2, ",", ".");
			q = quant.value;
		}
	}	
	var objSubTotal = document.getElementById("subTotal");
	objSubTotal.innerHTML = vSubTotal.format(2, ",", ".");
	setCarrinho(num, q);
}

function change(div){
	switch(div){
			case "descricao":
				document.getElementById("descricao").style.display = "block";
				document.getElementById("dadosTecnicos").style.display = "none";
				document.getElementById("itensIncluso").style.display = "none";
			break;
			case "dadosTecnicos":
				document.getElementById("descricao").style.display = "none";
				document.getElementById("dadosTecnicos").style.display = "block";
				document.getElementById("itensIncluso").style.display = "none";
			break; 
			case "itensIncluso":
				document.getElementById("descricao").style.display = "none";
				document.getElementById("dadosTecnicos").style.display = "none";
				document.getElementById("itensIncluso").style.display = "block";
			break;  
	}		
}

function switchOrdem(ordem){                                
	window.location = "index.php?"+ordem;
}

function exibirPedidos(n){
	var a = document.getElementById('ped'+n+'a');
	var b = document.getElementById('ped'+n+'b');
	a.className = "hidePedidos";
	b.className = "showPedidos";
}

function ocultarPedidos(n){
	var a = document.getElementById('ped'+n+'a');
	var b = document.getElementById('ped'+n+'b');
	a.className = "showPedidos";
	b.className = "hidePedidos";	
}

window.onresize = function(event){
	var w = getWidth();
	var h = getHeight();
}

function getWidth(){  
	//return window.innerWidth ? window.innerWidth : /* For non-IE */ 
	//document.documentElement ? document.documentElement.clientWidth : /* IE 6+ (Standards Compilant Mode) */ 
	//document.body ? document.body.clientWidth : /* IE 4 Compatible */ 
	//return window.screen.width; /* Others (It is not browser window size, but screen size) */ 
	return document.body.clientWidth;
}  

function getHeight(){  
	//return window.innerHeight ? window.innerHeight : /* For non-IE */ 
	//document.documentElement ? document.documentElement.clientHeight : /* IE 6+ (Standards Compilant Mode) */ 
	//document.body ? document.body.clientHeight : /* IE 4 Compatible */ 
	//return window.screen.height; /* Others (It is not browser window size, but screen size) */ 
	return document.body.clientHeight;
}  

function calcFrete(valor, frete, qt, total){
	var freteTotal = frete * qt;
	var vfinal = valor + freteTotal;
	for(var i = 0; i < total; i++){
		var n = i + 1;
		var item = document.getElementById('item_frete_'+n);
		item.value = frete.format(2, "", "");
	}
	var resultado = document.getElementById("subtotal");
	resultado.innerHTML = "R$ "+vfinal.format(2, ",", ".");
}


