$(function(){
	/**
	 * 
	 */
	jQuery.fn.products = function(settings){
		
		//----------------------------------------------------------------------
		//
		// Variáveis
		//
		//----------------------------------------------------------------------
		
		/**
		 * Variável de configuração. 
		 */
		var opt = {
			idCategory:0,
			target:'', 
			categoryTitle:'', 
			templateProduct:'',
			rows:20, 
			page:1, 
			paginationTarget:'',
			paginationTarget:'', 
			useStock:true, 
			pesquisa:''
		}
		
		/**
		 * Total de páginas.
		 */
		var totalPages = 0;
		
		/**
		 * Total de produtos.
		 */
		var totalRows = 0;
		
		/**
		 * Nome da categoria.
		 */
		var categoryName = '';
		
		/**
		 * Estende a array de configurações.
		 */ 
		jQuery.extend(opt, settings);
		
		//----------------------------------------------------------------------
		//
		// Métodos
		//
		//----------------------------------------------------------------------
		
		/**
		 * Monta a celula do produto.
		 */
		function generateCell(productList, totalProducts, totalPages, htmlData) {
			
			// Define o complemento do plural / singular. 
			var complement = (totalProducts > 1)?('S'):('');
			$('#quantidade-listados').html(totalProducts+' PRODUTO'+complement);
			
			// Efetua o loop sobre os produtos recuperados.
			for(var i = 0; i < productList.length; i++) {
				
				// Define as informações do produto.
				var productData = productList[i];
				
				// Verifica se é necessário mostrar o valor "de"
				var usePromotionalValue = false;
				if(productData.sellValue < productData.thanValue) {
					usePromotionalValue = true;
				}
				
				var soldOut = false;
				
				// Verifica se existe quantidade disponível e se o produto utiliza estoque.
				if(productData.quantity <= 0 && productData.useStock && opt.useStock) {
					soldOut = true;
				}
				
				// Efetua o replace das tags predefinidas.
				var newHtml = htmlData.replace('<useSellValue>', (usePromotionalValue)?('block'):('none'));
				
				newHtml = newHtml.replace('<noQuantity>', (soldOut)?('block'):('none') );
				newHtml = newHtml.replace('<hasQuantity>', (!soldOut)?('block'):('none') );
				newHtml = newHtml.replace('<idProperty>', productData.idProperty);
				newHtml = newHtml.replace('<idProduct>', productData.idProduct);
				newHtml = newHtml.replace('<longName>', productData.longName);
				newHtml = newHtml.replace('<shortDescription>', productData.shortDescription);
				newHtml = newHtml.replace('<image>', productData.image);
				newHtml = newHtml.replace('<currencySymbol>', productData.currencySymbol);
				newHtml = newHtml.replace('<linkName>', productData.linkName);
				
				newHtml = newHtml.replace('<sellValue>', currency.format(productData.sellValue));
				newHtml = newHtml.replace('<thanValue>', currency.format(productData.thanValue));
				
				// Efetua a inclusão da celula no componente html.
				$(opt.target).append(newHtml);
				
				// Mostra a celula inclusa.
				$('#product-'+productData.idProperty).fadeIn('slow');
			}
		}
		
		/**
		 * Função para apresentação da tela de sem produtos.
		 */
		function noProducts() {
			
			// Mostra a mensagem de sem produtos... 
			$(opt.target).html('Nenhum produto encontrado');
		}
		
		/**
		 * Função para se mostra a páginação.
		 */
		function showPagination() {
			
			// Verifica se não foi definido nenhum template
			if(opt.paginationTemplate == '' || opt.paginationTarget == '') {
				$.showError("ERRO!", opt.paginationTemplate);
				return;
			}
			
			// Recupera o template a ser utilizado.
			$.get(opt.paginationTemplate, function(htmlData){
				
				var paginas = '';
				
				// Recupera o rash da url atual.
				var urlRash = document.location.hash;
				urlRash = urlRash.substring(1);
				
				// Recupera o querystring definido.
				var stringComposition = urlRash.split("?");
				
				if(stringComposition != '') {
					
					stringComposition = stringComposition[1];
				
					// Separa pelo & comercial.
					var variables = stringComposition.split("&");
					
					// Cria as variáveis a serem alocada os valores.
					var hasPagina = false;
					
					var variable = '';
				
					// Efetua o loop sobre as variáveis recebidas.
					for(var i=0; i < variables.length; i++) {
						var variableSplit = variables[i].split("=");
						var variableName = variableSplit[0];
						var variableValue = variableSplit[1];
						
						if(variableName == 'pagina') {
							variable = variables[i];
							hasPagina = true;
						}
					}
				}
				
				// Verifica se a quantidade de páginas é superior a 1.
				if(totalPages > 1) {
					
					// Gera os itens das paginas.
					for(var i=0; i < totalPages; i++ ) {
						
						var newUrl = urlRash+"&pagina="+(i+1);
						
						if(hasPagina) {
							newUrl = urlRash.replace(variable, 'pagina='+(i+1));
						}
						
						var classString = '';
						
						// Verifica se é a página atual.
						if( (i+1) == opt.page) {
							classString = 'class="selecionado"';
						}
						
						if( (i+1) != opt.page) {
							paginas+='<a href="#'+newUrl+'">';
						}
						
						// Incrementa a string de página.
						paginas+= '<li '+classString+'>'+(i+1)+'</li>';
						
						if( (i+1) != opt.page) {
							paginas+='</a>';
						}
					}
					
					// Páginas a serem listadas.
					var formatedHtml = htmlData.replace('<paginas>', paginas);
					formatedHtml = formatedHtml.replace('<total-paginas>', totalPages);
					formatedHtml = formatedHtml.replace('<pagina-atual>', opt.page);
					
					// Efetua o replace
					$(opt.paginationTarget).html(formatedHtml);
					
				}				
				
			});
			
		}
				
		/**
		 * Esconde o preloader.
		 */
		function hidePreload() {
			$(opt.target).html('');
		}
				
		/**
		 * Efetua a recuperação dos dados.
		 */
		function ajaxGetProducts() {
			
			// Código da categoria ser recuperada.
			var idCategory = opt.idCategory;
			
			// Define a url a ser chamda 
			var url = "/entryPoint.php?class=ProductSearchWebAjax&method=getByCategory";
			var params = "idCategory="+idCategory+"&page="+opt.page+"&rows="+opt.rows;
			
			// Verifica se a categoria é 0...
			if(idCategory == 0) {
				url = "/entryPoint.php?class=ProductSearchWebAjax&method=getFirstPage";
			}
			
			// Verifica se existe a pesquisa...
			if(opt.pesquisa !== '') {
				url = "/entryPoint.php?class=ProductSearchWebAjax&method=search";
				params = "term="+opt.pesquisa+"&page="+opt.page+"&rows="+opt.rows;
			}
			
			// Chamada em ajax.
			$.ajax({
				type:"POST",
				dataType:"xml",
				data:params,
				url:url,
				
				// Trata o erro.
				error:function(XMLHttpRequest, textStatus, errorThrown) {
					$.showError("ERRO!", XMLHttpRequest.responseText);	
				},
				
				// Exibe o 'aguarde...'.
				beforeSend: function(){
					
					// Mostra o preloader..
					$.showPreload('Aguarde...', false, 200, 0, false);
				},
				
				// Trata o retorno em caso de sucesso.
				success: function(data, textStatus, XMLHttpRequest){
					
					// Verifica se retornou erro.
					if( $(data).find('error').text()) {
						$.showError("ERRO!", XMLHttpRequest.responseText);
						return;
					}
					
					var productList = new Array();
							
					// Efetua o loop para cada produto recebido.
					$(data).find('product').each(function() {
						var productData = new Array();
						productData['idProduct'] = $(this).find('idProduct').text();
						productData['shortDescription'] = $(this).find('shortDescription').text();
						productData['longName'] = $(this).find('longName').text();
						productData['unitSymbol'] = $(this).find('unitSymbol').text();
						productData['unitPrecision'] = $(this).find('unitPrecision').text();
						productData['idImage'] = $(this).find('idImage').text();
						productData['hideValue'] = $(this).find('hideValue').text();
						productData['compositionType'] = $(this).find('compositionType').text();
						productData['currencySymbol'] = $(this).find('currencySymbol').text();
						productData['classType'] = $(this).find('classType').text();
						productData['quantity'] = $(this).find('quantity').text();
						productData['idProperty'] = $(this).find('idProperty').text();
						productData['sellValue'] = $(this).find('sellValue').text();
						productData['image'] = $(this).find('image').text();
						productData['thanValue'] = $(this).find('thanValue').text();
						productData['linkName'] = $(this).find('linkName').text();
						productData['useStock'] = $(this).find('useStock').text();
						
						productList.push(productData);
					});
					
					// Recupera o total de páginas.
					totalPages = $(data).find('totalPages').text();
					
					// Recupera o total de páginas.
					totalRows = $(data).find('totalRows').text();
					
					// Recupera o nome da categoria.
					$(data).find('category').each(function(){
						categoryName = $(this).find('name').text();
						
						// Define o título da categoria.
						$('#titulo-categoria').html(categoryName);
						$('#titulo-categoria').show('slow');
					});
					
					// Verifica se existem produtos a serem listados.
					if(totalRows > 0) {
						
						// Recupera o html utilizado.
						$.get(opt.templateProduct, function(htmlData){
							
							// Esconde o preloader.
							hidePreload();
							
							// Após recuperar o html a ser utlizado repassa as 
							//informações para o método
							generateCell(productList, totalRows, totalPages, htmlData);
							
							if(totalPages > 1) {
								
								// Mostra a páginação.
								showPagination();
							} else {	
								// Efetua o replace removendo as informações de paginação.
								$(opt.paginationTarget).html('&nbsp');
							}	
						});
					} else {
						
						// Mostra a tela de produto não avaliado.
						noProducts();
						
						// Efetua o replace removendo as informações de paginação.
						$(opt.paginationTarget).html('&nbsp');
					}
				}, 
				
				complete: function() {
					$.closePreload();
				}
			});
		}
		
		//----------------------------------------------------------------------
		//
		// Main
		//
		//----------------------------------------------------------------------
		return this.each(function(){
			
			// Efetua o ajax para recuperação das informações de acordo com o 
			//código da categoria recebida.
			ajaxGetProducts();					
		});
	}
	
});
