 /*
 * @author Renan Vaz
 * @version 1.0
 * @example
 * $("element").focusInOut({
 *
 * 		textIn: 'texto inicial',
 *		textOut: 'texto com focus'
 *
 * });
 * @obs With no arguments, the default is above
 * @license free
 * @param text textIn, text textOut
 * @contribution Renan Vaz
 *
 */
 function URLEncode(plaintext)
{
	// The Javascript escape and unescape functions do not correspond
	// with what browsers actually do...
	var SAFECHARS = "0123456789" +					// Numeric
					"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +	// Alphabetic
					"abcdefghijklmnopqrstuvwxyz" +
					"-_.!?~*'():/";					// RFC2396 Mark characters
	var HEX = "0123456789ABCDEF";
	var encoded = "";
	for (var i = 0; i < plaintext.length; i++ ) {
		var ch = plaintext.charAt(i);
	    if (ch == " ") {
		    encoded += "+";				// x-www-urlencoded, rather than %20
		} else if (SAFECHARS.indexOf(ch) != -1) {
		    encoded += ch;
		} else {
		    var charCode = ch.charCodeAt(0);
			if (charCode > 255) {
			    alert( "Unicode Character '" 
                        + ch 
                        + "' cannot be encoded using standard URL encoding.\n" +
				          "(URL encoding only supports 8-bit characters.)\n" +
						  "A space (+) will be substituted." );
				encoded += "+";
			} else {
				encoded += "%";
				encoded += HEX.charAt((charCode >> 4) & 0xF);
				encoded += HEX.charAt(charCode & 0xF);
			}
		}
	} // for

	return encoded;
};
function Verifica_CPF(CPF) {
	CPF = CPF.replace(/\D/g,"");
	if (CPF.length != 11 || CPF == "00000000000" || CPF == "11111111111" || CPF == "22222222222" || CPF == "33333333333" || CPF == "44444444444" || CPF == "55555555555" || CPF == "66666666666" || CPF == "77777777777" || CPF == "88888888888" || CPF == "99999999999" || CPF == "00000000191")
	return false;
	// Aqui começa a checagem do CPF
	var POSICAO, I, SOMA, DV, DV_INFORMADO;
	var DIGITO = new Array(10);
	DV_INFORMADO = CPF.substr(9, 2); // Retira os dois últimos dígitos do número informado
	
	// Desemembra o número do CPF na array DIGITO
	for (I=0; I<=8; I++) {
	  DIGITO[I] = CPF.substr( I, 1);
	}
	
	// Calcula o valor do 10º dígito da verificação
	POSICAO = 10;
	SOMA = 0;
	   for (I=0; I<=8; I++) {
		  SOMA = SOMA + DIGITO[I] * POSICAO;
		  POSICAO = POSICAO - 1;
	   }
	DIGITO[9] = SOMA % 11;
	   if (DIGITO[9] < 2) {
			DIGITO[9] = 0;
	}
	   else{
		   DIGITO[9] = 11 - DIGITO[9];
	}
	
	// Calcula o valor do 11º dígito da verificação
	POSICAO = 11;
	SOMA = 0;
	   for (I=0; I<=9; I++) {
		  SOMA = SOMA + DIGITO[I] * POSICAO;
		  POSICAO = POSICAO - 1;
	   }
	DIGITO[10] = SOMA % 11;
	   if (DIGITO[10] < 2) {
			DIGITO[10] = 0;
	   }
	   else {
			DIGITO[10] = 11 - DIGITO[10];
	   }
	
	// Verifica se os valores dos dígitos verificadores conferem
	DV = DIGITO[9] * 10 + DIGITO[10];
	   if (Number(DV) != Number(DV_INFORMADO)) {
		  return false;
	   }else return true;
}
function saudacao(){
	var data = new Date();
	hora = data.getHours();
	if(hora < 12){
		return 'Bom dia';
	}else if(hora < 18){
		return 'Boa tarde';
	}else return 'Boa noite';
}
function validaEmail(email){
	return /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/.test(email);
}
function validaEmailList(email,separator){
	email = email || 'nada';
	var emails = email.split(separator);
	for (i in emails){
	if(!validaEmail($.trim(emails[i])))
	return false;
	}
	return true;
}
function validaEmailList2(email,separator){
	return /^([a-zA-Z0-9._%+-]+@(?:[a-zA-Z0-9-]+\.)+[a-zA-Z]{2,4})(, ?([a-zA-Z0-9._%+-]+@(?:[a-zA-Z0-9-]+\.)+[a-zA-Z]{2,4}))*?$/.test(email);
}
function $r(id){
	return document.getElementById(id);
}
jQuery.fn.focusInOut = function(params) {
	var options = {
		
		textIn: '',
		textOut: '',
		fnIn: function(o){},
		fnOut: function(o){},
		senha:false

	}
	var op = jQuery.extend(options, params);

   return this.each(function(){
		//initializing variables
		var $self = jQuery(this);
		 $self.attr('textIn',op.textIn);
		 $self.attr('textOut',op.textOut);
		 if(op.senha){
			 $self.val('').hide()
			 $self.after('<input type="text" value=""/>');
			 
			 $self.next().attr('textIn',op.textIn);
		 	 $self.next().attr('textOut',op.textOut);
			 $self.next().val(op.textIn);
			 $self.next().focus(function (){
							   if(jQuery.trim($(this).val()) == jQuery.trim($(this).attr('textIn'))){
							   $(this).hide().prev().show().focus();
							   }
							   });
			 $self.blur(function (){ 
								  if(jQuery.trim($(this).val()) == jQuery.trim($(this).attr('textOut')))
								  $(this).hide().next().show();
								  });
		 }else{
			 if($self.val()=='')
		 	 $self.val(op.textIn);
			 $self.focus(function (){
								   if(jQuery.trim($(this).val()) == jQuery.trim($(this).attr('textIn'))){ 
											$(this).val(jQuery.trim($(this).attr('textOut'))); 
											op.fnIn($(this));
								   }
								   });
			 $self.blur(function (){ 
								  if(jQuery.trim($(this).val()) == jQuery.trim($(this).attr('textOut'))){ 
											$(this).val(jQuery.trim($(this).attr('textIn'))); 
											op.fnOut($(this));
								  }
								  });
		 }
   });
};

/**
 * @author Renan Vaz
 * @version 1.0
 * @example
 * $("input[@type=checkbox]").check(); $("input[@type=radio]").uncheck();
 * 
 * @contribution Renan Vaz
 *
 */
jQuery.fn.extend({ 
	check: function() { 
	return this.each(function() { 
	this.checked = true; }); }, 
	uncheck: function() {
	return this.each(function() { 
	this.checked = false; }); } 
}); 
/**
 * @author Renan Vaz
 * @version 1.0
 * @example
 * $("input").countChars(40);
 * @obs With no arguments, the default is 30, the span have like id='id input'+limit
 * @license free
 * @param number p (max chars)
 * @contribution Renan Vaz
 *
 */
jQuery.fn.countChars = function(p) {
	var params = {
			limit: p
		}
	var options = {
			limit: 30
		}
		var fnCount = function($this){
				var tamanho = $this.value.length;
				var resto   = Number(jQuery($this).attr('MaxCh')) - tamanho;
				resto 		= resto > 0 ?resto : '0'; 
				var obj     = jQuery($this).attr('id')+'limit';
				jQuery('#'+obj).html(resto);
			};
		op = jQuery.extend(options, params);
   return this.each(function(){
		//initializing variables
		var $self   = jQuery(this);
		$self.attr('MaxCh',op.limit);
		$self.attr('maxlength',op.limit);
		fnCount(this);
	$self.keyup(function (){fnCount(this)});
	$self.blur(function (){fnCount(this)});
	$self.parents("form").each(function() {
		//Bind parent form submit
		$self.submit(function() {
			if($self.val()==text) {
				$self.val('');
			}
		});
	});
   });
};
jQuery.fn.extend({
  scrollTo : function(speed, easing) {
    return this.each(function() {
      var targetOffset = jQuery(this).offset().top;
      jQuery('html,body').animate({scrollTop: targetOffset}, speed, easing);
    });
  }
});

/**
 * @author Renan Vaz
 * @version 1.0
 * @example
 * $("input").countChars(40);
 * @obs With no arguments, the default is 30, the span have like id='id input'+limit
 * @license free
 * @param borderColor String (hex) e.g default is '#c00'
 * @param borderOut   String (hex) e.g default is '2px'
 * @param borderOver  String (hex) e.g default is '4px'
 * @param clear		  String (hex) e.g default is 'both' clear float
 * @contribution Renan Vaz
 * usage:
 * $(function(){
 * $('a').innerBorder({clear:'right'});
 * });
 */

jQuery.fn.innerBorder = function(params) {
		var options = {
			borderColor: '#BEBCBC',
			borderOut: '2px',
			borderOver: '4px'
		}
		op = jQuery.extend(options, params);
	 return this.each(function() {
		var $self = jQuery(this);
		$self.attr('innerBorder','yes');
		jQuery(this).css({float: 'left', overflow:'hidden',clear:op.clear});
		jQuery('[innerBorder=yes]').hover(function(){
		  jQuery('img',this).css('margin','-'+op.borderOver);
          jQuery(this).css({border:op.borderOver+' solid '+op.borderColor})
        },
        function(){
            jQuery('img',this).css('margin','-'+op.borderOut);
            jQuery(this).css({border:op.borderOut+' solid '+op.borderColor})
        });
		jQuery('img',this).css('margin','-'+op.borderOut);
		jQuery(this).css({border:op.borderOut+' solid '+op.borderColor})
	});
}

jQuery.fn.isChrome = function(){
	return  navigator.userAgent.toLowerCase().indexOf("chrome") > -1;
}

//-------------------------------------------------------------------------
//@param font = font path  ex: fonts/arial.swf
//@param css array [ font-style:italic; display: inline;] apenas adicionar mais atributos a classe principal 
//@param cssAdd array [em { font-style:italic; display: inline;}] adicionar novas classes
// depende do plugin flash do jquery

/////////////////////////////////////////////////////////////////////

$.extend({
  	formatDate: function(params){
		var data = params.date.split('/');
		if(params.pt)
		return data[0]+'/'+data[1]+'/'+data[2];
		else
		return data[2]+'/'+data[1]+'/'+data[0];
	},
	F_ucFirst:  function(str){
		return str.substr(0,1).toUpperCase()+str.substr(1);
	},
	ucFirst:function(str){
		str 	= $.trim(str);  
		return str.substr(0,1).toUpperCase()+str.substr(1);
	},
	formatName: function(str){
		str 		= $.trim(str);  
		var aStr	= str.split(' ');
		var notConverter = new Array('das','dos','da','de','di','do','e');
		var strReturn = new String();
		for(i=0;i<aStr.length;i++)
		strReturn += aStr[i].substr(0,1).toUpperCase()+aStr[i].substr(1)+' ';
		for(i=0;i<notConverter.length;i++)
		strReturn = strReturn.replace(notConverter[i].substr(0,1).toUpperCase()+notConverter[i].substr(1),notConverter[i]);
		return $.trim(strReturn);
	},
	padLeft: function(val, ch, num) {
		var re = new RegExp(".{" + num + "}$");
		var pad = "";
		if (!ch) ch = " ";
		do  {
			pad += ch;
		}while(pad.length < num);
		return re.exec(pad + val)[0];
	},
	padRight: function (val, ch, num){
		var re = new RegExp("^.{" + num + "}");
		var pad = "";
		if (!ch) ch = " ";
		do {
			pad += ch;
		} while (pad.length < num);
		return re.exec(val + pad)[0];
	},
	formatNumber: function(nStr){
		nStr += '';
		x = nStr.split(',');
		x1 = x[0];
		x2 = x.length > 1 ? ',' + x[1] : '';
		var rgx = /(\d+)(\d{3})/;
		while (rgx.test(x1)) {
			x1 = x1.replace(rgx, '$1' + '.' + '$2');
		}
		return x1 + x2;
	}
});

$.fn.charCounter = function (max, settings) {
		max = max || 100;
		settings = $.extend({
			container: "<span></span>",
			classname: "charcounter",
			format: "%1",
			pulse: false,
			delay: 0
		}, settings);
		var p, timeout;
		
		function count(el, container) {
			el = $(el);
			if (el.val().length > max) {
			    el.val(el.val().substring(0, max));
			    if (settings.pulse && !p) {
			    	pulse(container, true);
			    };
			};
			if (settings.delay > 0) {
				if (timeout) {
					window.clearTimeout(timeout);
				}
				timeout = window.setTimeout(function () {
					container.html(settings.format.replace(/%1/, (max - el.val().length)));
				}, settings.delay);
			} else {
				container.html(settings.format.replace(/%1/, (max - el.val().length)));
			}
		};
		
		function pulse(el, again) {
			if (p) {
				window.clearTimeout(p);
				p = null;
			};
			el.animate({ opacity: 0.1 }, 100, function () {
				$(this).animate({ opacity: 1.0 }, 100);
			});
			if (again) {
				p = window.setTimeout(function () { pulse(el) }, 200);
			};
		};
		
		return this.each(function () {
			var container = settings.alvo ? $(settings.alvo) : (!settings.container.match(/^<.+>$/)) 
				? $(settings.container) 
				: $(settings.container)
					.insertAfter(this)
					.addClass(settings.classname);
			$(this)
				.bind("keydown", function () { count(this, container); })
				.bind("keypress", function () { count(this, container); })
				.bind("keyup", function () { count(this, container); })
				.bind("focus", function () { count(this, container); })
				.bind("mouseover", function () { count(this, container); })
				.bind("mouseout", function () { count(this, container); })
				.bind("paste", function () { 
					var me = this;
					setTimeout(function () { count(me, container); }, 10);
				});
			if (this.addEventListener) {
				this.addEventListener('input', function () { count(this, container); }, false);
			};
			count(this, container);
		});
	};

(function(){
	$.registerEvents = function() {
		$.each( arguments, function(i,n) {
			if (!$.fn[n]) return;
			var old = $.fn[n];
			$.fn[n] = function() {
				var r = old.apply(this, arguments);
				$(this).trigger(n);
				return r;
			}
		});
	}
    $.fn.extend({
    	block: function(fn){ 
    		return $(this).each(function(){
    			$(this).css('position','relative');
    			$('.rvaz-block',this).remove();
    			var blocker = $('<div />').css({
    				position: 'absolute',
    				top: 0,
    				left: 0,
    				width: $(this).innerWidth(),
    				height: $(this).innerHeight()
    			}).addClass('rvaz-block').appendTo($(this)).fadeTo(200,.5);
    			if(typeof fn == 'function') fn(this, blocker);
    		});
    	},
    	unblock: function(){
    		return $(this).each(function(){
    			$('.rvaz-block',this).fadeTo(200,0, function(){ $(this).remove(); });
    		});
    	},
    	defaultValue: function(text){
    		var text = text;
    		return $(this).each(function(){
    			var $self = $(this);
    			var color = $self.css('color');
    			$self.bind('focus',function(){	if($self.val() == text){$self.css('color', color).val('')} });
    			$self.bind('blur',function(){	if($.trim($self.val()) == ''){$self.css('color', '#ccc').val(text)} });
    			if($self.val() == '') $self.trigger('blur');
    		});
    	},
    	scrollTo : function(speed) {
    		return this.each(function() {
    	      	var targetOffset = $(this).offset().top-58;
    			targetOffset = ((targetOffset + $(window).height()) > $('body').height() ? targetOffset - ((targetOffset + $(window).height()) - $('body').height()) : targetOffset);
    	      	$('html,body').animate({scrollTop: targetOffset}, 1000, 'easeInOutExpo');
    	    });
    	},
    	scrollInMouse: function(){
    		return $(this).each(function(){
    			var $self = $(this);
    			var y;
    			var lastY;
    			var interval;
    			var inAnimation = false;
    			var margin = 0;
    			var vel = 4;
    			var padding = 50;
    			var x = 0;
    			function animateThis(){
    				try {
    				    var top = $self.css('top') == 'auto' ? 0 : Number($self.css('top').replace('px', ''));
    					var nextY = Math.ceil(top + (y - top) / vel);
                        console.log($self.css('top') + ' ' + y);
    					if (lastY !== nextY) {
    						$self.css({
    							top: nextY
    						});
    						lastY = nextY;
    					} else {
    						clearInterval(interval);
    						inAnimation = false;
    					}
    				}catch(e){
    				    inAnimation = false;
    					var str = '';
    					try{console.log(e)}catch(e){}
    					clearInterval(interval);
    				}
    			}
    			
    			$(this).parent().mousemove(function(e){			 
    				if(!inAnimation){
    					//$('#info-page').text(++x);
    					interval = setInterval(animateThis, 20);
    					inAnimation = true;
    				}
    				if($self.height() - $(this).height()){
    					var p1 = e.pageY > $(this).offset().top + padding ? e.pageY - padding > (($(this).offset().top + $(this).height()) - 2 * padding) ? (($(this).offset().top + $(this).height()) - 2 * padding) : e.pageY - padding : $(this).offset().top;
    					var pct = Math.ceil((((p1 - $(this).offset().top)*100)/($(this).height() - 2 * padding)));
    					y		= -Math.ceil((pct * (($self.height() + 2 * margin) - $(this).height()))/100)+margin;
    				}
    			});
    		});
    	}
    });
    $.registerEvents('slideDown','slideUp','slideToggle','remove');
})(jQuery);