// JavaScript Document


//SOURCE JQUERY

//http://php4every1.com/tutorials/jquery-ajax-tutorial/
//http://stackoverflow.com/questions/3904896/asynchronous-ajax-query-with-jquery
//http://api.jquery.com/jQuery.ajax/
//http://stackoverflow.com/questions/4716398/jquery-load-ajax-request-on-keyup-no-arrowkeys
//http://stackoverflow.com/questions/6142887/jquery-keyup-ignore-non-changing-characters
//http://docs.jquery.com/Specifying_the_Data_Type_for_AJAX_Requests

var xhr1;
$(document).ready(function(){
	
	var objReturn = 'HTMLobj';
	function displayRequest(data){
		if(data!=null){
			$('#waiting').hide();
			if(objReturn == 'JSONobj'){
				$('#message').removeClass().addClass((data.error === true)?'error':'success').text(data.msg).show(700);//Json
			} else if(objReturn == 'HTMLobj'){
				$('#message').empty().html(data).show(700); //return html
			}
		}else{
			//$('#message').empty().html('error').show(700);//JSON,HTML
		}	
	}
	$('#searchfield').bind('keyup',function() {
		if ($('#searchfield').val() != '') {
			$('#waiting').show();
			$('#divblock').show();
			$('#message').hide();
			
			if(xhr1 != null ){
				xhr1.abort(); //stop last ajax
			}
			
			xhr1 = $.ajax({
				type : 'POST',   
				//private function don't work
				url : '/produits/searchproduct',
				//document.body, xml, html, script, json   
				//important to firefox return good object
				dataType : (objReturn=='HTMLobj')?'html':'json', 
				//data: "name=John&location=Boston",
				data: {
					searchfield : $('#searchfield').val(), //lonely POST
					searchReturn : objReturn,
					ajaxDebug : false
				},
				//async:true,
				//cache:false,
				//timeout:10000,
				//beforeSend:function(){},
				//whileLoading: function(){},
				complete : function(xhr1, status) {
					$('#profil_waiting').hide();
				},
				success : function(data){
					displayRequest(data);
				},
				error : function(XMLHttpRequest, textStatus, errorThrown) {
					displayRequest(null);
				}
	
			});
			//return false; //IE problem
		} else {
			displayRequest(null);
		}
	});
	
	
});
    
	
	
	
	
