//VALIDA EMAIL
function emailCheck (emailStr) {
	var emailPat=/^(.+)@(.+)$/
	var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]"
	var validChars="\[^\\s" + specialChars + "\]"
	var quotedUser="(\"[^\"]*\")"
	var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/
	var atom=validChars + '+'
	var word="(" + atom + "|" + quotedUser + ")"
	var userPat=new RegExp("^" + word + "(\\." + word + ")*$")
	var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$")
	
	var matchArray=emailStr.match(emailPat)
	if (matchArray==null) {
		alert("O endereço de email "+emailStr+" não está correto.")
		return false
	}
	var user=matchArray[1]
	var domain=matchArray[2]
	
	if (user.match(userPat)==null) {
		// user is not valid
		alert("O nome do usuário do e-mail "+emailStr+" não parece ser válido.")
		return false
	}
	
	var IPArray=domain.match(ipDomainPat)
	if (IPArray!=null) {
		  for (var i=1;i<=4;i++) {
			if (IPArray[i]>255) {
				alert("O número do IP não é válido no e-mai "+emailStr+" !")
			return false
			}
		}
		return true
	}
	
	var domainArray=domain.match(domainPat)
	if (domainArray==null) {
		alert("O domínio do e-mail "+emailStr+" não parece estar correto.")
		return false
	}
	
	var atomPat=new RegExp(atom,"g")
	var domArr=domain.match(atomPat)
	var len=domArr.length
	if (domArr[domArr.length-1].length<2 || 
		domArr[domArr.length-1].length>3) {
	   alert("O endereço precisa terminar com 3 letras do domínio ou 2 letras do país.")
	   return false
	}
	
	if (len<2) {
	   var errStr="O endereço "+emailStr+" não contém o domínio!"
	   alert(errStr)
	   return false
	}
	
	return true;
}


// CORRIGE A EXIBIÇÃO DE PNGS TRANSPARENTE NO IE 5.5 & 6.
function correctPNG(){
   var arVersion = navigator.appVersion.split("MSIE")
   var version = parseFloat(arVersion[1])
   if ((version >= 5.5) && (document.body.filters)) 
   {
      for(var i=0; i<document.images.length; i++)
      {
         var img = document.images[i]
         var imgName = img.src.toUpperCase()
         if (imgName.substring(imgName.length-3, imgName.length) == "PNG")
         {
            var imgID = (img.id) ? "id='" + img.id + "' " : ""
            var imgClass = (img.className) ? "class='" + img.className + "' " : ""
            var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' "
            var imgStyle = "display:inline-block;" + img.style.cssText 
            if (img.align == "left") imgStyle = "float:left;" + imgStyle
            if (img.align == "right") imgStyle = "float:right;" + imgStyle
            if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle
            var strNewHTML = "<span " + imgID + imgClass + imgTitle
            + " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
            + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
            + "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>" 
            img.outerHTML = strNewHTML
            i = i-1
         }
      }
   }    
}

//exibe a div especificada por "target"
function show(target) {
	if(div=document.getElementById(target)){
		div.style.display = 'inline';
		//Ganbiarra para forçar o reflow da página
		document.body.className += '';
	}
}

//exibe a div especificada por "target" com display mode definido pelo usuario
function showAs(target, mode) {
	if(div=document.getElementById(target)){
		div.style.display = mode;
		//Ganbiarra para forçar o reflow da página
		document.body.className += '';
	}
}

//exibe o frame especificado por "target" e carrega o conteudo de uma página externa
function showFrame(target, content) {
	if(frame=document.getElementById(target)){
		frame.style.display = 'none';
		frame.src = content;
		frame.style.display = 'inline';
		//Ganbiarra para forçar o reflow da página
		document.body.className += '';
	}
}

//oculta a div especificada por "target"
function hide(target) {
	if(div=document.getElementById(target)){
		div.style.display = 'none';
		//Ganbiarra para forçar o reflow da página
		document.body.className += '';
	}
}

//oculta a div especificada por "target"
function showhide(target) {
	if(div=document.getElementById(target)){
		if(div.style.display == 'none'){
			div.style.display = 'inline';
			//Ganbiarra para forçar o reflow da página
			document.body.className += '';
		}else{
			div.style.display = 'none';
			//Ganbiarra para forçar o reflow da página
			document.body.className += '';
		}
	}
}

//oculta a div especificada por "target"
function showhideAs(target, mode) {
	if(div=document.getElementById(target)){
		if(div.style.display == 'none'){
			div.style.display = mode;
			//Ganbiarra para forçar o reflow da página
			document.body.className += '';
		}else{
			div.style.display = 'none';
			//Ganbiarra para forçar o reflow da página
			document.body.className += '';
		}
	}
}

//testa se o campo dado está vazio
function requerido(campo){
	if(document.getElementById(campo).value == ""){
		alert("Campo de preenchimento obrigatório ("+campo+")")
		return false
	}
	return true
}

//Carrega as imagens referentes ao estado over dos botões
function preloadImages(){
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=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];}}
}

//Cross browser attachEvent function
function addEvent(obj, evType, fn){ 
 if (obj.addEventListener){ 
   obj.addEventListener(evType, fn, false); 
   return true; 
 } else if (obj.attachEvent){ 
   var r = obj.attachEvent("on"+evType, fn); 
   return r; 
 } else { 
   return false; 
 } 
}

//Faz a Layer label seguir o mouse

if (document.all){}
else document.captureEvents(Event.MOUSEMOVE);
document.onmousemove=mouse;

function getPosition(e) {
    e = e || window.event || window.Event;
    var cursor = {x:0, y:0};
    if (e.pageX || e.pageY) {
        cursor.x = e.pageX;
        cursor.y = e.pageY;
    } 
    else {
        cursor.x = e.clientX + (document.documentElement.scrollLeft || document.body.scrollLeft) - document.documentElement.clientLeft;
        cursor.y = e.clientY + (document.documentElement.scrollTop || document.body.scrollTop) - document.documentElement.clientTop;
    }
    return cursor;
}

function mouse(e) {
	pos = getPosition(e);
	captionObj = document.getElementById("caption");
	if(isValidObject(captionObj)){
		captionObj.style.left = (pos.x-(captionObj.offsetWidth+10)) + 'px';
		captionObj.style.top = (pos.y-(captionObj.offsetHeight+10)) + 'px';
	}
}

function displayCaption(label){
	captionObj = document.getElementById("caption");
	captionObj.innerHTML = label;
	//captionObj.appendChild(document.createTextNode(label));
	mouse();
	captionObj.style.visibility="visible";
}

function isValidObject(objToTest) {
  if (null == objToTest) return false;
  if ("undefined" == typeof(objToTest)) return false;
  return true;
}

function hideCaption(){
	captionObj = document.getElementById("caption");
	captionObj.removeChild(captionObj.childNodes[0]);
	captionObj.style.visibility="hidden";
}

String.prototype.trim=function(){  //trim leading or trailing whitespace and extra spaces
	return this.replace(/^\s*/, "").replace(/\s*$/, "").replace(/\s{2,}/, " ");
}

function checkEmail(valor){
	if(valor==''){return true;}
	if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(valor)){return (true);}
	return (false);
}

function checaCampos(form){  //verifica o preenchimento obrigatorios dos campos antes de enviá-los
	if(!form){return false;}
	var element,enviar=true;
	for(var i=0;i<form.elements.length;i++){
		element=form.elements[i];
		if(element.className.indexOf('required')>=0){  //campo requerido
			if(element.type.toUpperCase()=='CHECKBOX'){  //se for um checkbox
				checkboxes=document.getElementsByName(element.name);
				for(var c=0;c<checkboxes.length;c++){
					if(checkboxes[c].checked){break;}
				}
				if(c<checkboxes.length){continue;}
				alert('Favor selecione pelo menos uma das opções apresentadas.');
				element.focus();
				return false;
			}
			if(element.value.length<=0){  //nao preenchido
				if(element.type.toUpperCase().indexOf('SELECT')>=0){
					alert('Favor selecione pelo menos uma opção.');
				}else{
					alert('Favor preencha o campo corretamente');
				}
				element.focus();
				enviar=false;
				break;
			}
		}
		if(element.className.indexOf('email')>=0){  //campo tipo email
			if(!checkEmail(element.value.trim())){
				alert('Favor escreva um e-mail válido.');
				element.focus();
				enviar=false;
				break;
			}
		}
	}
	return enviar;
}

addEvent(window, 'load', function(){preloadImages('images/icones/compareVeiculosOver.jpg','images/icones/compareVeiculosRemoveOver.jpg','images/icones/detalheVeiculosOver.jpg','images/icones/indiqueVeiculosOver.jpg','images/icones/listViewOver.jpg','images/icones/orcamentoVeiculosOver.jpg','images/icones/searchOver.jpg','images/icones/thumbsViewOver.jpg','images/icones/rssOver.jpg');});

addEvent(window, 'load', correctPNG);