// JavaScript Document
$(function(){
	$("#q").val("Hitta en produkt");
	//alert("I'm loaded...");
	$('#results').hide();
	$("#q").keyup(function(){
		var str = cleanString($('#q').val());
		$('#q').val(str);
		if(str != " "){
			sendData($('#q').val());
		} else {		
			$('#results').hide();
		}
	});
	$("#submit").click(function(event){
		if ($("#q").val() != 'Hitta en produkt'){
			doSearch($('#q').val());
		} else {
			$("#q").val();
		}
		event.preventDefault();
	});
	$("#q").focus(function(){
		if ($(this).val() == 'Hitta en produkt'){
			$(this).val('');
		}
		$("#search").addClass("open");				   
		showResults();
	});
	$("#q").blur(function(){
		if ($(this).val() == ""){
			$(this).val('Hitta en produkt');
		}
		$("#search").removeClass("open");		  
		$('#results').fadeOut();	
	});
	
});

function cleanString(tstr){
var nono = new Array("/", "*", "!", '\\', "(", ")", "[", "]", "{", "}", "#","$","%","^","&","@","|",";",":","'","\'","\"","=","+","<",">","?","_",",",".");
	for(var i = 0; i <= nono.length-1; i++){
		tstr = tstr.replace(nono[i], "");	
	}
	return tstr;
}

function sendData (str) {
	$("#load").show();	
	if(str != ""){
		var url = 'ajax/products.php';
		//var pars = "q="+str;
		$.ajax({ 
		      'url': url, 
		      'data': {'q': str}, 
		      'dataType': 'text', 
		      'type': 'GET', 
		      'success': function(data) { 
		          	$('#load').hide();
					$('#results').html(data);
		         	$('#results').show();
				}
		}); 
		
	
	//	var myAjax = new Ajax.Request( url, {method: 'get', parameters: pars, onLoading: show('load'), onComplete: showResponse} );
	}
}

function toggle(myDiv){
	
	if($(myDiv).style.display == "none") {
		$(myDiv).style.display = "inline-block";
	} else {	
		$(myDiv).style.display = "none";
	}
}

function show(myDiv){
	$(myDiv).style.display = "block";
}
function hide(myDiv){
	$(myDiv).style.display = "none";
}
function showResults() {
	if($('#q').val() != ' '){
		$("#results").fadeIn("medium");
	}
}
function doSearch(value) {
	value = value.replace("/&/g","AND");
	url = "search.php?q="+value;
  this.location.href = (url);
}
