/**
 * +project
 * +project.basics
 * +project.forms
 * +project.userInterface
 * +jQuery Init
 *
 * @namespace project
 */
var project = {};

/**
 * @classDescription "Classe" com os métodos padrões do framework
 */ 
project.basics = (function ($) {

	return {
		/**
		 * @method links ações conforme atributos e eventos de alguns links
		 */
		links : function() {
			$('a[target="_blank"]').each(
				function(elm) {
					$(this).attr("title", $(this).attr('title') +  ' (Este link abre uma nova janela) ');
				}
			);
			
			$('a[rel="external"]').each(
				function(elm) {
					$(this).attr("title", $(this).attr('title') +  ' (Este link abre uma nova janela) ');
				}
			);
		},
		
		
		/**
		 * @method parseQueryString
		 * @param {String} queryString url com os parâmetros a serem retornados
		 * @return {Object} objeto com os parâmetros da url
		 */
		parseQueryString : function(queryString){ 
			var result = {};

			if (queryString == undefined) queryString = location.search ? location.search : '';
			if (queryString.charAt(0) == '?') queryString = queryString.substring(1);

			queryString = queryString.split('#')[0];
			queryString = queryString.replace('+', ' ');
			queryString = queryString.replace('?', '&');

			var queryComponents = queryString.split(/[&;]/g);

			for (var i = 0; i < queryComponents.length; i++){
				var keyValuePair = queryComponents[i].split('=');
				var key = decodeURIComponent(keyValuePair[0]);
				var value = decodeURIComponent(keyValuePair[1]);

				if (!result[key]) result[key] = [];
				result[key].push((keyValuePair.length == 1) ? '' : value);

			}
			
			return result;
		},
		
		
		/**
		 * @method placeholder
		 */
		placeholder: function() {
			// evento focus
			$('.placeholder:not(.placeholder[type="password"])').bind('focus', function(){
				// se o valor do input for igual ao atributo title dele...
				if($(this).val() == $(this).attr('title')) {
					//... o valor do input fica vazio
					$(this).val('');
				}
			
			// evento blur
			}).bind('blur', function(){
				// se o valor do input for igual a vazio...
				if($(this).val() == '') {
					// ... o input recebe o valor de seu atributo title
					$(this).val($(this).attr('title'));
				}
			});
		},
		
		
		/**
		 * @method stringtoSlug
		 */
		stringToSlug: function(str) {
		  str = str.replace(/^\s+|\s+$/g, ''); // trim
		  str = str.toLowerCase();
		  
		  // remove accents, swap ñ for n, etc
		  var from = "àáäâèéëêìíïîòóöôùúüûñç·/_,:;";
		  var to   = "aaaaeeeeiiiioooouuuunc------";
		  for (var i=0, l=from.length ; i<l ; i++) {
		    str = str.replace(new RegExp(from.charAt(i), 'g'), to.charAt(i));
		  }

		  str = str.replace(/[^a-z0-9 -]/g, '') // remove invalid chars
		    .replace(/\s+/g, '-') // collapse whitespace and replace by -
		    .replace(/-+/g, '-'); // collapse dashes

		  return str;
		},
		
		
		 /**
		* @method preloadImage
		* @param {String} src
		* @param {Function} callback
		*/
		preloadImage: function(src, callback) {
			var preloadImg = $('<img src="'+ src +'" style="position:absolute; top:-9999px; left:-9999px;" />');

			$('body').append(preloadImg);

			preloadImg.load(function(){
				$(this).remove();
				callback(src);
			});
		}
	}
	
})(jQuery);


/**
 * @classDescription "Classe" com os métodos relacionados aos formulários do site
 */
project.forms = (function ($) {
	var properties = {};
	
	/**
	 * @method loadProductList
	 * @param order
	 * @param page
	 */
	function loadProductList(order, page) {
		var order        = (order && order != "") ? order : $('input[name="order"]').val(),
			page         = (page && page != "") ? page : $('input[name="page"]').val(),
		    productsList = (properties.target) ? properties.target : $('#productsList'),
			search       = $('#filterOptions input[name="search"]').val(),
		    loadingList, html, cssClass;
		
		if(!$('#loadingList')[0]) {
			productsList.append('<div id="loadingList" class="products-loading" style="display:none;"></div>');
			$('#loadingList').css('opacity', 0.8);
		}
		
		loadingList = $('#loadingList');
		loadingList.css('height', productsList.height() + 'px').fadeIn();
		
		$.get(document.location.href, { 
			gender        : $('#gender').val(),
			productType   : $('#productType').val(),
			sportActivity : $('#sportActivity').val(),
			color         : $('#color').val(),
			technology    : $('#technology').val(),
			collection    : $('#collection').val(),
			size          : $('#size').val(),
			order         : order,
			page          : page,
			search        : search,
			ajax          : true 
		}, function(data){
			if(!$('error', data)[0]) {
				$('product', data).each(
					function(i) {
							
						el = $(this);
						
						if($('product', data).length == i + 1 || (i + 1) % 4 == 0)
							cssClass = 'class="last"';
						else
							cssClass = '';
							
						html  = '<li '+ cssClass +' style="display:none;">';
						html += '<a href="'+ rootUrl + 'produto/' + el.attr('slug') +'">';
						html += '<strong>'+ el.find('name').text() +'</strong>';
						html += '<em>'+ el.attr('reference') +'</em>';
						html += '<img src="'+ rootUrl +'public/upload/products/'+ el.attr('slug') +'/'+ el.find('img').attr('src') +'" alt="" />'
						html += '</a>';
						html += '</li>';
						
						productsList.find('ul:eq(0)').append(html);
						
						if(i == $('product', data).length - 1) {
							$('input[name="order"]').val(order);
							$('input[name="page"]').val(page);
							
							productsList.find('li:visible').hide().addClass('remove');
							productsList.find('li.remove').remove();
							loadingList.fadeOut();
							
							productsList.find('li').fadeIn();
							
							html = $('pagination', data).text();
							
							$('.pagination').each(function(){
								$(this).html(innerShiv(html));
							});
							
							productsList.css('height', productsList.find('ul').height() + 'px');
						}
					}						
				);
			
			} else {
				loadingList.fadeOut();
				productsList.find('ul').html('<li class="empty">' + $('error', data).text() + '</li>');
				$('.pagination').html('');
			}
		});
	}
	
	
	/**
	 * @method filtersNav
	 */
	function filtersNav() {
		$('#filterOptions').delegate('select', 'change', function(){
			loadProductList("", 1);
		});
	}	
	
	
	/**
	 * @method orderList
	 */
	function orderList() {
		var el, order;
		
		$('#productsOrder a').click(
			function() {
				el = $(this);
				el.parent().addClass('selected').siblings().removeClass('selected');
				order = project.basics.parseQueryString(el.attr('href')).order;
				
				loadProductList(order.toString());
				
				return false;
			}	
		);
	}	
	
	
	/**
	 * @method ajaxPagination
	 */
	function ajaxPagination() {
		var el, page;
	
		$('.pagination').delegate('a', 'click',
			function() {
				el = $(this);
				page = el.attr('data-page');
				
				loadProductList("", page);
				
				return false;
			}	
		);
	}
	
	/**
	 * @method clearAll
	 */
	function clearAll() {
		$('#filter .description a').click(
			function() {
				$('#filterOptions select').each(
					function() {
						$(this).find('option:eq(0)').attr('selected', true)
						       .parents('.filter').find('.filter-content').text($(this).find('option:eq(0)').text())
						       .end().find('ul li:eq(0)').addClass('selected').siblings().removeClass('selected');
					}
				);
				
				$('#productsOrder menu li:eq(0)').addClass('selected')
				                                 .siblings().removeClass('selected');
				
				loadProductList("A-Z", 1);
				
				return false;
			}	
		);	
	}
	
	
	return {
		/**
		 * @method searchForm
		 */
		searchForm: function() {
			var elm;
			
			$('#searchForm').submit(
				function() {
					elm = $(this); 
					
					elm.attr({ 
						action: elm.attr('action') + '/' + project.basics.stringToSlug(elm.find('#search').val()),
						method: 'post'
					});
					
					if(elm.find('#search').val() == 'Buscar')
						elm.find('#search').val('');
				}
			);
		},
		
		
		/**
		 * @method customFilters
		 */
		customFilters: function(filters) {
			var elm, elmOption, classSelected;
			
			filters.each(
				function() {
					elm = $(this);
					
					elm.addClass('hide')
					   .wrap('<div class="filter" id="'+ elm.attr('id') +'Custom" />')
					   .parent().prepend('<div class="filter-content">'+ elm.find('option:eq(0)').html() +'</div><ul />');
					
					elm.find('option').each(
						function(i) {
							elmOption = $(this);
							
							if(i == 0)
								classSelected = 'class="selected"';
							else
								classSelected = '';
								
							
							elm.parent().find('ul').append('<li '+ classSelected +' data-value="'+ elmOption.val() +'"><a href="javascript:void(0)">'+ elmOption.html() +'</a></li>');
						}
					);
				}
			)
			
			$('#filter').delegate('.filter', 'mouseenter', function() {
				$(this).find('ul').stop(1,1).slideDown({
					method   : 'easyInSine',
					duration : 220
				});
			
			}).delegate('.filter-content','click', function() {
				$(this).parents('.filter').find('ul').stop(1,1).slideDown({
					method   : 'easyInSine',
					duration : 220
				});

			}).delegate('.filter','mouseleave', function() {
				$(this).find('ul').stop(1,1).slideUp({
					method   : 'easyInSine',
					duration : 150
				});
			
			}).delegate('.filter a', 'click', function(){
				elm = $(this);				
				
				if(elm.text() != elm.parents('.filter').find('.filter-content').text()) {
					elm.parents('.filter').find('select option[value="'+ elm.parent().attr('data-value') +'"]').attr('selected', true);
					elm.parents('.filter').find('select').change();
					elm.parents('.filter').find('.filter-content').html(elm.html())
					   .end().find('ul').hide()
					   .end().end().parent().addClass('selected').siblings().removeClass('selected');
				} else {
					elm.parents('.filter').find('.filter-content ul').hide();
				}
			});
		},
		
		
		/**
		 * @method productlist
		 */
		productsList: function() {
			this.customFilters($('#filter select'));
			
			// reset inputs
			$('#filterOptions select').each(
				function() {
					$(this).find('option:eq(0)').attr('selected', true)
				}
			);		
			$('input[name="order"]').val('A-Z');
			$('input[name="page"]').val(1);
			
			// navegação dos filtros
			filtersNav();
			
			// navegação pela paginação
			ajaxPagination();
			
			 // ordenação da listagem
			orderList();
			
			// limpar todos os filtros da listagem
			clearAll();
		},
		
		
		/**
		 * @method searchList
		 */
		searchList: function() {
			properties.target = $('#main > nav.left'); 
			
			this.customFilters($('#filter select'));
			
			// reset inputs
			$('#filterOptions select').each(
				function() {
					$(this).find('option:eq(0)').attr('selected', true)
				}
			);
			$('input[name="order"]').val('A-Z');
			$('input[name="page"]').val(1);
			
			// navegação dos filtros
			filtersNav();
			
			// navegação pela paginação
			ajaxPagination();
			
			 // ordenação da listagem
			orderList();
			
			// limpar todos os filtros da listagem
			clearAll();
		}
	}	
		
	
})(jQuery);


/**
 * @classDescription "Classe" com os métodos relacionados a interface
 */ 
project.userInterface = (function ($) {
	/**
	 * @method imageDetails
	 */
	function imageDetails() {
		var productImages = $('#productImages'),
		    el, img;
		
		productImages.find('#productLargeImage img').wrap('<div id="currentImage" />')
		             .end().find('#productLargeImage').append(innerShiv('<figcaption>Clique para ampliar</figcaption>'));
		
		productImages.find('nav').delegate('a', 'click',
			function() {
				el = $(this);
				
				$('#currentImage img').fadeOut(
					function() {
						img = $(this);
						
						img.parent().addClass('products-loading');
						
						project.basics.preloadImage(el.attr('data-image'), function(src){
							img.attr('src', src);
							img.fadeIn().parent().removeClass('products-loading');
						});
					}
				);

				return false;
			}
		);
		
		imageZoom();
	}
	
	
	/**
	 * @method imageZoom
	 */
	function imageZoom() {
		var productImages = $('#productImages'),
		    currentImage  = $('#currentImage');
		
		currentImage.delegate('img', 'click', function(){
			expandImageArea(productImages, currentImage);
		}).find('img').css('cursor', 'pointer');
		
		// acrescenta ao clique das thumbs de produtos a ação de fechar a imagem com zoom antes de mudar para a clicada
		productImages.find('nav a').bind('click',
			function() {
				if(currentImage.hasClass('zoom-in')) {
					currentImage.find('img').animate({ 
						maxWidth  : currentImage.find('img').attr('data-small-width') + 'px',
						maxHeight : currentImage.find('img').attr('data-small-height') + 'px',
						top       : parseInt(402 - currentImage.find('img').attr('data-small-height')) / 2 + 'px', 
						left      : parseInt(currentImage.parents('#main').width() - currentImage.find('img').attr('data-small-width')) / 2 + 'px'
					}, function(){
						$(this).addClass('type-zoom');
						$('#productLargeImage figcaption').html('Clique para ampliar');
						
					}).draggable('disable').end().removeClass('zoom-in');
				}
			}	
		);
	}
	
	function expandImageArea(productImages, currentImage) {
		var productDescription = $('#productDescription');
		
		// se productImages ainda não possuir a classe zoom, então é para exibir os detalhes das imagens
		if(!productImages.hasClass('zoom')) {
			
			// amplia com animação o elemento productImages
			productImages.css({ position:'absolute' }).animate({
				width  : '803px',
				height : '469px'
			}).addClass('zoom');
			
			// currentImage é ampliado com animação
			currentImage.animate({
				width  : '100%',
				height : '402px'
			}, function(){
				
				$(this).click(function(e){
					zoomInZoomOutImage($(this), e)
				});
				
				// cursores
				$(this).find('img').addClass('type-zoom');
				
			}).css('position', 'relative')
			  .find('img').css({ 
				position:'absolute', 
				top : parseInt(402 - currentImage.find('img').height()) / 2 + 'px', 
				left: parseInt(currentImage.parents('#main').width() - currentImage.find('img').width()) / 2 + 'px'
			});
			
			 productDescription.slideUp();
			
			// Insere(se ele ainda não existir) e exibe o botão fechar detalhes das imagens
			if(!productImages.find('.close-zoom')[0]) {
				productImages.append('<a href="javascript:void(0)" class="close-zoom">Fechar</a>');
				
				productImages.find('.close-zoom').click(function(){
					productImages.animate({ width:'399px' }, function(){
						$(this).css('position', 'static')
						       .removeClass('zoom');
					}).css('height', 'auto');

					currentImage.animate({
						width  : '399px',
						height : '306px'
					}, function(){
						$(this).unbind('click')
						       .css('position', 'static');
						
						currentImage.delegate('img', 'click', function(){
							expandImageArea(productImages, currentImage);
						});						
					}).removeClass('zoom-in')
					  .find('img').css({ 
						position:'static' 
					}).animate({ 
						maxWidth  : currentImage.find('img').attr('data-small-width') + 'px',
						maxHeight : currentImage.find('img').attr('data-small-height') + 'px'
					}, function(){
						// cursor
						$('#currentImage img').removeClass('type-zoom').css('cursor', 'pointer');
						
						$('#productLargeImage figcaption').html('Clique para ampliar');
					});
					
					productDescription.slideDown();
					
					productImages.find('.close-zoom').fadeOut();
				});				
			}
			productImages.find('.close-zoom').fadeIn();
		}
	}
	
	
	/**
	 * @method zoomInZoomOutImage
	 * @param el
	 * @param e
	 */
	function zoomInZoomOutImage(el, e) {
		var x, y, 
		    imageXCenter, imageYCenter, 
		    top, left,
		    limitLeft, limitRight, limitTop, limitBottom;
		
		// evita alguns bugs
		el.unbind('click');
		
		// se o elemento ainda não possui a classe zoom-in então é para dar zoom na imagem
		if(!el.hasClass('zoom-in')) {
			// qual a posição no eixo X que a imagem foi clicada
			x = Math.round(e.pageX - el.find('img').offset().left);
			if(x < 0)
				x = 0;
			else if(x > el.find('img').width())
				x = el.find('img').width();
			x = Math.round((x * el.find('img').attr('data-width')) / el.find('img').width());
			
			// qual a posição no eixo Y que a imagem foi clicada
			y = Math.round(e.pageY - el.find('img').offset().top);
			if(y < 0)
				y = 0;
			else if(y > el.find('img').height())
				y = el.find('img').height();
			y = Math.round((y * el.find('img').attr('data-height')) / el.find('img').height());
			
			// pega aproximadamente o centro do container
			imageXCenter = Math.round((el.width() / 2) - 5);
			imageYCenter = Math.round((el.height() / 2) - 5);
			
			// calcula a posição top e left que deverá ficar a imagem ampliada (centralizado onde o usuário clicou)
			// top
			if(imageYCenter > y && el.find('img').attr('data-height') > el.height())
				top = 0;
			else if(el.find('img').attr('data-height') < (y - imageYCenter) + el.height() && el.find('img').attr('data-height') > el.height())
				top = Math.round(el.height() - el.find('img').attr('data-height'));
			else if(el.find('img').attr('data-height') < el.height())
				top = Math.round((el.height() / 2) - (el.find('img').attr('data-height') / 2));
			else 
				top = '-' + Math.round(parseInt(y - imageYCenter));	
			
			// left
			if(imageXCenter > x && el.find('img').attr('data-width') > el.width())
				left = 0;
			else if(el.find('img').attr('data-width') < (x - imageXCenter) + el.width() && el.find('img').attr('data-width') > el.width())
				left = Math.round(el.width() - el.find('img').attr('data-width'));
			else if(el.find('img').attr('data-width') < el.width())
				left = Math.round((el.width() / 2) - (el.find('img').attr('data-width') / 2));
			else
				left = '-' + Math.round(parseInt(x - imageXCenter));
			
			// anima a imagem ampliando
			el.find('img')
			  .attr('data-small-width', el.find('img').width())
	          .attr('data-small-height', el.find('img').height())
	          .animate({ 
				maxWidth: el.find('img').attr('data-width') + 'px',
				maxHeight: el.find('img').attr('data-height') + 'px',
				top: top + 'px',
				left: left + 'px'
			}, function(){
				// deixa a imagem "arrastável"
				if(el.find('img').hasClass('ui-draggable') != true) {
					limitLeft   = Math.round((el.width() - el.find('img').attr('data-width')) + el.offset().left);
					limitTop    = Math.round((el.height() - el.find('img').attr('data-height')) + el.offset().top);
					limitRight  = Math.round(el.offset().left);
					limitBottom = Math.round(el.offset().top);
					
					el.find('img').css('cursor','default')
		              .removeClass('type-zoom')
					
					if(el.find('img').attr('data-width') < el.width() && el.find('img').attr('data-height') > el.height()) { 
						el.find('img').draggable({ containment:[limitLeft, limitTop, limitRight, limitBottom ], axis:'y' });
						
						// cursor
						el.find('img').css('cursor', 'n-resize');
					} else if(el.find('img').attr('data-height') < el.height() && el.find('img').attr('data-width') > el.width()) {
						el.find('img').draggable({ containment:[limitLeft, limitTop, limitRight, limitBottom ], axis:'x' });
						
						// cursor
						el.find('img').css('cursor', 'e-resize');
					} else if(el.find('img').attr('data-height') > el.height() && el.find('img').attr('data-width') > el.width()) {	
						el.find('img').draggable({ containment:[limitLeft, limitTop, limitRight, limitBottom ] });
						
						// cursor
						el.find('img').css('cursor','move');
					}
				} else {
					// cursor
					el.find('img').css('cursor','default')
					              .removeClass('type-zoom');
					
					if(el.find('img').attr('data-width') < el.width() && el.find('img').attr('data-height') > el.height()) {
						el.find('img').draggable("option", "axis", "y");
						
						// cursor
						el.find('img').css('cursor', 'n-resize');
						
					} else if(el.find('img').attr('data-height') < el.height() && el.find('img').attr('data-width') > el.width()) {
						el.find('img').draggable("option", "axis", "x");
						
						// cursor
						el.find('img').css('cursor', 'e-resize');
					} else if(el.find('img').attr('data-height') > el.height() && el.find('img').attr('data-width') > el.width()) {	
						// cursor
						el.find('img').css('cursor', 'move');
					}		
					
					if(el.find('img').hasClass('ui-draggable')) {
						el.find('img').draggable('enable');
					}				
					
				}
					
				// "rebind" click
				el.click(function(e){
					zoomInZoomOutImage($(this), e)
				});
				
				$('#productLargeImage figcaption').html('Clique para reduzir');
			// adiciona a classe zoom-in em #currentImage	
			}).end().addClass('zoom-in');
			        
		
		// senão é para tirar o zoom da imagem
		} else {
			el.find('img')
			  .animate({ 
				maxWidth: el.find('img').attr('data-small-width') + 'px',
				maxHeight: el.find('img').attr('data-small-height') + 'px',
				top : parseInt(402 - el.find('img').attr('data-small-height')) / 2 + 'px', 
				left: parseInt(el.parents('#main').width() - el.find('img').attr('data-small-width')) / 2 + 'px'
			}, function(){
				el.click(function(e){
					zoomInZoomOutImage($(this), e)
				});
				
				el.find('img').addClass('type-zoom');
				
				$('#productLargeImage figcaption').html('Clique para ampliar');
				
			// remove a classe zoom-in de #currentImage	
			}).end().removeClass('zoom-in') ;
			
			if(el.find('img').hasClass('ui-draggable')) {
				// desabilita o drag
				el.find('img').draggable('disable')
			}
		}
	}
	
	/**
	 * @method colorNav
	 */
	function colorNav() {
		var productInfo   = $('#productInfo'),
			productImages = $('#productImages'),
			currentImage  = productImages.find('#currentImage img'), 
		    el, href, loadingColor, title, totalImages;		
		
		productInfo.find('ul a').click(
			function() {
				href = project.basics.parseQueryString($(this).attr('href'));
				
				if(!$('#loadingColor')[0]) {
					$('#main').append('<div id="loadingColor" class="products-loading" style="display:none;"></div>');
					$('#loadingColor').css('opacity', 0.8);
				}
				
				loadingColor = $('#loadingColor');
				loadingColor.fadeIn();
				
				$.get(document.location.href, { color:href.color.toString(), ajax:true }, function(data){
					$('#productInfo h2:eq(0), #currentImage img, #productImages nav ul li').hide();
					productImages.find('nav ul').empty();
					
					productInfo.find('h2:eq(0)').html('Código ' + $('color', data).attr('code') + ' <span class="upper">' + $('color name', data).text() + '</span>').fadeIn();
					
					project.basics.preloadImage(rootUrl + 'public/upload/products/' + $('color', data).attr('product-slug') + '/' + $('color', data).attr('slug') + '/details/' + $('img[featured="1"]', data).attr('detail'),
						function(src) {
							currentImage.attr('src', src);
							currentImage.fadeIn();
						}	
					);
					
					totalImages = $('img', data).length - 1;
					
					$('img', data).each(
						function(i) {
							el = $(this);
							
							project.basics.preloadImage(rootUrl +'public/upload/products/'+ $('color', data).attr('product-slug') + '/' + $('color', data).attr('slug') + '/thumbs/' +  el.attr('thumb'),
								function(src) {
									productImages.find('nav ul').append('<li><a href="javascript:void(0)" data-image="'+ rootUrl +'public/upload/products/'+ $('color', data).attr('product-slug') + '/' + $('color', data).attr('slug') + '/details/' + el.attr('detail')+'"><img src="'+ src +'" alt="" /></a></li>');
								
									if(i == totalImages) {
										loadingColor.fadeOut();
										productImages.find('nav li').fadeIn();
									}
								}	
							);						
						}
					);

					title = $('title').html().split('-');
					document.title = title[0] + '-' + title[1] + ' - ' + $('color name', data).text();
				});				
				
				
				return false;
			}
		);
	}
	
	
	return {
		/**
		 * @method acessibleMainMenu - deixa os submenus do menu principal do site acessível pela navegação por tab
		 */
		acessibleMainMenu: function() {
			var menuParent = $('#menu .parent');
			
			// quando qualquer link do menu receber o evento focus...
			menuParent.find('a').focus(
				function () {
					$(this).parents('.parent').addClass('selected')
					       .siblings('.parent').removeClass('selected');
				}
			)
			
			// quando um dos itens pais do menu(link) receber o evento clique...
			menuParent.find('h2 a').click(
				function() {
					return false;
				}
			);
			
			// quando um dos itens pais do menu(li) receber o evento mouseenter...
			menuParent.mouseenter(
				function() {
					$(this).addClass('selected')
				           .siblings('li').removeClass('selected');
				}	
			
			// quando um dos itens pais do menu(li) receber o evento mouseleave...
			).mouseleave(
				function() {
					$(this).removeClass('selected');
				}
			);
			
			// quando o foco sair de um item do menu...
			$('body > header a, body > header input').focus(
				function() {
					if(!$(this).parents('#menu')[0])
						menuParent.removeClass('selected');	
				}
			);
		},
		
		
		/**
		 * @method textReplacement - substitui alguns textos por fontes que não são de sistema
		 */
		textReplacement: function() {
			// js cufon
			Cufon.replace('#menu h3, #eventInfo h1, #viewEventSite, #soccer #content h1, #soccerDescription, #viewSoccerSite, #athlete #content h1');
			Cufon.now();
		},
		
		
		/**
		 * @method productDetails
		 */
		productDetails: function() {
			// ações relacionadas a visualização das imagens do produto
			imageDetails();
			
			// navegação pelas cores do site
			colorNav();
		},
		
		
		/**
		 * @method easyToneHotsite
		 */
		easyToneHotsite: function() {
			var player = $('#player');
			
			$('#easyToneVideos a').click(
				function() {
					player.slideToggle();
					
					return false;
				}	
			);
			
			player.find('a').click(function(){
				player.slideUp();
				
				return false;
			}) 
		},
		
		
		/**
		 * @method zigTechHotsite
		 */
		zigTechHotsite: function() {
			var zigTechProducts = $('#zigTechProducts'),
			    el; 
			
			zigTechProducts.find('.list:eq(0)').jcarousel({
		       wrap: 'last',
		       visible: 3
		    });
			
			zigTechProducts.find('.list ul:eq(0) a').click(
				function() {
					return false;
				}
			);
			
			zigTechProducts.find('#zigTechLines a').click(
				function() {
					el = $(this);
					
					el.addClass('selected').siblings('a').removeClass('selected');
					
					$(el.attr('href')).fadeIn().siblings('.list').hide();
					
					if($(el.attr('href')).find('li').length > 3 && !$(el.attr('href')).find('.jcarousel-clip')[0]) {
						$(el.attr('href')).jcarousel({
							wrap: 'last',
							visible: 3	
					    });
					}
					
					return false;
				}	
			);
		}
	}
})(jQuery);


/**
  * jQuery Init
  */
jQuery(document).ready(
    function() {
		/*
		 * Funções padrões para todas as páginas
		 */
    	
    	$('body').addClass('js').removeClass('no-js');
    	
    	// menu acessível pela navegação por tab
    	project.userInterface.acessibleMainMenu();
    	
    	// ações conforme atributos e eventos de alguns links
		project.basics.links();
		
		// placeholder crossbrowser
		project.basics.placeholder();
		
		// ações referente ao formulário de busca
		project.forms.searchForm();
		
		
		/*
		 * Funções específicas para determinadas páginas
		 */
		
		// Produtos - listagem
		if($('#products')[0]) {
			project.forms.productsList();
		}
		
		// Produtos - detalhes
		if($('#productDetails')[0]) {
			project.userInterface.productDetails();
		}
		
		// Busca - listagem
		if($('#searchResults')[0]) {
			project.forms.searchList();
		}
		
		// Hotsites - easytone
		if($('#easytone')[0]) {
			project.userInterface.easyToneHotsite();
		}
		
		// Hotsites - zigtech
		if($('#zigtech')[0]) {
			project.userInterface.zigTechHotsite();
		}
	}
);

jQuery(window).load(function(){
	// cufon
	project.userInterface.textReplacement();
});
