//Funcao Habilita/Desanilita Itens Seminovos
function seminovosTradePictures(itemId, itemNome){
	for(i=1; i <=5; i++){
		$('#foto'+itemId+'_'+i).css('display','none');	
		$('#btFotos'+itemId+'_'+i).removeClass('lightBoxSeminovosContentPagOn');
		$('#btFotos'+itemId+'_'+i).addClass('lightBoxSeminovosContentPagOff');
	}
	
	$('#foto'+itemId+'_'+itemNome).css('display','block');
	$('#btFotos'+itemId+'_'+itemNome).addClass('lightBoxSeminovosContentPagOn');
}

//Funcao Habilita/Desanilita Itens Lifestyle
function lifestyleTradePictures(itemId, itemNome){
	for(i=1; i <=5; i++){
		$('#foto'+itemId+'_'+i).css('display','none');	
		$('#btFotos'+itemId+'_'+i).removeClass('lightBoxLifestyleContentPagOn');
		$('#btFotos'+itemId+'_'+i).addClass('lightBoxLifestyleContentPagOff');
	}
	
	$('#foto'+itemId+'_'+itemNome).css('display','block');
	$('#btFotos'+itemId+'_'+itemNome).addClass('lightBoxLifestyleContentPagOn');
}

//Funcao Habilita/Desanilita Itens Lifestyle
function lifestyleItens(itemLifestyle){
	var checks = document.getElementById('prod'+itemLifestyle);

	if (checks.checked) {
		$('#btSaiba'+itemLifestyle).css('display','none');
		$('#BoxItens'+itemLifestyle).css('display','block');
	} else {
		$('#btSaiba'+itemLifestyle).css('display','block');
		$('#BoxItens'+itemLifestyle).css('display','none');
	}

}

//Funcao Monta Menu Family
function builderMenuLeftFamily(itemMenu,totalItens){
	for(i=1; i <=totalItens; i++){
			if(i != itemMenu){
				$('#itemMenuCarros'+i).css('display','none');
				$('#itemMenuFamilia'+i).fadeIn("slow", function() {
				})			
			} else {
				$('#itemMenuFamilia'+i).fadeOut("slow", function() {
					$('#itemMenuCarros'+itemMenu).fadeIn("slow", function() {
						$('#itemMenuFamilia'+i).css('display','none');
						$('#itemMenuCarros'+i).css('display','block');
					})
				})				
				
			}
	}
	/*if($('#itemMenuFamilia'+itemMenu).css('display')=='block'){

		$('#itemMenuFamilia'+itemMenu)
		.fadeOut('slow', function() {
			//$(this).remove();
			$('#itemMenuFamilia'+itemMenu).css('display','none');
			$('#itemMenuCarros'+itemMenu).fadeIn('slow', function() {
				
			})
			
	});*/

	
}


//Funcao Monta Menu
function builderMenu(itemMenu,timetoopen){
	if($('#subMenus').css('display')=='block'){
		$('#subMenuModelos').css('display','none');
		$('#subMenuServicos').css('display','none');
		$('#subMenuSeminovos').css('display','none');
		$('#subMenuLifestyle').css('display','none');
		$('#'+itemMenu).css('display','block');
	}else{
		$('#subMenuModelos').css('display','none');
		$('#subMenuServicos').css('display','none');
		$('#subMenuSeminovos').css('display','none');
		$('#subMenuLifestyle').css('display','none');
		$('#'+itemMenu).css('display','block');

		$('#subMenus').animate({
			fontColor: "#000000",
			height: 'toggle'
			//opacity: 'toggle'
			}, timetoopen, 'linear', function() {
				$('#subMenuHidden').css('display','block');
		});
	}
}

function closeMenu(){
	$('#subMenuHidden').css('display','none');
	
	if($('#subMenus').css('display')=='block'){	
		$('#subMenus').animate({
			fontColor: "#000000",
			height: 'toggle'
			//opacity: 'toggle'
			}, 300, 'linear', function() {
				
		});
	}
}


//Funcao Load Ajx
function showLoadAjax(){
	$('body').css('overflow-x', 'hidden'); // hide scrollbars!
	
	$('<div id="loadAjax"></div>')
		.css('position', 'absolute')
		.css('top', $(document).scrollTop())
		.css('opacity', '0.9')
		.css('top', '0')
		.css('left', '0')
		//.css('width', $(window).width() + 'px')
		//.css('height', $(window).height() + 'px')
		.css('width', '100%')
		.css('height', $(document).height() + 'px')
		.css('backgroundImage', 'url(_img/ajax_loader.gif)')
		.css('backgroundRepeat', 'no-repeat')
		.css('backgroundPosition', 'center 30%')
		.css('backgroundColor', '#000')
		.css('z-index', '9999')
		
			
		.fadeIn('slow', function() {
			//positionSoulLightBox(itemLightBox, lightWidth, lightHeight);
		})
		
		/*	
		.click(function() {
			removeLoadAjax();
		})
		*/
		.appendTo('body');
		
}
function removeLoadAjax() {
	$('#loadAjax')
		.fadeOut('slow', function() {
			$(this).remove();
	});
}


//Funcao Soul Lightbox
function showSoulLightBox(itemLightBox, lightWidth, lightHeight){
	$('body').css('overflow-x', 'hidden'); // hide scrollbars!
	
	$('<div id="overlay"></div>')
		.css('position', 'absolute')
		.css('top', $(document).scrollTop())
		.css('opacity', '0.7')
		.css('top', '0')
		.css('left', '0')
		//.css('width', $(window).width() + 'px')
		//.css('height', $(window).height() + 'px')
		.css('width', '100%')
		.css('height', $(document).height() + 'px')
		.css('background', '#000')
		.css('z-index', '9998')
			
		.fadeIn('slow', function() {
			$('#'+itemLightBox).fadeIn("slow");
			positionSoulLightBox(itemLightBox, lightWidth, lightHeight);
		})
			
		.click(function() {
			removeSoulLightBox(itemLightBox);
		})
			
		.appendTo('body');
		
		if($('#overlay').css('display')=='block'){
			$(window).resize(function() {
				resizeSoulLightBox(itemLightBox, lightWidth, lightHeight);
			})
		}
}


function resizeSoulLightBox(itemLightBox, lightWidth, lightHeight) {
	var top = ($(window).height() - lightHeight) / 2;
	var left = ($(window).width() - lightWidth) / 2;
	$('#'+itemLightBox)
		//.css('position', 'absolute')
		//.css('z-index', '9999')
		//.css('width', lightWidth + 'px')
		//.css('height', lightHeight + 'px')
		.css('top', top + $(document).scrollTop())
		.css('left', left);
		//.fadeIn();
}

function positionSoulLightBox(itemLightBox, lightWidth, lightHeight) {
	var top = ($(window).height() - lightHeight) / 2;
	var left = ($(window).width() - lightWidth) / 2;
	$('#'+itemLightBox)
		.css('position', 'absolute')
		.css('z-index', '9999')
		.css('width', lightWidth + 'px')
		.css('height', lightHeight + 'px')
		.css('top', top + $(document).scrollTop())
		.css('left', left)
		.fadeIn();
}

function removeSoulLightBox(itemLightBox) {
	$('#'+itemLightBox).css('display','none');	
	$('#overlay')
		.fadeOut('slow', function() {
			//$('body').css('overflow-y', 'scroll'); // show scrollbars!
			$(this).remove();
	});
}


//formulario

function hasOptions(obj){if(obj!=null && obj.options!=null){return true;}return false;}
function moveSelectedOptions(from,to){if(arguments.length>3){var regex = arguments[3];if(regex != ""){unSelectMatchingOptions(from,regex);}}if(!hasOptions(from)){return;}for(var i=0;i<from.options.length;i++){var o = from.options[i];if(o.selected){if(!hasOptions(to)){var index = 0;}else{var index=to.options.length;}to.options[index] = new Option( o.text, o.value, false, false);}}for(var i=(from.options.length-1);i>=0;i--){var o = from.options[i];if(o.selected){from.options[i] = null;}}if((arguments.length<3) ||(arguments[2]==true)){sortSelect(from);sortSelect(to);}from.selectedIndex = -1;to.selectedIndex = -1;}
	
function ismaxlength(obj, teste, mlength) {
	//var mlength=obj.getAttribute? parseInt(obj.getAttribute("maxlength")) : ""
	if (obj.getAttribute && obj.value.length>mlength)
		obj.value=obj.value.substring(0,mlength)
	if(arguments[1]){
		arguments[1].innerHTML = mlength - obj.value.length;
	}
}

// Javascript library for form validation

var blnIsNetscape=eval(navigator.appName=="Netscape");
if (blnIsNetscape) document.captureEvents(Event.KEYPRESS);

arrSettings=new Array();
arrRules=new Array();

function set(objField,strRules,strName) {  
	arrSettings[arrSettings.length]=new Array(objField,strRules,strName);
}

function verifyForm(objForm) { //Function that verifies datatype consistence and other rules, defined by the set() function, of a form. Returns true if the form is ok to be submitted, false otherwise
	loadSettings(); //Just executes the set() statements, which are defined on the page
	for (intField=0;intField<arrSettings.length;intField++) { //Go through all form items
			arrRules=arrSettings[intField][1].split(";"); //The rules for a field are in an array containing fieldobject,rules_separated_by_commas. Split the rules.
			for (intRule=0;intRule<arrRules.length;intRule++) { //Go through the rules...
			
				strRule=trim(arrRules[intRule]);
				
				if (strRule.indexOf(":")>-1) { //A kind of rule that has parameters, get its name and value
					strRuleName=strRule.split(":")[0];
					
					strRuleValue=strRule.split(":")[1];
					
				}
				else {
					strRuleName=strRule;
					
					strRuleValue="";
				}

				switch (strRuleName) { //Switch the type of rule
					case "required":
						if (getFieldValue(arrSettings[intField][0]).replace(" ","")=="") {
							alert("O campo " + arrSettings[intField][2] + " é de preenchimento obrigatório");
							//alert("O campo " + getFieldName(arrSettings[intField][0]) + " é de preenchimento obrigatório");
							arrSettings[intField][0].focus();
							return(false);
						}
						break;
					case "email":
						if (!verifyMail(trim(getFieldValue(arrSettings[intField][0])),'E-mail inválido')) {arrSettings[intField][0].focus(); return(false);}
						break;
					//In this case, "Name" parameter will be used to pass the acceptable file types
					case "file":
						if (!checkFileType(arrSettings[intField][0],strRuleValue)) return(false);
						break;
					case "length":
						if (!verifyLength(strRuleValue,strRuleValue,arrSettings[intField][0],arrSettings[intField][2])) return(false);
						break;
					case "lengthRange":
						intMinLength=strRuleValue.split("~")[0];
						intMaxLength=strRuleValue.split("~")[1];
						if (!verifyLength(intMinLength,intMaxLength,arrSettings[intField][0],arrSettings[intField][2])) return(false);
						break;
					case "lengthMin":
						if (!verifyLength(strRuleValue,"",arrSettings[intField][0],arrSettings[intField][2])) return(false);
						break;
					case "lengthMax":
						if (!verifyLength("",strRuleValue,arrSettings[intField][0],arrSettings[intField][2])) return(false);
						break;
					default:
						alert("Warning: rule " + strRuleName + " of unknown type");
          case "compare":
           if (getFieldValue(eval(strRuleValue))!=getFieldValue(arrSettings[intField][0]))
            {
              alert("Por favor, o campo Senha e confirmação de senha deverão conter os mesmos dados.");
              arrSettings[intField][0].focus();
              return(false);
            }
						break;
					//default:
					//alert("Warning: rule " + strRuleName + " of unknown type");
				}
			}
			//Done with the rules, now check datatypes
			if (!verifyDataType(arrSettings[intField][0],arrSettings[intField][2])) return(false);
	} //Fields loop
	return(true);
}

function verifyDataType(objField,strLabel) {
	strDataType=getFieldType(objField);
	strFieldValue=getFieldValue(objField);
	switch (strDataType) {
		case "bte":
			if (isNaN(strFieldValue)) {
				alert("O campo " + strLabel + " deve conter um valor numérico");
				objField.focus();
				return(false);
			}
			break;
		case "int":
			if (isNaN(strFieldValue)) {
				alert("O campo " + strLabel + " deve conter um valor numérico");
				objField.focus();
				return(false);
			}
			break;
		case "lng":
			if (isNaN(strFieldValue)) {
				alert("O campo " + strLabel + " deve conter um valor numérico");
				objField.focus();
				return(false);
			}
			break;
		case "dbl":
			if (isNaN(strFieldValue.replace(",","."))) {
				alert("O campo " + strLabel + " deve conter um valor numérico");
				objField.focus();
				return(false);
			}
			break;
		case "cur":
			strDblValue=strFieldValue.replace(".","");
			strDblValue=strDblValue.replace(",",".");
			if (isNaN(strDblValue)) {
				alert("O campo " + strLabel + " deve conter um valor numérico (formato aceito: 88,88)");
				objField.focus();
				return(false);
			}
			break;
		case "dat":
			if (!verifyDate(objField)) return(false);
			break;
		default:
	}
	return(true);
}

function verifyLength(intMinLength,intMaxLength,objField,strLabel) { //Check the size of a field's value
	strFieldValue=getFieldValue(objField);
	intLength=strFieldValue.length;
	if (intMinLength=="" || intMinLength==null) { //Just max
		if (intLength>intMaxLength) {
			alert("O campo " + strLabel + " pode conter no máximo " + intMaxLength + " caracteres");
			objField.focus();
			return(false);
		}
	}
	else if (intMaxLength=="" || intMaxLength==null) { //Just min
		if (intLength<intMinLength) {
			alert("O campo " + strLabel + " deve conter no mínimo " + intMinLength + " caracteres");
			objField.focus();
			return(false);
		}
	}
	else if (intMinLength==intMaxLength) { //Fixed value
		if (intLength!=intMinLength) {
			alert("O campo " + strLabel + " deve conter " + intMinLength + " caracteres");
			objField.focus();
			return(false);
		}
	}
	else { //Range
		if (strValue.length<intMinLength || strValue.length>intMaxLength) {
			alert("O campo " + strLabel + " deve conter no mínimo " + intMinLength + " e no máximo " + intMaxLength + " caracteres");
			objField.focus();
			return(false);
		}
	}	
	return(true);
}

function getFieldValue(objField) { //Just cause combos don't have a value in Netscape
	//alert(objField)
	if (objField.type=="select-one") return (objField.options[objField.selectedIndex].value);
	else return(objField.value);
}

function getFieldType(objField) { //Just return the three first characters of the field's name
	return(objField.name.substr(0,3));
}

function getFieldName(objField) { //Just return the three first characters of the field's name
	return(objField.name);
}

function maskField(objField) { //Avoid invalid chars from being typed on a field (IE only)
	intKeyCode=event.keyCode;
	strTypedChar=String.fromCharCode(intKeyCode);
	if (!verifyField(strTypedChar))	return(false);
	return(true);
}

//objField --> form field to be validated;
//strFileTypes --> acceptable types of file separeted by pipes ('gif|jpg|bmp').
function checkFileType(objField,strFileTypes) {
	var strValue = objField.value;
	var strSuffix = strValue.substr(strValue.lastIndexOf('.')+1);
	var arrFileTypes = strFileTypes.split('|');
	var intField;
	var intResult = 0;
	for (intField=0;intField<arrFileTypes.length;intField++) {
		if(strSuffix!=arrFileTypes[intField]) {
			intResult++;
		}
	}
	if(intResult==arrFileTypes.length) {
		alert("Tipo de arquivo inválido!");
		objField.focus();
		return(false);
	} else {
		return(true);
	}
}

function verifyMail(strEmail,strErrorMsg) {
	if (strEmail=='') return(true);
	if (!strErrorMsg) strErrorMsg="E-mail inválido"; //Use the default error message if nothing is given
	strValidChars="@abcdefghijklmnopqrstuvxywzABCDEFGHIJKLMNOPQRSTUVXYWZ0123456789-_."; //Characters that an email can contain
	arrBoundaryChars=new Array();
	for (intPos=0;intPos<strEmail.length;intPos++) { //Check if all characters are valid
		strThisChar=strEmail.substr(i,1);
		if (strValidChars.indexOf(strThisChar)==-1) {
			alert(strErrorMsg);
			return(false);
		}
		if (strThisChar=="@" || strThisChar==".") { //Feed the BoundaryChars array
			arrBoundaryChars[arrBoundaryChars.length]=parseInt(intPos);
		}		
	}
	for (intPos=0;intPos<arrBoundaryChars.length;intPos++) { //Check if dots and ats are not in conflict
		intThisItem=arrBoundaryChars[i]
		intNextItem=(i==arrBoundaryChars.length) ? 0 : arrBoundaryChars[i+1]
		if (intThisItem==0 || intThisItem==strEmail.length) {
			alert(strErrorMsg);
			return(false);
		}
		if (intThisItem+1==intNextItem) {
			alert(strErrorMsg);
			return(false);
		}
	}
		
	intFirstAtIndex=strEmail.indexOf("@");
	intLastAtIndex=strEmail.lastIndexOf("@");
	intFirstDotIndex=strEmail.indexOf(".");
	intLastDotIndex=strEmail.lastIndexOf(".");
	
	if (intFirstAtIndex!=intLastAtIndex || intFirstAtIndex==-1 || intFirstDotIndex==-1 || intLastDotIndex<intFirstDotIndex) {
		alert(strErrorMsg);
		return(false);
	}
	return(true); //If it got here, it's all ok (I hope)
}

function verifyDate(objField) {
	strDate=getFieldValue(objField);
	if (strDate.indexOf("/")==strDate.lastIndexOf("/")){ // se houver menos que duas barras caia fora
		//alert("data inválida")
		return(false)
	}
	day=strDate.substr(0,strDate.indexOf("/"))
	month=strDate.substr(strDate.indexOf("/")+1,strDate.lastIndexOf("/")-strDate.indexOf("/")-1)
	year=strDate.substr(strDate.lastIndexOf("/")+1,strDate.length-strDate.lastIndexOf("/")-1)
	if (isNaN(day) || isNaN(month) || isNaN(year)) {
		//alert("data inválida. formato aceito: dd/mm/aaaa")
		return(false)
	}
	if (day<1 || day>31 || month<1 || month>12 || year<1800 || year>2200) {
		//alert("data inválida")
		return(false)
	}
	return(true)
}

//To do: re-write the date validation and add more rules

function trim(str) {
	var startIndex,endIndex,returnValue
	for (i=0;i<str.length;i++) {
		atChar=str.substring(i,1)
		if (atChar!=" " && atChar!="\n" && atChar!="\r" && atChar!="\t") {
			startIndex=i
			break
		}
	}
	for (i=str.length-1;i>=0;i--) {
		atChar=str.substring(i,1)
		if (atChar!=" " && atChar!="\n" && atChar!="\r" && atChar!="\t") {
			endIndex=i
			break
		}
	}
	return(str.substring(startIndex,endIndex+1))
}





/*
$(document).ready(function(){
  $('a.lightbox').click(function(e) {
    $('body').css('overflow-y', 'hidden'); // hide scrollbars!
    
    $('<div id="overlay"></div>')
      .css('top', $(document).scrollTop())
      .css('opacity', '0')
      .animate({'opacity': '0.5'}, 'slow')
      .appendTo('body');
      
    $('<div id="lightbox"></div>')
      .hide()
      .appendTo('body');
      
    $('<img />')
      .attr('src', $(this).attr('href'))
      .load(function() {
        positionLightboxImage();
      })
      .click(function() {
        removeLightbox();
      })
      .appendTo('#lightbox');
    
    return false;;
  });
});

function positionLightboxImage() {
  var top = ($(window).height() - $('#lightbox').height()) / 2;
  var left = ($(window).width() - $('#lightbox').width()) / 2;
  console.log("The calculated position is:");
  console.log(top,left);
  $('#lightbox')
    .css({
      'top': top + $(document).scrollTop(),
      'left': left
    })
    .fadeIn();
  console.log('A jQuery selection:');
  console.log($('#lightbox'));
}

function removeLightbox() {
  $('#overlay, #lightbox')
    .fadeOut('slow', function() {
      $(this).remove();
      $('body').css('overflow-y', 'auto'); // show scrollbars!
    });
}

*/



