/**
 * Input element decorator
 * Usage: $(<selector>).inputDecorator();
 */

INPUT_CLASSNAME = 'inp';
INPUT_ACTIVE_CLASSNAME = 'inp-active';

jQuery.fn.extend({
	inputDecorator: function () {
		
		if (this) {
			
			var me = this,
				hasFocus = false;
		
			var fadein = function () {
				$(me).addClass(INPUT_ACTIVE_CLASSNAME);
			}
		
			var fadeout = function () {
				$(me).removeClass(INPUT_ACTIVE_CLASSNAME);
			}
		
			$(this)
				.mouseover(function () {
					if (!hasFocus) fadein();
				})
				.mouseout(function () {
					if (!hasFocus) fadeout();
				})
				.find('input, textarea')
					.focus(function () {
						fadein();
						hasFocus = true;
					})
					.blur(function () {
						fadeout();
						hasFocus = false;
					});
					
		}
		
	}
});


/**
 * Main Menu decorator
 * Usage: $(<selector>).menuDecorator();
 */

jQuery.fn.extend({
	mainMenuDecorator: function () {
		
		if (this) {
			
			var me = $(this),
				activeItem = $(this).hasClass('mmenu-search') ? this.parent().find('.search .title') : me.find('.active'),
				pointerCover = me.find('.pointer-cover'),
				pointer = me.find('.pointer'),
				_defWidth = activeItem.outerWidth(),
				flowbackTimeout;
			
			if (!pointer) {
				return false
			}
			
			var getLeftPos = function (item) {
				return $(item).offset().left + ($(item).outerWidth() - pointer.outerWidth()) / 2 - $(me).offset().left;
			}
			
			var movePointer = function (item) {
				pointer
					.stop()
					.animate({
						left: getLeftPos(item),
						queue: true
					}, 500, "swing");
			}
			
			var adjustPointer = function () {
				pointer.css('left', getLeftPos(activeItem));
			}
			
			var showPointer = function () {
				pointerCover.fadeOut("slow");
			}
			
			var resizeHandler = setInterval(function () {
				var _width = activeItem.outerWidth();
				if (_width != _defWidth) {
					_defWidth = activeItem.outerWidth();
					adjustPointer();
				}
			}, 500);
			
			setTimeout(function () {
				adjustPointer();
				showPointer();
			}, 500);
			
			$(this).find('a').each(function () {
				$(this)
					.mouseover(function () {
						clearTimeout(flowbackTimeout);
						movePointer(this);
					})
					.mouseout(function () {
						clearTimeout(flowbackTimeout);
						flowbackTimeout = setTimeout(function () {
							movePointer(activeItem);				
						}, 500);
					});
			})
			
		}
		
	}
});


/**
 * Clients
 * Usage: $(<selector>).clients();
 */

jQuery.fn.extend({
	clients: function () {
		
		if (this) {
			
			var me = this,
				linkMore = $(this).find('.link-more a'),
				moreBlock = $(this).find('.more');
		
			linkMore.click(function () {
				
				linkMore
					.text(moreBlock.is(':visible') ? 'Show more' : 'Show less')
					.toggleClass('less');
				moreBlock.slideToggle();
				
			});
					
		}
		
	}
});

