var Agente=navigator.userAgent.toUpperCase();

if(1+Agente.indexOf('MSIE'))var sBrowser='IE';

else if(1+Agente.indexOf('FIREFOX'))var sBrowser='FF';

else var sBrowser='NS';



if (document.all)

	var tagDisplay = "block";

else

	var tagDisplay = "table-row";



function mascararSenha(campo) {

	if (campo.id == "senhaMascara") {

		campo.style.display = "none";

		document.getElementById("senhaValor").style.display = tagDisplay;

		document.getElementById("senhaValor").focus();



	} else if (campo.id == "senhaValor") {

		if (campo.value.length == 0) {

			campo.style.display = "none";

			document.getElementById("senhaMascara").style.display = tagDisplay;

		}

	}

}





function carrinhoConcluir() {

	if (document.formCarrinho.frete.value == "") {

		alert("Informe o CEP de entrega para calcular o valor do frete!");	

		document.formCarrinho.cep.focus();

	} else {

		window.location = "identificacao.php";

	}

}



function carrinhoValidaAddCarinho() {

	try {

		if (document.frmProdutoDet.tamanho.value == "") {

			alert("Informe o tamanho!");

			document.frmProdutoDet.tamanho.focus();

			return false;

		}

	} catch (e) {}



	try {

		if (document.frmProdutoDet.cor.value == "") {

			alert("Informe a cor!");

			document.frmProdutoDet.cor.focus();

			return false;

		}



	} catch (e) {}

}



function carrinhoAlteraQtd(campoAlteraQtd, tamanho, cor) {
	quantidade 		= eval("document.formCarrinho."+campoAlteraQtd+".value");
	array 			= campoAlteraQtd.split('x');
	produto_codigo 	= array[1];
	tamanho		 	= array[2];
	cor			 	= array[3];

	if (quantidade == "")	
		quantidade = 1;
		
	if (quantidade <= 0) {
		window.location = "carrinho_exec.php?produto_codigo="+produto_codigo+"&tamanho="+tamanho+"&cor="+cor+"&action=remove";
	} else {
		window.location = "carrinho_exec.php?produto_codigo="+produto_codigo+"&quantidade="+quantidade+"&tamanho="+tamanho+"&cor="+cor;
	}
}

function ajax() {

    try {

        return new ActiveXObject("Microsoft.XMLHTTP");

    } catch(e) {

        try {

            return new ActiveXObject("Msxml2.XMLHTTP");

        } catch(ex) {

            try {

                return new XMLHttpRequest();

            } catch(exc) {

                alert("Esse browser nao tem recursos para uso do AJAX");

                return false;

            }

        }

    }

}



function calculoFrete() {

	var cep  = document.formCarrinho.cep_.value;

	var peso = document.formCarrinho.peso.value;

	var tipo_frete  = "sedex"; //document.formCarrinho.tipo_frete[0].checked;
	
	/*
	if (tipo_frete) {
		tipo_frete = "sedex";	
	} else {
		tipo_frete = "pac";	
	}
	*/

	var len = cep.length;

	if (cep == "" || len < 9 || cep == "00000-000") {

		alert("Informe o CEP de entrega de forma correta!")

		document.formCarrinho.cep_.focus();

	} else {

		ajax1 = new ajax;

		document.getElementById("frete_destino").innerHTML = "<img src='img/ajax-loader4.gif'>";

		ajax1.open("POST", "class/Frete.php", true );

		ajax1.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

		ajax1.send("&cepDestino="+cep+"&peso="+peso+"&tipo_frete="+tipo_frete);

		ajax1.onreadystatechange = function() { 

			if (ajax1.readyState == 4) {

				var strRetorno  = ajax1.responseText;

				var strDestino  = strRetorno.split("|")[0];

				var strFrete    = strRetorno.split("|")[1];

				

				if (strFrete == undefined) { 

					document.getElementById("frete_destino").innerHTML 	= "Nao foi possível calcular o valor do frete";

					document.getElementById("frete_valor").innerHTML 	= "";

				} else {

					//document.getElementById("frete_destino").innerHTML 	= "Envio: " + strDestino;
					document.getElementById("frete_destino").innerHTML 	= "";


					document.getElementById("frete_valor").innerHTML 	= strFrete;



					document.formCarrinho.frete.value = float2moeda(strFrete);

				}

				

				calculoValorTotal();

			} else {

				document.getElementById("frete_destino").innerHTML = "<img src='img/ajax-loader4.gif'>";

			}

		}

	}

}



function calculoValorTotal() {

	document.getElementById("frete_valor").innerHTML = float2moeda(document.getElementById("frete_valor").innerHTML);	



	var subtotal 	= moeda2float(document.getElementById("subtotal").innerHTML);

	var frete_valor = moeda2float(document.getElementById("frete_valor").innerHTML);



	var total = roundNumber(subtotal + frete_valor);

	document.getElementById("total").innerHTML = float2moeda(total);

}



function float2moeda(num) {

   x = 0;



   if(num<0) {

      num = Math.abs(num);

      x = 1;

   }   if(isNaN(num)) num = "0";

      cents = Math.floor((num*100+0.5)%100);



   num = Math.floor((num*100+0.5)/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));   ret = num + ',' + cents;   if (x == 1) ret = ' - ' + ret;return ret;



}



function moeda2float(moeda){



   moeda = moeda.replace(".","");



   moeda = moeda.replace(",",".");



   return parseFloat(moeda);



}



function roundNumber (rnum) {



   return Math.round(rnum*Math.pow(10,2))/Math.pow(10,2);



}



function validaCPF(cpf){ // Verifica a validade do CPF informado

	var msg = "CPF válido";

	var sch;

	var nRecebeCPF, nSoma, nresultado1, nresultado2, ns, nx;

	var arrNumero = Array(11);



	nRecebeCPF = cpf;

	ns = "";

	for(nx=0;nx<nRecebeCPF.length;nx++){

		sch = nRecebeCPF.substring(nx,nx+1);

		sch = parseInt(sch);

		sch = new String(sch);

		if(sch != "NaN"){

			ns += sch;

		}

	}



	nRecebeCPF = ns



	tudoIgual = 1; // Verifica se todos os números são iguais

	for (i = 1; i < nRecebeCPF.length; i++) {

		if (nRecebeCPF.substring(i-1, i) != nRecebeCPF.substring(i, i+1)){

			tudoIgual = 0;

		}

	}



	if(nRecebeCPF.length != 11){

		msg = "Quantidade de dígitos inferior a quantidade de dígitos de CPF";

		resultado = false;

	}

	else if(tudoIgual == 1){

		msg = "Todos us números são iguais";

		resultado = false;

	}

	else if(nRecebeCPF == "12345678909"){

		msg = "Número de CPF inexistente";

		resultado = false;

	}

	else{

		arrNumero[0] = nRecebeCPF.substring(0,1);

		arrNumero[1] = nRecebeCPF.substring(1,2);

		arrNumero[2] = nRecebeCPF.substring(2,3);

		arrNumero[3] = nRecebeCPF.substring(3,4);

		arrNumero[4] = nRecebeCPF.substring(4,5);

		arrNumero[5] = nRecebeCPF.substring(5,6);

		arrNumero[6] = nRecebeCPF.substring(6,7);

		arrNumero[7] = nRecebeCPF.substring(7,8);

		arrNumero[8] = nRecebeCPF.substring(8,9);

		arrNumero[9] = nRecebeCPF.substring(9,10);

		arrNumero[10] = nRecebeCPF.substring(10,11);



		nSoma = 10 * arrNumero[0] + 9 * arrNumero[1] + 8 * arrNumero[2] + 7 * arrNumero[3] + 6 * arrNumero[4] + 5 * arrNumero[5] + 4 * arrNumero[6] + 3 * arrNumero[7] + 2 * arrNumero[8]



		nSoma = nSoma-(11*parseInt(nSoma/11));



		if(nSoma == 0 || nSoma == 1){

			nresultado1 = 0;

		}

		else{

			nresultado1 = 11-nSoma;

		}



		if(nresultado1 == arrNumero[9]){

			nSoma = arrNumero[0] * 11 + arrNumero[1] * 10 + arrNumero[2] * 9 + arrNumero[3] * 8 + arrNumero[4] * 7 + arrNumero[5] * 6 + arrNumero[6] * 5 + arrNumero[7] * 4 + arrNumero[8] * 3 + arrNumero[9] * 2

			nSoma = nSoma-(11*parseInt(nSoma/11));

			if(nSoma == 0 || nSoma == 1){

				nresultado2 = 0;

			}

			else{

				nresultado2 = 11 - nSoma;

			}



			if(nresultado2 == arrNumero[10]){

				resultado = true;

			}

			else{

				msg = "CPF inválido";

				resultado = false;

			}

		}

		else{

			msg = "CPF inválido";

			resultado = false;

		}

	}

	//resultado = msg;

	return resultado;

}



function checkMail(mail){

	var er = new RegExp(/^[A-Za-z0-9_\-\.]+@[A-Za-z0-9_\-\.]{2,}\.[A-Za-z0-9]{2,}(\.[A-Za-z0-9])?/);

	if(typeof(mail) == "string"){

		if(er.test(mail)){ return true; }

	}else if(typeof(mail) == "object"){

		if(er.test(mail.value)){ 

					return true; 

				}

	}else{

		return false;

		}

}



function windowopen(title,src,left,top,tamx,tamy){

  if(!overlay){if(!setupOverlay()) return false;}

  rewriteOverlayDiv("");

  var v=navigator.userAgent.toUpperCase();

  if(1+v.indexOf('MSIE')){var Xadic=10;var Yadic=29;}	//IE

  else{var Xadic=18;var Yadic=37;}	//Netscape e outros Mozilla

  left+=document.body.scrollLeft;top+=document.body.scrollTop;	//compensa scroll X/Y

  var s='<iframe scrolling=no frameborder=0 name=iframePOP ID=iframePOP style=z-index:210;position:absolute;left:'+left+';top:'+top+';width:'+(tamx+Xadic)+'px;height:'+(tamy+Yadic)+'px src=popup.php?src='+escape(src)+'&title='+escape(title)+'&tamy='+(tamy+Yadic)+'><\/iframe>';

  rewriteOverlayDiv(s);

  return void(0);

}



function fechaIf(){

  if(sBrowser=='NS')window.parent.parent.document.getElementById("iframePOP").style.visibility='hidden';

  else window.parent.parent.document.all.iframePOP.style.visibility='hidden';

  window.parent.document.getElementById("iframeInt").src='ChatVazio.htm';

}



// Overlay: escreve no div abaixo com a página já carregada

try{document.write("<div id=overlay name=overlay></div>");}catch(e){}



var overlay=null;

function findOverlayRef(){

  if( document.layers ){ //Netscape layers

    return document.layers["overlay"];}

  if( document.getElementById ){ //DOM; IE5, NS6, Mozilla, Opera

    return document.getElementById("overlay");}

  if( document.all ){ //Proprietary DOM; IE4

    return document.all["overlay"];}

  if( document["overlay"] ){ //Netscape alternative

    return document["overlay"];}

  return false;

}

function setupOverlay(){

  if((obj=findOverlayRef())){

    overlay=new Object();

    overlay.div=obj;

    overlay.px=document.childNodes?'px':0;

    overlay.style=obj.style?obj.style:obj;

    return true;

  }

  return false;

}

function rewriteOverlayDiv( s ){

  if( typeof( overlay.div.innerHTML )!='undefined' ){

    overlay.div.innerHTML=s;

  } else {

    if( overlay.div.document && overlay.div.document!=window.document ){

      overlay.div.document.open();

      overlay.div.document.write(s);

      overlay.div.document.close();

    }

  }

}



function moveOverlay(t,l){

  if(!overlay){ if(!setupOverlay()) return false;}

  overlay.style.left=l + overlay.px;

  overlay.style.top=t + overlay.px;

  return false;

}

function sizeOverlay(h,w){

  if(!overlay){ if(!setupOverlay()) return false;}

  if( overlay.style.resizeTo ) overlay.style.resizeTo( w, h );

  overlay.style.width=w + overlay.px;

  overlay.style.pixelWidth=w;

  overlay.style.height=h + overlay.px;

  overlay.style.pixelHeight=h;

  return false;

}







var DIF_dragging=false;

var DIF_iframeBeingDragged="";

var DIF_iframeObjects=new Object();

var DIF_iframeWindows=new Object();

var DIF_iframeMouseDownLeft=new Object();

var DIF_iframeMouseDownTop=new Object();

var DIF_pageMouseDownLeft=new Object();

var DIF_pageMouseDownTop=new Object();

var DIF_handles=new Object();

var DIF_highestZIndex=210;

var DIF_raiseSelectedIframe=false;

var DIF_allowDragOffScreen=false;



bringSelectedIframeToTop(true);



function bringSelectedIframeToTop(val){DIF_raiseSelectedIframe=val;}



function allowDragOffScreen(val){DIF_allowDragOffScreen=val;}



function addHandle(o,win){

  if(arguments.length==2 && win==window){

    var p=win;

    while(p=p.parent){

      if(p.addHandle){p.addHandle(o,win,true);return;}

      if(p==win.top){return;}

      }

    return;

  }

  var topRef=win;

  var topRefStr="window";

  while(topRef.parent && topRef.parent!=window){

    topRef=topRef.parent;

    topRefStr=topRefStr + ".parent";

  }

  if (typeof(win.DIF_mainHandlersAdded)=="undefined" || !win.DIF_mainHandlersAdded){

    with (win){ 

      eval("function OnMouseDownHandler(evt){ if(typeof(evt)=='undefined'){evt=event;}"+topRefStr+".parent.DIF_begindrag(evt, "+topRefStr+") }");

      eval("document.onmousedown=OnMouseDownHandler;");

      eval("function OnMouseUpHandler(evt){ if(typeof(evt)=='undefined'){evt=event;}"+topRefStr+".parent.DIF_enddrag(evt, "+topRefStr+") }");

      eval("document.onmouseup=OnMouseUpHandler;");

      eval("function OnMouseMoveHandler(evt){ if(typeof(evt)=='undefined'){evt=event;}"+topRefStr+".parent.DIF_iframemove(evt, "+topRefStr+") }");

      eval("document.onmousemove=OnMouseMoveHandler;");

      win.DIF_handlersAdded=true;

      win.DIF_mainHandlersAdded=true;

      }

    }

  if (typeof(window.DIF_handlersAdded)!="undefined" || !window.DIF_handlersAdded){

    eval("function OnMouseMoveHandler(evt){ if(typeof(evt)=='undefined'){evt=event;}DIF_mouseMove(evt, window) }");

    eval("document.onmousemove=OnMouseMoveHandler;");

    window.DIF_handlersAdded=true;

    }

  o.style.cursor="arrow";

  var name=DIF_getIframeId(topRef);

  if (DIF_handles[name]==null){

    DIF_handles[name]=new Array();

    DIF_iframeMouseDownLeft[name]=0;

    DIF_iframeMouseDownTop[name]=0;

    DIF_pageMouseDownLeft[name]=0;

    DIF_pageMouseDownTop[name]=0;

    }

  DIF_handles[name][DIF_handles[name].length]=o;

  }



function DIF_getEventPosition(evt){

  var pos=new Object();

  pos.x=0;

  pos.y=0;

  if (!evt){

    evt=window.event;

    }

  if (typeof(evt.pageX) == 'number'){

    pos.x=evt.pageX;

    pos.y=evt.pageY;

  }

  else {

    pos.x=evt.clientX;

    pos.y=evt.clientY;

    if (!top.opera){

      if ((!window.document.compatMode) || (window.document.compatMode == 'BackCompat')){

        pos.x += window.document.body.scrollLeft;

        pos.y += window.document.body.scrollTop;

      }

      else {

        pos.x += window.document.documentElement.scrollLeft;

        pos.y += window.document.documentElement.scrollTop;

      }

    }

  }

  return pos;

}



function DIF_getIframeId(win){

  var iframes=document.getElementsByTagName("IFRAME");

  for (var i=0; i<iframes.length; i++){

    var o=iframes.item(i);

    var w=null;

    if (o.contentWindow){

      // For IE5.5 and IE6

      w=o.contentWindow;

      }

    else if (window.frames && window.frames[o.id].window){

      w=window.frames[o.id];

      }

    if (w == win){

      DIF_iframeWindows[o.id]=win;

      DIF_iframeObjects[o.id]=o;

      return o.id; 

      }

    }

  return null;

  }



function DIF_getObjectXY(o){

  var res=new Object();

  res.x=0; res.y=0;

  if (o != null){

    res.x=o.style.left.substring(0,o.style.left.indexOf("px"));

    res.y=o.style.top.substring(0,o.style.top.indexOf("px"));

    }

  return res;

  }



function getSrcElement(e){

  var tgt=e.target;

  while (tgt.nodeType != 1){ tgt=tgt.parentNode;}

  return tgt;

  }



function isHandleClicked(handle, objectClicked){

  if (handle==objectClicked){ return true;}

  while (objectClicked.parentNode != null){

    if (objectClicked==handle){

      return true;

      }

    objectClicked=objectClicked.parentNode;

    }

  return false;

  }

  

function DIF_begindrag(e, win){

  var iframename=DIF_getIframeId(win);

  if (iframename==null){ return;}

  if (DIF_handles[iframename]==null || DIF_handles[iframename].length<1)return;

  var isHandle=false;

  var t=e.srcElement || getSrcElement(e);

  for(var i=0; i<DIF_handles[iframename].length; i++){

    if(isHandleClicked(DIF_handles[iframename][i],t)){

      isHandle=true;

      break;

      }

    }

  if(!isHandle)return false;

  DIF_iframeBeingDragged=iframename;

  if (DIF_raiseSelectedIframe)DIF_iframeObjects[DIF_iframeBeingDragged].style.zIndex=DIF_highestZIndex++;

  DIF_dragging=true;

  var pos=DIF_getEventPosition(e);

  DIF_iframeMouseDownLeft[DIF_iframeBeingDragged]=pos.x;

  DIF_iframeMouseDownTop[DIF_iframeBeingDragged]=pos.y;

  var o=DIF_getObjectXY(DIF_iframeObjects[DIF_iframeBeingDragged]);

  DIF_pageMouseDownLeft[DIF_iframeBeingDragged]=o.x - 0 + pos.x;

  DIF_pageMouseDownTop[DIF_iframeBeingDragged]=o.y -0 + pos.y;

  }



function DIF_enddrag(e){

  DIF_dragging=false;

  DIF_iframeBeingDragged="";

  }



function DIF_mouseMove(e){

  if (DIF_dragging){

    var pos=DIF_getEventPosition(e);

    DIF_drag(pos.x - DIF_pageMouseDownLeft[DIF_iframeBeingDragged] , pos.y - DIF_pageMouseDownTop[DIF_iframeBeingDragged]);

    }

  }



function DIF_iframemove(e){

  if (DIF_dragging){

    var pos=DIF_getEventPosition(e);

    DIF_drag(pos.x - DIF_iframeMouseDownLeft[DIF_iframeBeingDragged] , pos.y - DIF_iframeMouseDownTop[DIF_iframeBeingDragged]);

    }

  }



function DIF_drag(x,y){

  var o=DIF_getObjectXY(DIF_iframeObjects[DIF_iframeBeingDragged]);

  var newPositionX=o.x-0+x;

  var newPositionY=o.y-0+y;

  if (!DIF_allowDragOffScreen){

    if (newPositionX < 0){ newPositionX=0;}

    if (newPositionY < 0){ newPositionY=0;}

    }

  DIF_iframeObjects[DIF_iframeBeingDragged].style.left=newPositionX + "px";

  DIF_iframeObjects[DIF_iframeBeingDragged].style.top =newPositionY + "px";

  DIF_pageMouseDownLeft[DIF_iframeBeingDragged] += x;

  DIF_pageMouseDownTop[DIF_iframeBeingDragged] += y;

  }

