var _HTTP_PATH_ = "http://" + document.domain + "/";

var total_de_divs_de_produtos = 1;

switch (document.domain) {
	case 'www.magicwebdesign.com.br':
		_HTTP_PATH_ += "dev/conduspar/";
		break;
	case '192.168.0.200':
		_HTTP_PATH_ += "dev/conduspar.com.br/";
		break;
}

function envia(param) {
  if (param == 1) {
    if (document.f1.nome.value.length < 3) {
      alert("Preencha o campo NOME!");
      document.f1.nome.focus();
    }
    else {
      if (!validaemail(document.f1.emai.value)) {
        alert("Preencha o campo E-MAIL!");
              document.f1.emai.focus();
      }
      else {
        document.f1.submit();
      }
    }
  }
  else if (param == 2) {
    if (!validaemail(document.f2.emai.value)) {
      alert("Preencha o campo E-MAIL!");
      document.f2.emai.focus();
    }
    else {
      document.f2.submit();
    }
  }
  else if ( param == 3 ) {
    if (document.f1.nome.value.length < 3) {
      alert("Preencha o campo NOME!");
      document.f1.nome.focus();
    }
    else {
      if (!validaemail(document.f1.email.value)) {
        alert("Preencha o campo E-MAIL!");
              document.f1.email.focus();
      }
      else {
        if ( document.f1.comentario.value.length < 3 )
        {
            alert("Preencha o campo MENSAGEM!");
        } else {
            document.f1.submit();
        }
      }
    }
  } else {
    if (document.f1.nome.value.length < 3) {
      alert("Preencha o campo NOME!");
      document.f1.nome.focus();
    }
    else {
      if (!validaemail(document.f1.email.value)) {
        alert("Preencha o campo E-MAIL!");
              document.f1.email.focus();
      }
      else {
        document.f1.submit();
      }
    }
  }
}

var res = screen.height;
	if (res <= 600)
	{
		document.write('<style type="text/css">#geral{min-height:100%;_height:100%;}<\/style>')
	}
	else if ( res == 768 )
	{
		document.write('<style type="text/css">#geral{min-height:100%;_height:100%;}<\/style>')
	}
	else if ( res == 864 )
	{
		document.write('<style type="text/css">#geral{min-height:92%;_height:92%;}<\/style>')
	}
	else if ( res == 1024 )
	{
		document.write('<style type="text/css">#geral{min-height:100%;_height:100%;}<\/style>')
	}
	else if ( res == 1200 )
	{
		document.write('<style type="text/css">#geral{min-height:100%;_height:100%;}<\/style>')
	}
	else
	{
		document.write('<style type="text/css">#geral{min-height:100%;_height:100%;}<\/style>')
	}


function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

function validaBusca()
{
	if($('busca').value.replace(/\ /g, '') == "")
	{
		alert('Digite alguma palavra para efetuar uma busca!');
	}
	else
	{
		if($('busca').value.length<3)
		{
			alert('Digite alguma palavra com no mínimo 3 caracteres para efetuar uma busca!');
		}
		else
		{
			$('frm_busca').submit();
		}
	}
}

function validaemail(email) {
  var objRegExp  = /^[A-Za-z0-9]([\w\.\-\_]*)@([A-Za-z0-9\.]*)\.(([A-Za-z]{3}\.[A-Za-z]{2}$)|([A-Za-z]{3}$)|([a-z]{2}$))/i ;
  return objRegExp.test(email);
}

//Funções Ajax
//url -> página a ser carregada, parametros -> colocar os parametros separados por "&", div -> onde será carregado o resultado
var g=0;
function AjaxRequest(url, elemento)
{
	var ajax = objAjax();
	if(ajax == null)
	{
		alert("Impossível concluir a operação");
	}

	url2 = url+Math.random();

	ajax.open("GET",url2,true);
	ajax.onreadystatechange = function()
	{
		if(ajax.readyState == 4)
		{
			document.getElementById(elemento).src = url+'&amp;' + (g++);
		}
	}

	ajax.send(null);
}

function objAjax()
{
	var xmlHttp=null;
	try
	  {
	  // Firefox, Opera 8.0+, Safari
	  xmlHttp=new XMLHttpRequest();
	  }
	catch (e)
	  {
	  // Internet Explorer
	  try
	    {
	    xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
	    }
	  catch (e)
	    {
	    xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
	    }
	  }
	return xmlHttp;
}



function abre_popup(foto)
{
  window.open('foto.htm?'+foto,'imagem','width=100, height=100, status=no');
}

function MM_jumpMenu(targ,selObj,restore){ //v3.0
  eval(targ+".location='"+selObj.options[selObj.selectedIndex].value+"'");
  if (restore) selObj.selectedIndex=0;
}
/*
    COMO USAR
    EX: onkeypress="return Mascaras ( event, 'FONE', 'nome_id' );"
*/
function Mascaras ( e, formato, objeto )
{
    var key;

    if ( window.event ) keyPressed = window.event.keyCode; // IE hack
    else keyPressed = e.which; // <B>standard method</B>

    if ( keyPressed >= 48 && keyPressed <= 57 )
    {
        var campo = document.getElementById(objeto);

        /*
            DATA
            FORMATO: 00/00/0000
        */
        if ( formato == 'DATA' )
        {
            separador = '/';
            conjunto1 = 2;
            conjunto2 = 5;
            if ( campo.value.length == conjunto1 )
                campo.value = campo.value + separador;

            if ( campo.value.length == conjunto2 )
                campo.value = campo.value + separador;

            return true;
        }

        /*
            HORA
            FORMATO: 00:00
        */
        if (formato == 'HORA')
        {
            separador = ':';
            conjunto1 = 2;
            if ( campo.value.length == conjunto1 )
                campo.value = campo.value + separador;

            return true;
        }

        /*
            CEP
            FORMATO: 00000-000
        */
        if (formato == 'CEP')
        {
            separador = '-';
            conjunto1 = 5;
            if (    campo.value.length == conjunto1 )
                campo.value = campo.value + separador;

            return true;
        }

        /*
            CPF
            FORMATO: 000.000.000-00
        */
        if (formato == 'CPF')
        {
            separador = '.';
            separador1 = '-';
            conjunto1 = 3;
            conjunto2 = 7;
            conjunto3 = 11;
            if ( campo.value.length == conjunto1 )
                campo.value = campo.value + separador;

            if ( campo.value.length == conjunto2 )
                campo.value = campo.value + separador;

            if ( campo.value.length == conjunto3 )
                campo.value = campo.value + separador1;

            return true;
        }

        /*
            CNPJ
            FORMATO: 00.000.000/0000-00
        */
        if (formato == 'CNPJ')
        {
            separador1 = '.';
            separador2 = '/';
            separador3 = '-';
            conjunto1 = 2;
            conjunto2 = 6;
            conjunto3 = 10;
            conjunto4 = 15;
            if ( campo.value.length == conjunto1 )
                campo.value = campo.value + separador1;

            if ( campo.value.length == conjunto2 )
                campo.value = campo.value + separador1;

            if ( campo.value.length == conjunto3 )
                campo.value = campo.value + separador2;

            if ( campo.value.length == conjunto4 )
                campo.value = campo.value + separador3;

            return true;
        }
		
		/*
            IE
            FORMATO: 00.000.000-0
        
        if (formato == 'IE')
        {
			
            separador1 = '.';
            separador2 = '-';
            conjunto1 = 2;
            conjunto2 = 6;
            conjunto3 = 10;
            
            if ( campo.value.length == conjunto1 )
                campo.value = campo.value + separador1;

            if ( campo.value.length == conjunto2 )
                campo.value = campo.value + separador1;

            if ( campo.value.length == conjunto3 )
                campo.value = campo.value + separador2;
			
            return true;
        }*/

        /*
            FONE
            FORMATO: (00) 0000-0000
        */
        if ( formato == 'FONE' )
        {
            separador1 = '(';
            separador2 = ') ';
            separador3 = '-';
            conjunto1 = 0;
            conjunto2 = 3;
            conjunto3 = 9;
            if ( campo.value.length == conjunto1 )
                campo.value = campo.value + separador1;

            if ( campo.value.length == conjunto2 )
                campo.value = campo.value + separador2;

            if ( campo.value.length == conjunto3 )
                campo.value = campo.value + separador3;

            return true;
        }

        /*
            FONE2
            FORMATO: 0000-0000
        */
        if ( formato == 'FONESIMPLES' )
        {
            separador1 = '-';
            conjunto1 = 4;
            if ( campo.value.length == conjunto1 )
                campo.value = campo.value + separador1;

            return true;
        }
    }
    else if ( keyPressed == 8 || keyPressed == 13 || keyPressed == 0 )
        return true;
    else
        return false;
}

/*
    COMO USAR
    EX: onkeypress="return TextoSimples ( event );"
*/
function TextoSimples ( e )
{
    if ( window.event ) keyPressed = window.event.keyCode; // IE hack
    else keyPressed = e.which; // <B>standard method</B>

    if ( keyPressed == 8 || keyPressed == 95  || keyPressed == 13  || keyPressed == 0 ) return true;
    else if ( ( keyPressed >= 48 && keyPressed <= 57 ) || (keyPressed > 96 && keyPressed < 123) || keyPressed == 95 ) return true;
    else if ( ( keyPressed > 191 && keyPressed < 221 ) || ( keyPressed > 223 && keyPressed < 253 ) ) return true;

    return false;
}

/*
    COMO USAR
    EX: onkeypress="return Numeros ( event );"
*/
function Numeros ( e )
{
    if ( window.event ) keyPressed = window.event.keyCode; // IE hack
    else keyPressed = e.which; // <B>standard method</B>

    if ( keyPressed == 8 || keyPressed == 13 || keyPressed == 0 ) return true;
    else if ( keyPressed >= 48 && keyPressed <= 57 ) return true;

    return false;
}

function MM_jumpMenu(targ,selObj,restore){ //v3.0
  eval(targ+".location='"+selObj.options[selObj.selectedIndex].value+"'");
  if (restore) selObj.selectedIndex=0;
}

function abreFotoGaleria(galer_id, foto,imagemOriginal)
{
 var regex = new RegExp(foto + '$');
 if (!$('img#galeria_foto').attr('src').match(regex)) {
 $('img#galeria_foto')
 .fadeOut('slow', function() {
 $('span#loading-animation').show();
 var oSrc = this.src, img = null;
 img = $(document.createElement('img'))
 .load(function(){
 $('img#galeria_foto')
 .attr({
 src: this.src,
 oSrc: oSrc,
 alt: foto,
 title: foto
 })
 .fadeIn('slow');
  if(imagemOriginal!="")
  {
  	document.getElementById('linkBaixarImagem').href=_HTTP_PATH_+"baixarImagem.php?imagem="+imagemOriginal;
  	$('div#baixarImagem').show();
  }
  else
  {
  	$('div#baixarImagem').hide();
  }

 $('span#loading-animation').hide()
 })
 .attr('src', ( _HTTP_PATH_ || "") + "img/galeria/" + galer_id + "/" + foto)
 });
 }

}

function acrescenta_click (id)
{
	new Ajax.Request("_ajax_clicks.php",
	{
		method     : 'post',
		postBody   : 'id=' + id,
		onLoading  : function() {},
		onComplete : function(req) {},
		onFailure  : function() {}
	});
}

function adicionarProdutos ()
{
	total_de_divs_de_produtos++;
	
	// copia conteúdo do primeiro div (primeiro produto)
	var	tmp				= $$('div._etapa');
		classe			= tmp[tmp.length-1].className == 'agrupa_produto _etapa' ? 'agrupa_produto2 _etapa' : 'agrupa_produto _etapa';
	
	var div				= document.createElement('div');
		div.className	= classe;
		div.setAttribute('class', classe);
		div.id			= "div_produtos_"+total_de_divs_de_produtos;
		div.innerHTML	= $('produtos_modelo').innerHTML;
		 
	var span = div.getElementsByTagName('span');
	
	for (var i=0; i<span.length; i++)
	{
		span[i].id = span[i].id  + total_de_divs_de_produtos;
	}
		 
	var select			= div.getElementsByTagName('select');
		select[0].id	= select[0].id + total_de_divs_de_produtos;
	
	var div2				= document.createElement('div');
		div2.className		= "botao_remover";
		div2.id				= "link_remover" + total_de_divs_de_produtos;
		
	var link2				= document.createElement('a');
		link2.href			= "#";
		link2.id			= "link_remover_"+total_de_divs_de_produtos;
		link2.onclick		= function(){return removerProdutos(this.id.replace('link_remover_',''))};
		link2.onmouseout	= function(){MM_swapImgRestore()};
		link2.onmouseover	= function(){MM_swapImage('bt_remover','','img/bt_remover-over.gif',1)};
	
	var img2				= document.createElement('img');
		img2.src			= "img/bt_remover.gif";
		img2.name			= "bt_remover";
		img2.width			= "99";
		img2.height			= "25";
		img2.alt			= "Remover o produto";
		img2.title			= "Remover o produto";
		img2.className		= "bt_remover";
	
	link2.appendChild(img2);
	div2.appendChild(link2);
	div.appendChild(div2); 
	
	// adiciona o novo div ao final da lista
	$('produtos').appendChild(div);
	
	var	tmp = $$('div._etapa');
	
	return false;
}

function removerProdutos (id)
{
	$('div_produtos_'+id).remove();
	
	var classe = "agrupa_produto2 _etapa";
	var	tmp = $$('div._etapa');
	for(var i=0; i<tmp.length; i++)
	{
		classe = classe == 'agrupa_produto2 _etapa' ? 'agrupa_produto _etapa' : 'agrupa_produto2 _etapa';
		tmp[i].className = classe;
	}
	
	return false;
}

function carregaCotacao (id, tipo, produto, bitola)
{
	if (tipo == 'C')
	{
		bitola = bitola.replace('+', ';;');	
	}
	
	new Ajax.Request("ajaxCotacao.php",
	{
		method			: 'post',
		postBody		: 'id=' + id +
					 	  '&tipo=' + tipo +
						  '&produto=' + produto +
					 	  '&bitola=' + bitola,
		onLoading		: function() {},
		onComplete		: function(req)
						{
							id = id.substr(13, id.length);
							if (tipo == 'P')
							{
								$('cotacao_produto'+id).update(req.responseText);
							}
							if (tipo == 'B')
							{
								$('cotacao_bitola'+id).update(req.responseText);
							}
							if (tipo == 'C')
							{
								$('cotacao_cor'+id).update(req.responseText);
							}
						},
		onFailure	: function() {}
	});
}


function validaCotacao()
{
	var msg = '';
	
	if ($('razao_social').value == '')
	{
		msg += '	- Razão Social\n';
	}
	
	if ($('contato').value == '')
	{
		msg += '	- Contato\n';
	}
	
	if ($('cidade').value == '')
	{
		msg += '	- Cidade\n';
	}
	
	if ($('fone').value == '')
	{
		msg += '	- Fone\n';
	}
	
	if ($('email').value == '')
	{
		msg += '	- E-mail\n';
	}
	
	if ($('cnpj').value == '')
	{
		msg += '	- CNPJ\n';
	}
	
	
	
	for (var i=0; i < total_de_divs_de_produtos; i++)
	{
	
		var j = i + 1;
	
		if ($('selectProduto'+j).value == '---Selecione---')
		{
			msg += '	- Produto '+j+'\n';
		}
		
		if (document.getElementsByName('bitola[]')[i].value == '---Selecione---')
		{
			msg += '	- Bitola '+j+'\n';
		}
		
		if (document.getElementsByName('cor[]')[i].value == '---Selecione---')
		{
			msg += '	- Cor '+j+'\n';
		}
		
		if (document.getElementsByName('metragem[]')[i].value == '')
		{
			msg += '	- Metragem '+j+'\n';
		}
	
	}
		
		
	if (msg == '')
	{
		$('f1').submit();
		return true;
	}
	
		
	var mensagem = 'Os campos a seguir precisam ser preenchidos:\n' + msg;
	alert(mensagem);
	return false;
	
}