//Fix das máscaras e placeholders dos formulários
function fixMasksPlace()
{
	$('[placeholder]').placehold();

	$('[mask]').bind('focus', function(e){
		$(this).unmask().mask($(this).attr('mask'), {placeholder: "_"});
	}).bind('focusout', function(){
		$('[placeholder]').placehold();
	});
}


//Redirecionamento via javascript, usado bastante nos menus em flash
function redirect(where)
{
	window.location = BASE_URL + where;
}



//Tratar resize da janela, pra o rodapé ficar sempre em baixo
function resize()
{
	$("#content").css({'min-height' : $(window).height()-$("#header").height()-$("#footer").height()+'px'});

	$(window).resize(function(e){
		e.stopImmediatePropagation();
		resize();
	});
}


//Pré-recarregar alguma imagem
function preloadImage(caminho)
{
	$("<img />")
	.attr('src', caminho)
	.load(function(){
		$(this).remove();
	});
}



//Igual o ucFirst do PHP
function ucFirst(string)
{
	return string.substring(0, 1).toUpperCase() + string.substring(1).toLowerCase();
}


//Remove acento de uma string
function removeAcento(text)
{
	text = text.replace(new RegExp('[ÁÀÂÃ]','gi'), 'A');
	text = text.replace(new RegExp('[ÉÈÊ]','gi'), 'E');
	text = text.replace(new RegExp('[ÍÌÎ]','gi'), 'I');
	text = text.replace(new RegExp('[ÓÒÔÕ]','gi'), 'O');
	text = text.replace(new RegExp('[ÚÙÛ]','gi'), 'U');
	text = text.replace(new RegExp('[Ç]','gi'), 'C');
	text = text.toLowerCase();
	return text;
}



//Insere os flashs na página
function fixFlashs()
{

	/*

	<?php
		$id = "IdDoSwf";
		$params = "";
		$caminho = "publish/";
		list($width, $height) = getimagesize($caminho.$id.".swf");
		$html = $width."!#".$height."!#".$params."!#".$caminho;
	?>

	<div class="flash" id="<?=$id?>"><?=$html?></div>

	*/


	$('div.flash').each(function(){
		var atributos = $(this).html().split('!#');
		var dir = BASE_URL+atributos[3];
		var attrs = "baseURL="+BASE_URL+"&"+atributos[2];
		var swf = $(this).attr('id').replace('flash-', '');

		$(this).flash({
			swf: dir + swf +".swf",
			id: swf + "-swf",
			width: '100%',
			height: '100%',
			wmode: "transparent",
			flashvars: attrs,
			allowScriptAccess: "sameDomain",
			hasVersion: 10,
			hasVersionFail: function(){
				redirect('noflash');
			}
		});

		$(this).css({'width':atributos[0]+'px', 'height':atributos[1]+'px'}).removeClass('flash');
	})

}





//FadeIn e FadeOut para o IE, usar quando for dar fade em algo com PNG Transparente
$.fn.extend({
	fadeInIE: function(duration, callback)
	{
		var elm = $(this);

		if($.browser.msie){
			elm.show();

			if(typeof(callback) == 'function'){
				setTimeout(callback, 100);
			}


		} else {
			elm.fadeIn(duration, callback);
		}

		return elm;
	},

	fadeOutIE: function(duration, callback)
	{
		var elm = $(this);

		if($.browser.msie){
			elm.hide();

			if(typeof(callback) == 'function'){
				setTimeout(callback, 100);
			}

		} else {
			elm.fadeOut(duration, callback);
		}

		return elm;
	}

})







//Reseta os formulários, e mantém o placeholder
function formReset(form)
{
	form.find('select').val('');
	form.find('select[name=cidade]').html('<option value="">Cidade*</option>');
	form.find('[placeholder]').each(function() {
		$(this).val($(this).attr('placeholder'));
	});
}




//Função de validação de formulários
function validate(scope, errorSelector)
{
	var valid;
	var scopeElm = $(scope);

	var selectorError = errorSelector == undefined ? ".errormessage" : errorSelector;
	var error = scopeElm.find(selectorError);

	scopeElm.find('.error').removeClass('error');
	error.text('');

	scopeElm.find('[class^="required"], [class~="required"]').each(function () {

			var self = $(this);
			var value = self.val();
			var className = self.attr('class');
			var placeholderValue = self.attr('placeholder');
			valid = true;

			rulesParsing = className;
			rulesRegExp = /\[(.*)\]/;
			getRules = rulesRegExp.exec(rulesParsing);


			if(getRules != null)
			{
				str = getRules[1];
				pattern = /\W+/;
				result = str.split(pattern);

				switch(result[0])
				{
					case "email":
							// expressão para validar o email
							var pattern = new RegExp(/^[a-zA-Z0-9_\.\-]+\@([a-zA-Z0-9\-]+\.)+[a-zA-Z0-9]{2,4}$/);
							if(!pattern.test(value))
								valid = false;
						break;
					case "confirm":
							var valueToCompare = $('#' + result[1]).val();
							//console.log("Valor: '"+value+ "' Compare com: '" + valueToCompare + "' campo "+result[1]);
							if(value != valueToCompare)
								valid = false;
						break;
					case "date":
							// expressão para verificar se o campo contém somente números
							var pattern = new RegExp(/^[0-9\ ]+$/);

							if(!pattern.test(self.val()))
								valid = false;
							else
							{
								switch(result[1])
								{
									case "day":
											if(parseInt(self.val(), 10) < 1 || parseInt(self.val(), 10) > 31)
												valid = false;
										break;
									case "month":
											if(parseInt(self.val(), 10) < 1 || parseInt(self.val(), 10) > 12)
												valid = false;
										break;
									case "year":
											if(parseInt(self.val(), 10) < 1900 || parseInt(self.val(), 10) > 2011)
												valid = false;
										break;
								}
							}
						break;
				}
			}
			else
			{
				if(value == "" || value == placeholderValue)
					valid = false;
			}

			// se o campo atual não passou em uma das validações
			if(valid === false)
			{
				self.addClass('error');
				self.focus();
				error.text(self.attr('errormessage'));

				return false;
			}
			else
			{
				self.removeClass('error');

				return true;
			}

		});

		return valid;
}
