$(function(){		
	var x;
	x = $(document);
	x.ready(inicializarEventos);
	
	function inicializarEventos(){
		var x;
	  	x=$("#btnBuscar");
	  	x.click(presionBtnBuscar);
	  	x.mouseover(situarBtnBuscar);
	}
	
	function situarBtnBuscar(){		
		var x;
	  	x=$("#btnBuscar");
	  	x.css("cursor","pointer");
	}	
				  
	function presionBtnBuscar(){						
		pClave = document.getElementById('pCercador').value;	
		lon = pClave.length;
		if (lon < 3){
			alert("La consulta debe tener como minimo tres caracteres");		
		}else{
			document.cercador.submit();
		}	  		  		  	  	
	}
	
	function validar(e) {    		
		tecla = (document.all) ? e.keyCode : e.which;
		if (tecla==13) {
			pClave = document.getElementById('pCercador').value;	
			lon = pClave.length;	
			if (lon < 3){
				alert("La consulta debe tener como minimo tres caracteres");
				return false;				
			}else{
				enviar_datos();
			}
		}	  
	}	

	$("#pCercador").completar({		
		url: "http://www.fotoprix.com/autocompletar.php",
		type: "GET",
		data: "pCerca",		
		autoChange: true
	});

});


function validTxt(){	
	texto = txt.replace(/ /g, " ");
	texto = texto.substr(0,texto.lastIndexOf(" "));
	texto = texto.replace(/  /g," ");	
	return texto;
}

(function($) {
		  
	$.fn.completar = function(options) {		
		var opts = $.extend({}, $.fn.completar.defaults, options);		
		var jH = ".jSuggestHover";
		var jsH = "jSuggestHover";
		var iniVal = this.value;
		var textBox = this;
		var textVal = this.value;	
		var jC = "#jSuggestContainer";
		
		//$("body").append('<div id="jSuggestContainer"></div>');
		$(jC).hide();
		
		$(this).bind("keyup click", function(e){
													
			textBox = this;
			textVal = this.value;
									
			if (this.value.length >= opts.minchar && $.trim(this.value)!="Search Terms") {
				var offSet = $(this).offset();
				var w = 288;	
				
				if(document.body.clientWidth > 930){					
					var izq = document.body.clientWidth/2-(w/2)+79 + "px";
				}else{
					var izq = 396+'px';
				}

				
				var pC  = "splashLayer";								
				var tpo = 271;
				$("div:visible").each( function(){
				    if (this.id=="splashLayer"){
				    	tpo = 425+'px';				    	
				    }
				} 
				);	
				
															
				$(jC).css({		
					top: tpo,				
					left: izq,
					position: "absolute",										
					opacity: opts.opacity,
					zIndex: opts.zindex
				}).show();
				
								
				// esc
				if (e.keyCode == 27 ) {
					$(jC).hide();
				}
				
				// enter
				else if (e.keyCode == 13 ) {
					
					validar(e.keyCode);
					
					if ($(jH).length == 1)
						$(textBox).val($(jH).text());
						$(jC).hide();
						iniVal = textBox.value;						
						txt = $(jH).text();							
						texto = txt.replace(/ /g, " ");
						texto = texto.substr(0,texto.lastIndexOf(" "));
						texto = texto.replace(/ /g," ");
						$(textBox).val(texto);												
						
				}
				
				// bajar
				else if (e.keyCode == 40) {
					// si hay alguna opción marcada en el desplegable
					if ($(jH).length == 1) {
						if (!$(jH).next().length == 0) {
							$(jH).next().addClass(jsH);
							$(".jSuggestHover:eq(0)").removeClass(jsH);														
							if (opts.autoChange)								
								txt = $(jH).text();															
								validTxt(txt);	
								texto = texto.replace(/  /g," ");														
								$(textBox).val(texto);								
						}
					}
					else {
						$("#jSuggestContainer ul li:first-child").addClass(jsH);
						if (opts.autoChange)							
							txt = $(jH).text();														
							texto = validTxt(txt);														
							texto = texto.replace(/  /g," ");
							$(textBox).val(texto);														
					}
					
				}

				// subir
				else if (e.keyCode == 38) {
					// si hay alguna opción marcada en el desplegable
					if ($(jH).length == 1 ) {
						if (!$(jH).prev().length == 0) {
							$(jH).prev().addClass(jsH);
							$(".jSuggestHover:eq(1)").removeClass(jsH);
							if (opts.autoChange)								
								txt = $(jH).text();							
								texto = validTxt(txt);
								texto = texto.replace(/  /g," ");
								$(textBox).val(texto);								
						}
						// if is first child
						else {
							$(jH).removeClass(jsH);
							$(textBox).val(iniVal);
						}
					}
				}
				
				// nueva consulta al servidor (la petición al servidor se realiza a cada tecla que se añade/quita de la keyword)								 							
				// c - ca - can - cano - canon - cano -> esto realiza 6 consultas al servidor				
				else if (textBox.value != iniVal){										
					iniVal = textBox.value;					
					
					if ($(".jSuggestLoading").length==0)
						$('<div class="jSuggestLoading"><img src="'+opts.loadingImg+'" align="bottom" /> '+ opts.loadingText+'</div>').prependTo("#jSuggestContainer");						
															
					// DIV del Cargando ...	
					// $(".jSuggestLoading").show();
					$(".jSuggestLoading").hide();
					$(jC).find('ul').remove();					
					opts.data = $(this).serialize();							
					
					setTimeout(function () {						
						$.ajax({
							type: opts.type,
							url: opts.url,
							data: opts.data,							
							success: function(msg){
								$(jC).find('ul').remove();
								$(jC).append(msg);
								$("#jSuggestContainer ul li").bind("mouseover",	function(){
										$(jH).removeClass(jsH);
										$(this).addClass(jsH);
										textVal = $(this).text();
										if (opts.autoChange)											
											txt = $(jH).text();							
											texto = validTxt(txt);
											texto = texto.replace(/  /g," ");
											$(textBox).val(texto);											
								});
								$("#jSuggestContainer ul li").click(function(){									
									$(this).addClass(jsH);									
									txt = $(jH).text();							
									texto = validTxt(txt);
									texto = texto.replace(/  /g," ");
									$(textBox).val(texto);																										
									// hacemos submit del formulario al clicar con el enter en la opción																											
									document.cercador.submit();																		
								});
								$(".jSuggestLoading").hide();
							}
						});
					}, opts.delay); 
																				
				}
			}
			// Si el texto es más corto que el valor de minchar, no se busca nada
			else {
				$(jH).removeClass(jsH);
				$(jC).hide();
			}
						
			return false;
		});
		
		$(document).bind("click", function(){
			$(jC).hide();
			iniVal = textBox.value;
		});
		
	};
	
	$.fn.completar.defaults = {
		minchar: 1,
		opacity: 1.0,
		zindex: 20000,
		delay: 0,
		loadingImg: 'http://www.fotoprix.com/img/autocompletar/ajax-loader.gif',
		loadingText: 'Loading...',
		autoChange: false,
		url: "http://www.fotoprix.com/autocompletar.php",
		type: "GET",
		data: ""
	};
		
	
		  

})(jQuery);