/*
*	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(){
		box3document.fixMasks();
		box3document.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;
			$(this)
				.removeClass('flash')
				.attr('id', config.id)
				.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",
					allowFullScreen: true,
					hasVersion: 10,
					hasVersionFail: function(){
						box3document.redirect('noflash');
					}
				})
		})
	}
}
/*
*	box3image 							- Manipulações das imagens em geral
*	box3image.preload(caminho)			- Pré-carrega uma imagem
*/
var box3image ={
	preload: function(caminho, completeFn){
		if($.browser.msie){
			if(typeof completeFn == 'function') completeFn();
			return false;
		}
		$("<img />")
		.attr('src', './'+caminho)
		.bind('load', function(){
			if(typeof completeFn == 'function') completeFn();
			$(this).remove();
		});
	}
}
/*
*	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('');
		form.find('.error').removeClass('error');
		form.find('.errormessage').text('');
	},
	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('');
		var seletor = '[class^="required"]:visible, [class~="required"]:visible, [class^="required"][type="hidden"], [class~="required"][type="hidden"]';
		scopeElm.find(seletor).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;
						/* Função para validar o CPF digitado. */
						case "cpf":
								value = value.replace(/[\.-]/g,'');
								if(value.length != 11 || value.replace(eval('/'+value.charAt(1)+'/g'),'') == ''){
									valid = false;
								}else{
									for(n=9; n<11; n++){
										for(d=0, c=0; c<n; c++) d += value.charAt(c) * ((n + 1) - c);
										d = ((10 * d) % 11) % 10;
										if(value.charAt(c) != d) return false;
									}
									
									return true;
								}
						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\ ]+$/);
								var value = self.val();
								if(!pattern.test(value))
									valid = false;
								else
								{
									var currentDate = new Date();
									var currentYear = currentDate.getFullYear();
									switch(result[1])
									{
										case "day":
												if(parseInt(value, 10) < 1 || parseInt(value, 10) > 31)
													valid = false;
											break;
										case "month":
												if(parseInt(value, 10) < 1 || parseInt(value, 10) > 12)
													valid = false;
											break;
										case "year":
												if(parseInt(value, 10) < 1900 || parseInt(value, 10) > currentYear)
													valid = false;
											break;
									}
								}
							break;
						case "fullDate":
							var value = self.val();
							var dates = value.split('/');
							var currentDate = new Date();
							var currentYear = currentDate.getFullYear();

							if(value == "")
								valid = false;
							if(parseInt(dates[0], 10) < 1 || parseInt(dates[0], 10) > 31)
								valid = false;
							else if(parseInt(dates[1], 10) < 1 || parseInt(dates[1], 10) > 12)
								valid = false;
							else if(parseInt(dates[2], 10) < 1900 || parseInt(dates[2], 10) > currentYear)
								valid = false;

							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();
					console.log(self.attr('errormessage'));
					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;
	},
	fadeToIE: function (duration, opacity, callback)
	{
		var elm = $(this);
		if($.browser.msie)
		{
			elm.css('opacity', opacity);
			if(typeof(callback) == 'function')
				setTimeout(callback, 100);
		}
		else
		{
			elm.fadeTo(duration, opacity, 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;
}; */
$.fn.extend({
	setVars: function(){
		try{
			var self = this;
			var json = jQuery.parseJSON(self.html()) || self;
			jQuery.each(json, function(key, value){
				self.data(key, value);
			})
		} catch(e){
			return false;
		}
		return self;
	}
})
var CustomHover ={
	init: function (elmLink)
	{
		var elm = $(elmLink);
		$.each(elm, function (){
			var self = $(this);
			self
				.append('<span class="transparent"></span>')
				.bind('mouseover', CustomHover.mouseIn)
				.bind('mouseout', CustomHover.mouseOut)
		});
	},
	mouseIn: function (e)
	{
		e.preventDefault();
		var self = $(this);
		var span = self.find('span');
		span.css({
			'background-image': self.css('backgroundImage'),
			'background-color': self.css('backgroundColor')
		});
		if($.browser.msie && self.css('backgroundColor') == 'transparent')
		{
			span.css('opacity','show');
		}
		else
		{
			span.stop().animate({opacity: 1}, 'fast');
		}
	},
	mouseOut: function (e)
	{
		e.preventDefault();
		var self = $(this);
		var span = self.find('span');
		if(self.hasClass('ativo')) return false;
		if($.browser.msie && self.css('backgroundColor') == 'transparent')
		{
			span.css('opacity',0);
			// span.stop().animate({opacity: 'hide'}, 'fast');
		}
		else
		{
			span.stop().animate({opacity: 0}, 'normal');
		}
	}
}
$.fn.extend({
	dnone: function(){
		this.css('display', 'none');
		return this;
	},
	dblock: function(){
		this.css('display', 'block');
		return this;
	}
});
/*--------------------------------------------------------------------
 * Plugin para customizar os Radios
--------------------------------------------------------------------*/

jQuery.fn.customRadio = function(){
	$(this).each(function(i){
		
	});
};

jQuery.fn.box3Radio = function(){
	$(this).each(function(i){
		if($(this).is('[type=checkbox],[type=radio]')){
			var input = $(this);
			input.prop('checked', false);
			var label = $('label[for='+input.attr('id')+']');
			var inputType = (input.is('[type=checkbox]')) ? 'checkbox' : 'radio';
			$('<div class="custom-'+ inputType +'"></div>').insertBefore(input).append(input, label);
			var allInputs = $('input[name='+input.attr('name')+']');
			label.hover(
				function(){
					$(this).addClass('hover');
					if(inputType == 'checkbox' && input.is(':checked')){
						$(this).addClass('checkedHover');
					}
				},
				function(){ $(this).removeClass('hover checkedHover'); }
			);
			input.bind('updateState', function() {

				if (input.prop('checked') == true){
					if (input.is(':radio')){
						allInputs.each(function(){
							$('label[for='+$(this).attr('id')+']').removeClass('checked');
						});
					};
					label.addClass('checked');
				}
				else { label.removeClass('checked checkedHover checkedFocus'); }
			})
			.focus(function() {
				label.addClass('focus');
				if(inputType == 'checkbox' && input.is(':checked')){
					$(this).addClass('checkedFocus');
				}
			})
			.blur(function() { label.removeClass('focus checkedFocus'); });
			
			if($.browser.msie)
				label.bind('click', function (e) { input.trigger('click');});
			
			input.bind('click', function (e) { 
				if(e) { e.preventDefault(); e.stopImmediatePropagation; }

				input.trigger('updateState'); 
			});
			
			//input.trigger('updateState');
		}
	});
};
$.fn.wait = function(time, type){
	time = time || 1000;
	type = type || "fx";
	return this.queue(type, function(){
		var self = this;
		setTimeout(function(){
			$(self).dequeue();
		}, time);
	});
};

