
// INIT PAGE

strFormSending 		= 'Enviando Formulário';
strFormSuccess 		= 'Formulário enviado com sucesso';
strFormError 		= 'Falha ao enviar formulário';
strFormMsgRequired 	= 'Campo obrigatório';
strFormMsgEmail 	= 'E-mail inválido';
strFormMsgDate 		= 'Data inválida';
strFormMsgTime 		= 'Hora inválida';
strFormMsgCurrency 	= 'Moeda inválida';

$(document).ready(function() 
{

	//DELAY FUNCTION
	jQuery.fn.delay = function(time,func){
		this.each(function(){
			setTimeout(func,time);
		});
		return this;
	};	

	// MENU BUILDER
	$("#ulMenu > li").append($('<ins \>'));
	$("#ulMenu > li").css("z-index","500");

	// MENU DROPDOWN
	$("#ulMenu > li").mouseenter(function() {
		$(this).attr("isOver","true");
		if ($('ul:first',this).length > 0)
		{
			$(this).addClass("liSelected");
			$('ul:first',this).css("top","34px");
			$('ul:first',this).css("left",-2);
			$('ul:first',this).css("display","block");
			$(this).css("z-index","510");
			//$('ul:first',this).width($('ul:first',this).width());
		}
	});
	$("#ulMenu > li").mouseleave(function() {
		$(this).attr("isOver","false");
		var objLi = this;
		$(objLi).css("z-index","500");
		$(this).delay(300, function() {
			if ($('ul',objLi).length > 0 && $(objLi).attr("isOver")!="true")
			{
				$('ul',objLi).css("display","none");
				$(objLi).removeClass("liSelected");
			}
		});
	});
	
	// LOAD SITE CONFIG
	$.ajax({
		url: "lib/util/ajaxSiteConfig.php", 
		data: "name=strSiteTitle", 
		success: function(strHTML) {
			eval(strHTML);
		}
	});

	// FORM PREPARE
	arrFields = $("form :input[required]");
	$(arrFields).removeAttr('required');
	$(arrFields).attr('requiredfield','true');
	
	// FORM E-MAIL ACTIONS
	$("#divContent form[method='get'][noAjax!='true']").submit(function(){
		bolValidation = formSubmit(this);

		if (bolValidation)
		{
			$.fancybox({ content: strFormSending, showCloseButton: false });

			strAjax = "strEmailDestination=" + escape($(this).attr('action')) + "&strEmailSubject=" + escape($(this).attr('name'));
			$(":input", this).each(function(){
				if ($(this).attr('type') != 'submit' && $(this).attr('type') != 'reset' && $(this).attr('type') != 'button')
				{
					strAjax += "&" + escape($(this).attr('name')) + "=" + escape($(this).val());
				}
			});

			$.ajax({
				type: "POST",
				url: "lib/util/ajaxSendForm.php",
				data: strAjax,
				success: function(strHTML) {
					if (strHTML == 'true')
					{
						$.fancybox({ content: strFormSuccess });
					}
					else
					{
						$.fancybox({ content: strFormError  });
					}
				},
				error: function() {
					$.fancybox({ content: strFormError });
				}
			});


		}
		return false;
	});

	// RTE IMAGES
	$('img[rel=rte]').each(function(){
		strSrc = $(this).attr('src');
		numWidth = $(this).attr('width');
		numHeight = $(this).attr('height');
		arrSrc = strSrc.split('upl/ckfinder/images/');
		$(this).attr('src','images/rte/'+numWidth+'x'+numHeight+'/'+arrSrc[1]);
		
		if ($(this).attr('thumb'))
		{
			$(this).attr('border','0');
			imgClone = $(this);
			$(this).wrap(
				$('<a/>')
					.attr('href','images/rte/max-'+700+'x'+500+'/'+arrSrc[1])
					.attr('title',imgClone.attr('alt'))
			)
		}
	});

	// THUMBNAIL FOR RTE IMAGES
	$('img[thumb]').parent().fancybox({
		'titleShow'			: true,
		'overlayOpacity'	: 0.8,
		'overlayColor'		: '#000',
		'type'				: 'image'
	});

	// SET MASK
	$("[mask]").each(function() 
	{
		$(this).setMask({ 
			mask : $(this).attr('mask'), 
			autoTab : false 
		});
		$(this).setMask($(this).attr('mask'));
	});

	// SIDE NEWSLETTER
	$("#divSideNewsletter form").submit(function(){
		bolValidation = formSubmit(this);

		if (bolValidation)
		{
			$.fancybox({ content: 'Enviando seu e-mail...', showCloseButton: false });

			strAjax = "email=" + escape($("#txtNewsletter").val());

			$.ajax({
				type: "POST",
				url: "lib/util/ajaxContactAdd.php",
				data: strAjax,
				success: function(strHTML) {
					if (strHTML == 'true')
					{
						$.fancybox({ content: 'E-mail cadastrado com sucesso!' });
					}
					else
					{
						$.fancybox({ content: 'Falha ao cadastrar.<br />Verifique os dados informados.' });
					}
				},
				error: function() {
					$.fancybox({ content: 'Falha ao cadastrar.<br />Verifique os dados informados.' });
				}
			});
		}

		return false;
	});

	// SIDE GALLERY
	$('#divSideGallery a img').parent().fancybox({
		'titleShow'			: true,
		'overlayOpacity'	: 0.8,
		'overlayColor'		: '#000',
		'type'				: 'image'
	});
	$('#divSideGallery .lnkMovePrevious').click(function(){
		if ($('#divSideGallery ul').attr('isMoving') != 'true')
		{
			numQtd = $('#divSideGallery ul li').length;
			numWidth = parseInt($('#divSideGallery ul li:first').outerWidth()+5);
			numLeft = $('#divSideGallery ul').position().left;
			numLeft = numLeft+numWidth;
			if (numLeft <= 0)
			{
				$('#divSideGallery ul').attr('isMoving','true');
				$('#divSideGallery ul').animate({ 
					left: numLeft + "px"
					}, 300, function(){
						$('#divSideGallery ul').attr('isMoving','false');
				});
			}
		}			
	});
	$('#divSideGallery .lnkMoveNext').click(function(){
		if ($('#divSideGallery ul').attr('isMoving') != 'true')
		{
			numQtd = $('#divSideGallery ul li').length;
			numWidth = parseInt($('#divSideGallery ul li:first').outerWidth()+5);
			numLeft = $('#divSideGallery ul').position().left;
			numLeft = numLeft-numWidth;
			if ( (numWidth*numQtd)-(numWidth*3) >= (numLeft*(-1)))
			{
				$('#divSideGallery ul').attr('isMoving','true');
				$('#divSideGallery ul').animate({ 
					left: numLeft + "px"
					}, 300, function(){
						$('#divSideGallery ul').attr('isMoving','false');
				});
			}
		}
	});

	// SIDE BANNER
	if ($('#divSideAds02 li').length > 1)
	{
		$('#divSideAds02').attr('numIndex','0');
		$('#divSideAds02 li').css('opacity','0');
		$('#divSideAds02 li:first').css('opacity','100');
	
		arrAdBanner02 = $('#divSideAds02 li');
	
		$(arrAdBanner02[0]).css('z-index','21');
		$(arrAdBanner02[0]).animate({ 
			opacity: 1
			}, 500)
		$('#divSideAds02').attr('numIndex',0);
		function rotateAdBanner02() {
			numCurrent = parseInt($('#divSideAds02').attr('numIndex'));
			numNext = (numCurrent + 1) == arrAdBanner02.length ? 0 : numCurrent + 1;
			$('#divSideAds02').attr('numIndex',numNext);
			$(arrAdBanner02[numCurrent]).css('z-index','20');
			$(arrAdBanner02[numNext]).css('z-index','21');
			$(arrAdBanner02[numCurrent]).animate({ 
				opacity: 0
				}, 500)
			$(arrAdBanner02[numNext]).animate({ 
				opacity: 1
				}, 500)
		}
		var timAdBanner02 = window.setInterval(rotateAdBanner02, 5000);
	}

	// SIDE POLL
	$("#divSidePoll form").submit(function(){
		bolValidation = formSubmit(this);

		if (bolValidation)
		{
			$.fancybox({ content: 'Enviando seu voto...', showCloseButton: false });

			strAjax = "enquete=" + escape($("#radPoll:checked").val());

			$.ajax({
				type: "POST",
				url: "lib/util/ajaxPollAdd.php",
				data: strAjax,
				success: function(strHTML) {
					if (strHTML == 'true')
					{
						$.fancybox({ content: 'Voto enviado com sucesso!' });
					}
					else
					{
						$.fancybox({ content: 'Falha ao enviar.' });
					}
				},
				error: function() {
					$.fancybox({ content: 'Falha ao enviar.' });
				}
			});
		}

		return false;
	});

});

function urlencode(str) 
{
	return escape(str).replace(/\+/g,'%252b');
}

// GENERAL FORM SUBMIT FUNCTION

function formSubmit(objForm)
{
	$bolReturn = formValidation(objForm);
			
	return $bolReturn;
}

// CHECK ALL POSSIBLE VALIDATIONS

function formValidation(objForm)
{
	var isValid = true;
	var objFirst = false;

	$(':input', $(objForm)).each(function() 
	{

		if (!formValidationRequieredField(this))
		{
			isValid = false;
			formErrorMessage(this, strFormMsgRequired);
		}
		else if (!formValidationEmail(this))
		{
			isValid = false;
			formErrorMessage(this, strFormMsgEmail);
		}
		else if (!formValidationDate(this))
		{
			isValid = false;
			formErrorMessage(this, strFormMsgDate);
		}
		else if (!formValidationTime(this))
		{
			isValid = false;
			formErrorMessage(this, strFormMsgTime);
		}
		else if (!formValidationCPF(this))
		{
			isValid = false;
			formErrorMessage(this, 'CPF inválido');
		}
		else if (!formValidationMinLength(this))
		{
			isValid = false;
			formErrorMessage(this, 'Campo deve conter ao menos '+$(this).attr('minlength')+' caracteres');
		}
		
		if (!isValid && !objFirst)
		{
			objFirst = this;
		}

	});

	if (objFirst)
	{
		$("html:not(:animated),body:not(:animated)").animate({ scrollTop: $(objFirst).offset().top-5 }, 500 );
	}

	return isValid;
}

// VALIDATION FIELDS FUNCTIONS

function formValidationRequieredField(objField)
{
	var isValid = true;

	if ($(objField).attr('requiredfield'))
	{
		if ($(objField).attr('type') == 'radio' || $(objField).attr('type') == 'checkbox')
		{
			var isChecked = false;
			$("input[name='"+$(objField).attr('name')+"']").each(function() {
				if ($(this).attr('checked')) 
				{
					isChecked = true;
				}
			});
			if ($("input[name='"+$(objField).attr('name')+"']:first")[0] == $(objField)[0]) 
			{
				isValid = isChecked;
			}
		}
		else if ($(objField).attr('type') == 'select-multiple')
		{
			if (!$(objField).val())
			{
				isValid = false;
			}
		}
		else
		{
			if (jQuery.trim($(objField).val()) == "")
			{
				isValid = false;
			}
		}
	}

	return isValid;
}
function formValidationCPF(objField)
{
	var isValid = true;

	if ($(objField).attr('validation') == 'cpf')
	{
		value = $(objField).val();
		
		value = value.replace('.','');
		value = value.replace('.','');
		cpf = value.replace('-','');
		
		while(cpf.length < 11) cpf = "0"+ cpf;
		
		var expReg = /^0+$|^1+$|^2+$|^3+$|^4+$|^5+$|^6+$|^7+$|^8+$|^9+$/
		var a = [];
		var b = new Number;
		var c = 11;
		
		for (i=0; i<11; i++)
		{
			a[i] = cpf.charAt(i);
			if (i < 9) b += (a[i] * --c);
		}


		if ((x = b % 11) < 2) { a[9] = 0 } else { a[9] = 11-x }
		
		b = 0;
		c = 11;
		
		for (y=0; y<10; y++) b += (a[y] * c--);
		
		if ((x = b % 11) < 2) { a[10] = 0; } else { a[10] = 11-x; }
		
		if ((cpf.charAt(9) != a[9]) || (cpf.charAt(10) != a[10]) || cpf.match(expReg)) isValid = false;

	}
	return isValid;
}
function formValidationRG(objField)
{
	var isValid = true;

	if ($(objField).attr('validation') == 'rg')
	{
		if ($(objField).val().length != 14)
		{
			isValid = false;
		}
		var regExp = /^[0-9]{2}\.[0-9]{3}\.[0-9]{3}-[0-9]{1}\b/;
		if (!regExp.test($(objField).val())) isValid = false;
	}
	return isValid;
}
function formValidationEmail(objField)
{
	var isValid = true;

	if ($(objField).attr('validation') == 'email')
	{
		var regExp = /^[.a-z0-9_-]{1,}@[.a-z0-9_-]{1,}\.[a-z]{2,3}(\.[a-z]{2,3})?\b/;
		if (!regExp.test($(objField).val())) isValid = false;
	}
	return isValid;
}
function formValidationDate(objField)
{
	var isValid = true;

	if ($(objField).attr('validation') == 'date')
	{
		
		if ($(objField).val().length == 0)
		{
			return true;
		}
							 
		var objRegExp = /^\d{2}(\/)\d{2}(\/)\d{4}$/
		strValue = $(objField).val();
		
		//check to see if in correct format
		if (!objRegExp.test(strValue))
		{
			return false;
		}
		else
		{
			var strSeparator = "/"; 
			var arrayDate = strValue.split(strSeparator); 
			//create a lookup for months not equal to Feb.
			var arrayLookup = { '01' : 31,'03' : 31, 
			'04' : 30,'05' : 31,
			'06' : 30,'07' : 31,
			'08' : 31,'09' : 30,
			'10' : 31,'11' : 30,'12' : 31}
			var intDay = parseInt(arrayDate[0],10); 
			
			//check if month value and day value agree
			if(arrayLookup[arrayDate[1]] != null) 
			{
				if(intDay <= arrayLookup[arrayDate[1]] && intDay != 0)
				{
					return true; //found in lookup table, good date
				}
			}
				
			//check for February (bugfix 20050322)
			var intMonth = parseInt(arrayDate[1],10);
			if (intMonth == 2) 
			{ 
				var intYear = parseInt(arrayDate[2]);
				if (intDay > 0 && intDay < 29) 
				{
					return true;
				}
				else if (intDay == 29) 
				{
					if ((intYear % 4 == 0) && (intYear % 100 != 0) || (intYear % 400 == 0)) 
					{
						// year div by 4 and ((not div by 100) or div by 400) ->ok
						return true;
					}   
				}
			}
		}  
		return false; //any other values, bad date
	}
	return isValid;
}
function formValidationTime(objField)
{
	var isValid = true;

	if ($(objField).attr('validation') == 'time')
	{
		if ($(objField).val().length == 0)
		{
			return true;
		}

		arrTime = $(objField).val().split(':');
		if (arrTime.length != 2)
		{
			isValid = false;
		}
		else if (parseInt(arrTime[0]) > 23)
		{
			isValid = false;
		}
		else if (parseInt(arrTime[1]) > 59)
		{
			isValid = false;
		}
	}
	return isValid;
}
function formValidationIntegerNonZero(objField)
{
	var isValid = true;

	if ($(objField).attr('validation') == 'integerNonZero')
	{
		if (parseInt($(objField).val()) != $(objField).val())
		{
			isValid = false;
		}
		if (parseInt($(objField).val()) <= 0)
		{
			isValid = false;
		}
	}
	return isValid;
}
function formValidationMinLength(objField)
{
	var isValid = true;

	if ($(objField).attr('minlength'))
	{
		if ($(objField).val().toString().length > 0)
		{
			if ($(objField).val().toString().length < parseInt($(objField).attr('minlength')))
			{
				isValid = false;
			}
		}
	}
	return isValid;
}

// SET ERROR MESSAGE ON A FIELD

function formErrorMessage(objItem, strMessage)
{
	formErrorMessageClear(objItem);
	if ($('#'+$(objItem).attr('spnErrorMessage')).length == 0)
	{

		var numLeft = $(objItem).position().left;
		var numTop = $(objItem).position().top;
		
		var objParent = $(objItem).parent();
		
		do 
		{
			var strSpanId = 'spnErrorMessage'+Math.round(Math.random()*10000);
		}
		while ($('#'+strSpanId).length > 0)
		
		if ($(objItem).attr('type') == 'radio' || $(objItem).attr('type') == 'checkbox')
		{
			numLeft += 5;
			$(objItem).parent().css('z-index','100');
	
			$("input[name='"+$(objItem).attr('name')+"']").attr('spnErrorMessage',strSpanId);
			$("input[name='"+$(objItem).attr('name')+"']").bind("focus click", function() {
				formErrorMessageClear(this);
			});
		}
		else
		{
			$(objItem).attr('spnErrorMessage',strSpanId);
			$(objItem).bind("focus", function() {
				formErrorMessageClear(this);
			});
		}

		$(objParent).prepend(
			$('<span/>')
			.addClass("spnErrorMessage")
			.html(strMessage)
			.attr('id',strSpanId)
			.css('top',numTop+10)
			.css('left',numLeft+10)
			.click(function() {
				formErrorMessageClear(objItem);
				$(objItem)[0].focus();
			})
		);
	}
}

// CLEAR ERROR MESSAGE ON A FIELD

function formErrorMessageClear(objItem)
{
	$('#'+$(objItem).attr('spnErrorMessage')).remove();
}

// FIELD COUNTER FUNCTION

function formFieldCounter(objItem, strCounterId)
{
	numMaxLenght = parseInt($(objItem).attr('maxlenght'));

	numLeft = numMaxLenght - $(objItem).val().length;

	$("#"+strCounterId).text('('+numLeft+' caracteres restantes)');
}

// TEXTAREA MAX LENGTH FUNCTION

function formMaxLength(objItem)
{
	numMaxLenght = parseInt(objItem.getAttribute('maxlenght'));

	strText = objItem.value;
	strText = strText.substr(0, numMaxLenght);
	
	objItem.value = strText;
}

// FIELDS SET REQUIRED

function formSetRequired(objItem, bolRequired)
{
	if (bolRequired)
	{
		$(objItem).attr('requiredfield','true');
		if ($(objItem).attr('type') == 'text' || $(objItem).attr('type') == 'password' || $(objItem).attr('type') == 'textarea')
		{
			$(objItem).css('background-color','#FFEEEE');
		}
		else if ($(objItem).attr('type') == 'select-one' || $(objItem).attr('type') == 'select-multiple')
		{
			$(objItem).css('background-color','#FFEEEE');
		}
		else if ($(objItem).attr('type') == 'radio' || $(objItem).attr('type') == 'checkbox')
		{
			$(objItem).parent().parent().css('background-color','#FFEEEE');
		}
		else if ($(objItem).attr('type') == 'file')
		{
			$(objItem).parent().css('background-color','#FFEEEE');
		}
	}
	else
	{
		$(objItem).removeAttr('requiredfield');
		if ($(objItem).attr('type') == 'text' || $(objItem).attr('type') == 'password' || $(objItem).attr('type') == 'textarea')
		{
			$(objItem).css('background-color','');
		}
		else if ($(objItem).attr('type') == 'select-one' || $(objItem).attr('type') == 'select-multiple')
		{
			$(objItem).css('background-color','');
		}
		else if ($(objItem).attr('type') == 'radio' || $(objItem).attr('type') == 'checkbox')
		{
			$(objItem).parent().parent().css('background-color','');
		}
		else if ($(objItem).attr('type') == 'file')
		{
			$(objItem).parent().css('background-color','');
		}
	}
}

