/*
*	box3document 						- Manipulações gerais do documento
*	box3document.baseURL 				- Url base
*	box3document.fixMasks 				- Ativa o plugin de mascaras
*	box3document.fixPlaceholder 		- Ativa o plugin de placeholder
*	box3document.fixMasksPlace 			- Ativa os dois plugins informados acima
*	box3document.redirect 				- Redireciona o documento (usado bastante com o flash)
*	box3document.resizeEvent 			- Verificador do evento de resize
*	box3document.resizeWindow			- Adiciona evento de resize, que chama o box3document.resize a cada 100 milesegundos
*	box3document.resize(func)			- Método que recebe uma função com o que deve ser feito, quanto a janela sofrer resize
*	box3document.fixFlashs				- Adiciona o flash nas divs com classe 'flash', mais detalhes e exemplo no método
*/
var box3document = {
	baseURL: location.protocol+'//'+location.host+'/',
	baseFront: location.protocol+'//' + location.host + location.pathname,
	fixMasks: function(){
		$('[mask]').bind('focus', function(e){
			$(this).unmask().mask($(this).attr('mask'), {placeholder: "_"});
		}).bind('focusout', function(){
			$('[placeholder]').placehold();
		});
	},
	fixPlaceholder: function(){
		$('[placeholder]').placehold();
	},
	fixMasksPlace: function(){
		box3.document.fixMasks();
		box3.document.fixPlaceholder();
	},
	redirect: function(where){
		window.location = box3document.baseURL + where;
	},
	resizeEvent: true,
	resizeWindow: function(){
		var resizeTimer = null;
		$(window).bind('resize', function() {
			if (resizeTimer) clearTimeout(resizeTimer);
			resizeTimer = setTimeout(box3document.resize, 100);
			box3document.resizeEvent = false;
		});
	},
	resize: function(callback){
		if(box3document.resizeEvent){
			box3document.resizeWindow();
			box3document.resizeCallback = callback;
		}
		box3document.resizeCallback();
	},
	fixFlashs: function(){
		/*
		<div class="flash">
			<?php
				$flash['id'] 			= 'universodakota';
				$flash['swf']			= 'universodakota.swf';
				$flash['vars'] 			= '';  //Passa baseURL por default
				list($width, $height) 	= getimagesize(($flash['swf']));
				$flash['width']	 	= $width;
				$flash['height']		= $height;
				echo json_encode($flash);
			?>
		</div>
		*/
		$('div.flash').each(function(){
			var config = $.parseJSON($(this).html());
				config.vars = "baseURL="+box3document.baseURL+"&"+config.vars;
			var self = $(this);
			$(this)
				.attr('id', config.id)
				.removeClass('flash')
				.css({'width':config.width+'px', 'height':config.height+'px'})
				.flash({
					swf: config.swf,
					id: config.id + "-swf",
					width: '100%',
					height: '100%',
					wmode: "transparent",
					flashvars: config.vars,
					allowScriptAccess: "sameDomain",
					hasVersion: 10,
					hasVersionFail: function(){
						self.hide();
					}
				})
		})
	}
}
/*
*	box3image 							- Manipulações das imagens em geral
*	box3image.preload(caminho)			- Pré-carrega uma imagem
*/
var box3image = {
	preload: function(caminho, completeFn) {
		if(box3image.images[caminho] != undefined)
		{
			$("<img />")
			.attr('src', caminho)
			.load(function() {
				box3image.images[caminho] = caminho;
				alert('complete load image');
				$(this).remove();
				if(typeof completeFn == 'function')
					completeFn();
			});
		}
		else
		{
			if(typeof completeFn == 'function')
					completeFn();
		}
	},
	images: []
}
/*
*	box3string 							- Manipulações de strings em geral
*	box3string.ucFirst(string)			- Transforma em maiusculo o primeiro caractere de uma string
*	box3string.removeAcento(string)		- Remove todos os acentos de uma string
*/
var box3string = {
	ucFirst: function(string){
		return string.substring(0, 1).toUpperCase() + string.substring(1).toLowerCase();
	},
	removeAcento: function(string){
		string = string.replace(new RegExp('[ÁÀÂÃ]','gi'), 'A');
		string = string.replace(new RegExp('[ÉÈÊ]','gi'), 'E');
		string = string.replace(new RegExp('[ÍÌÎ]','gi'), 'I');
		string = string.replace(new RegExp('[ÓÒÔÕ]','gi'), 'O');
		string = string.replace(new RegExp('[ÚÙÛ]','gi'), 'U');
		string = string.replace(new RegExp('[Ç]','gi'), 'C');
		string = string.toLowerCase();
		return string;
	}
}
/*
*	box3form 									- Manipulações dos forms
*	box3form.reset($.form)						- Reseta o formulário
*	box3form.validate($.scope, 'errorselector')	- Valida um formulário/elemento que contenha elementos com classe 'required'
*/
var box3form = {
	reset: function(form){
		form.find('select').val('');
		form.find('select[name=cidade]').html('<option value="">Cidade*</option>');
		form.find('input, textarea').val('');
	},
	validate: function(scope, errorSelector){
		/*
			<input type="text" class="required" errormessage="Preencha seu..." />
		*/
		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;
						case "vimeo":
							var pattern = /http:\/\/(www\.)?vimeo.com\/(\d+)($|\/)/;
							valid = pattern.test(value);
							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;
	}
}
/*
*	Extenção do jQuery para resolver problemas com fadeIn e fadeOut no IE
*	fadeInIE(duration, callback)				- Se for IE, show, caso contrário dá um fadeIn
*	fadeOutIE(duration, callback)				- Se for IE, hide, caso contrário dá um fadeOut
*/
$.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;
	}
});
$.fn.extend({
	href: function(){
		var self = this;
		return self.attr('href').substring(self.attr('href').indexOf('#'));
	}
});
$.extend({
	keys: function(obj)
	{
		var arr = [];
		$.each(obj, function(key){
			arr.push(key)
		});
		return arr;
	}
});
/*
Array.prototype.clean = function(deleteValue) {
	for (var i = 0; i < this.length; i++) {
		if (this[i] == deleteValue) {
			this.splice(i, 1);
			i--;
		}
	}
	return this;
};*/

