var timer;
var auth;

function livesearch(){
	
	check_auth();
	
	$('#livesearch_searchtext').keyup(function() {
		
		st = $('#livesearch_searchtext').val();
		
		
		if(st.length < 2){
			$("#results").empty();
		}
		
		if(st.length > 1){
			window.clearInterval(timer);
			timer = window.setInterval(function() {
					_run_livesearch();
					
					//count
					//count_hitengine();
					
					window.clearInterval(timer);	
			}, 450);
		}
	});	
		
	$('.select_searchmode').click(function(){		   
			_run_livesearch();
	});
	

}



function check_auth(){

	$.ajax({
	   type: "GET",
	   url: "http://"+window.location.hostname+"/modules/rp24_global/ajax/ajax.check_auth.php",
	   data: "search_phrase="+$('#livesearch_searchtext').val(),
	   success: function(msg){
			if(msg == 'true'){
				auth = true;
			}else{
				auth = false;
			}
	   }
	 });
}

function create_fuzzy_link(data){
	$('.fuzzy_link').empty();
	//console.log(data['auto_completion']);
	if(typeof(data['auto_completion']) != 'undefined'){
		$('.fuzzy_link').empty();
		//fuzzy = $('#completions_id_0').attr('ref');
		//console.log(fuzzy);
		//alert(data['auto_completion']);
		$('#livesearch_form_block').append('<p class="fuzzy_link">'+$('#tl_meinten_sie').val()+' <a href="#" style="font-style:italic;font-weight:bold;color:#be140f" onclick="select_completion(\''+data['auto_completion']+'\');">'+data['auto_completion']+'</a></p>');
	}
}

function replace_search_text_top_form(){
		suchenin = $('#tl_Suchen_in').val();
		//suchen_in = 'test';
		suchwort = $('#livesearch_searchtext').val();
		//console.log(suchwort);
		suchen_in_replaced = SuchenUndErsetzen(suchenin,'%%var%%',suchwort);
		$('#suchen_in').html(suchen_in_replaced);
		
}

var filter_form_flag = false;
function create_additional_filter_form(){		

	
	if(filter_form_flag == false){	
		
		
		html = '<div id="dialog_message_product_alert" style="display:none" title="'+$('#tl_product_alert_msg_head').val()+'"><p><span class="ui-icon ui-icon-circle-check" style="float:left; margin:0 7px 50px 0;"></span></p><p id="product_alert_msg_p"></p></div>';
		
		if(auth == true){
			product_alert_click_func = 'store_product_alert_user';
		}else{	
			product_alert_click_func = 'store_product_alert';
		}
		
		html += '<div id="product_alert_form" style="margin:18px 0 18px 0"><input name="alert_search_phase" id="alert_search_phase" type="hidden" value="" />Ich möchte über neue Artikel die das Suchwort <span id="alert_search_phase_word"></span> enthalten per E-Mail benachrichtigt werden: <input name="store_product_alert_submit" class="button" value="Speichern" id="store_product_alert_submit" type="button" onclick="'+product_alert_click_func+'()" /></div>';

		html += '<div id="livesearch_form_block"><form id="livesearch_form" name="livesearch_form" method="post" action="">'+"\n"+
        '<span id="suchen_in"></span> <input name="searchmode" type="radio" id="full" value="full" checked="checked" class="select_searchmode" onclick="_run_livesearch()" />'+"\n"+
       '<label for="volltext">'+$('#tl_volltext').val()+'</label>'+"\n"+
        '<input type="radio" name="searchmode" id="title" value="title" class="select_searchmode"  onclick="_run_livesearch()" />'+"\n"+
        '<label for="volltext">'+$('#tl_titel').val()+'</label>'+"\n"+
         '<input type="radio" name="searchmode" id="text" value="text" class="select_searchmode"  onclick="_run_livesearch()"  />'+"\n"+
       ' <label for="volltext">'+$('#tl_beschreibung').val()+'</label>  '+"\n"+     
   ' </form></div>'+"\n"+
   '<div class="livesearch_pager"></div><div id="results"></div><div class="livesearch_pager"></div>';
   		$('#mitte').empty();
		$('#mitte').append('<div id="content"><h1>'+$('#tl_livesuche').val()+'</h1><div id="content_center"></div></div>');
		$('#content_center').append(html);
		filter_form_flag = true;
		
		//gen ordering button
		ordering_button();	
	}
	
	
	
}

function ordering_button(){
		//http://87.106.9.75:8888/?q=test*%20:ordering:offers_price:*&rd=2&c=0&h=10
		$('#livesearch_form_block').append('<div id="search_button" style="margin:3px 0 3px 0;"><a href="#" onclick="toggle_sort()" class="sort_price">'+$('#tl_sortieren').val()+'</a></div>');
}


function _run_livesearch(){
	//create additional form
	create_additional_filter_form();
	
	replace_search_text_top_form();
	
	filter = get_filter_mode();			
	get_main_grid(st,false,filter,false,true);	
	//append fuzzy link
}

function reset_filter(){
	get_main_grid(st,false,false,false,true);
}


var last_facet;
var order = false;
var global_facet = false;
function get_main_grid(st,facet,filter,f,load_facets){

		
		if(st == ''){
				return false;	
		}
		
		if(f == false){
			hs = '&f=0';
		}else{
			hs = '&f='+f;
		}
		
		if(facet == false){
			facet_string = '';
		}else{
			facet_string = '&facet='+facet;
			global_facet = facet;
			//last_facet = facet;
		}
		
		if(order == false){
			order_string = '';
		}else{
			//console.log(order);
			order_string = '&order='+order
		}
		
		if(filter == false || filter == ''){
			filter_string = '&filter='+get_filter_mode();
		}else{
			filter_string = '&filter='+filter
		}
		

		
		//build querystring
		query_string = "q="+st+facet_string+order_string+filter_string+hs;
		//console.log(query_string );
		
		$('#alert_search_phase').val($('#livesearch_searchtext').val());
		$('#alert_search_phase_word').html($('#livesearch_searchtext').val());
		
		
				$.ajax({
				  url: "modules/rp24_global/ajax/ajax.hitengine_get_grid.php",
				  dataType: "json",
				  data: query_string,
				  success: function(data){

				  //empty result div
				  $("#results").empty();
				  
				    if(typeof(data[0])!="undefined"){
	 	
					//$("#results").append('<table cellspacing="0" class="table_singlecat">');
					
					for(i=0;i<data.length;i++){
						html = "		<tr class=\"usertable_td_2\">"+ "\n" +
			"<td class=\"table_singlcat_td_img\">"+data[i]['offers_fotos']+"</td>"+ "\n" +
			"<td class=\"table_singlcat_td_title\">"+ "\n" +
            "<table>"+ "\n" +
                    "<tr style=\"height:12px\">"+ "\n" +
                        "<td colspan=\"3\" class=\"table_singlecat_subtable_title\">"+ "\n" +
						"<a href=\"/index.php?mod=rp24_global&amp;mode=view_article&amp;nr="+data[i]['offers_id'][0]+"\" onclick=\"window.open(this.getAttribute('href'));return false;\" style=\"font-size:14px; font-weight:bold;\">"+data[i]['offers_title'][0]+"</a>"+ "\n";
                        
					if(data[i]['user_proofed_membership'][0] > 0){
						html += "<img src=\"templates/rp24/images/goldseller_24px.gif\" class=\"table_singlecat_subtable_goldseller\"  alt=\"Goldseller Logo\" height=\"15\" width=\"15\"  /></td>"+ "\n";
					}
                   html += "</tr>"+ "\n" +
                    "<tr>"+ "\n" +
                        "<td  class=\"table_singlecat_subtable_price\"><strong>"+data[i]['offers_price'][0]+" "+data[i]['currency']+" </strong>"+data[i]['unit']+"</td>"+ "\n" +
                        "<td  class=\"table_singlecat_subtable_date\">"+data[i]['offers_amount'][0]+" "+data[i]['units']+" "+data[i]['verfuegbar']+"</td>"+ "\n" +
                       "<td  class=\"table_singlecat_subtable_viewed\">"+data[i]['mindestabnahme']+": "+data[i]['offers_min_purch'][0]+"</td>"+ "\n" + 
                      
                     "</tr>  "+ "\n" +                          
                      "<tr>"+ "\n" +
                        "<td class=\"table_singlecat_subtable_cat\" colspan=\"2\">"+data[i]['breadcrump']+"</td>"+ "\n" +

					   "<td></td>"+ "\n" +
                   "</tr>"+ "\n" +
                "</table></td>"+ "\n" +
		        "</tr>";
						$("#results").append(html);						
					}
					//$("#results").append('</table>');
					$(".usertable_td_2").wrapAll('<table cellspacing="0" class="table_singlecat">');	
					
					
					generate_grid_pager(st,facet,filter,f,data[0]['hits']);
				  	}else{
						$("#results").append('<div>Es konnte kein Suchergebnis ermittelt werden. Bitte versuchen Sie es später noch einmal oder <a href="index.php?mod=rp24_global&mode=advanced_search&search=true&advtype=1&col1=1&col2=0">benutzen die herkömmliche Suchefunktion</a></div>');		
					}
					
/*					if(typeof(data) != 'undefined'){
						create_fuzzy_link(data[0]);
					}*/
					$('.table_singlecat').append('<a href="http://www.weitkamper.de" class="hitengine_link">powered by Hitengine</a>');
				  }
				  
				});
				
				
				
				get_completions(st);
				
				if(load_facets == true){
					$('.completions2_link').removeClass('hightlight_clicked');
					get_get_categories_facet_completions(st,false);
					get_get_country_facet_completions(st,false);
				}
		
			
}


function count_hitengine(){
			$.ajax({
			  url: "modules/rp24_global/ajax/ajax.count_hitengine.php",
			  data: query_string,
			  success: function(query){
					//alert(query);		  
			  }
			 });
}


function debug_show_server_query(query_string){

	$.ajax({
	  url: "modules/rp24_global/ajax/ajax.hitengine_get_query.php",
	  data: query_string,
	  success: function(query){
			//console.log(query);			  
	  }
	  });
}



function get_completions(st){

	if(st === ''){
			return false;
	}

	$.ajax({
		  url: "modules/rp24_global/ajax/ajax.hitengine_get_completions.php",
		  dataType: "json",
		  data: "q="+st,
		  success: function(data){
			  $('#categories-left').empty();
			  $('.completions').empty();
			  $('#categories-left').addClass('completions');
			  $('.completions').removeAttr('id');
			  
			  $('.completions').append('<h2>'+$('#tl_wortvorschlaege').val()+'</h2>');
                 if(typeof(data[0])!=="undefined"){

					for(i=0;i<data.length;i++){
						$('.completions').append('<li class="completions1"><a href="#"  class="completions1_link" id="completions_id_'+i+'" ref="'+data[i][0]+'" onclick="select_completion(\''+data[i][0]+'\');">'+data[i][0]+' ('+data[i][1].DC+')</a></li>');
					}

				}else{
				$('.completions').append('<li class="completions1"><a href="#" class="completions1_link">'+$('#tl_leider_keine_treffer').val()+'</a></li>');

				}
				$('.completions1').wrapAll('<ul class="sf-menu sf-vertical sf-js-enabled sf-shadow" />');
		  }
		  });		
}

function select_completion(st){

	$('#livesearch_searchtext').val(st);
	get_main_grid(st,false,false,0,true);
}

function add_filter(facet,filter,data_id,mode){

	if(data_id == false){
		data_id = '';
	}
	query = $('#livesearch_searchtext').val();
	facet = facet+data_id;
	load_facets = false;
	get_main_grid(query,facet,filter,0,load_facets);

}


function toggle_sort(){
	
	$('#sort_arrow').remove();
	 
	if(order == '2a'){
		order = '2';
		$('.sort_price').append('<span id="sort_arrow">&uArr;</span>');
	}else if(order == '2'){
		order = '2a';
		$('.sort_price').append('<span id="sort_arrow">&dArr;</span>');
	}else{
		order = '2a';	
		$('.sort_price').append('<span id="sort_arrow">&dArr;</span>');
	}
	//console.log('global_facet: '+global_facet);
	query = $('#livesearch_searchtext').val();
	
	get_main_grid(query,global_facet,false,0,false);
}


function highlight_obj(obj){

	$('.completions2_link').removeClass('hightlight_clicked');
	$('.completions3_link').removeClass('hightlight_clicked');
	$(obj).addClass('hightlight_clicked');
}


function get_get_categories_facet_completions(st,filter){

	if(st == ''){
			return false;	
	}

	if(filter == false){
		filter_string = '&filter='+get_filter_mode();
	}else{
		filter_string = '&filter='+filter
	}
				
	$.ajax({
		  url: "modules/rp24_global/ajax/ajax.hitengine_get_category_completions.php",
		  dataType: "json",
		  data: "q="+st+filter_string,
		  success: function(data){
			$('#statistic').empty();
			$('.category_completions').empty();
			$('#statistic').addClass('category_completions');
			$('#statistic').removeAttr('id');
			$('.category_completions').append('<h2>'+$('#tl_treffer_in_kategorien').val()+'</h2>');
			
			  	if(typeof(data[0])!="undefined"){				
					$('.category_completions').append('<li class="completions2"><a href="#" class="completions2_link" onclick="reset_filter();highlight_obj(this)">Alle ('+data[0][4]['TOTAL']+')</a></li>');

					for(i=0;i<data.length;i++){
						$('.category_completions').append('<li class="completions2"><a href="#" class="completions2_link" onclick="add_filter(\':facet:offers_categories_id:\',false,'+data[i][3]+',\'categories_facet\');highlight_obj(this)">'+data[i][2]+' ('+data[i][1]['DC']+')</a></li>');
					}
				}else{
					$('.category_completions').append('<li class="completions2"><a href="#" class="completions2_link" >'+$('#tl_leider_keine_treffer').val()+'</a></li>');
				}
				$('.completions2').wrapAll('<ul class="sf-menu sf-vertical sf-js-enabled sf-shadow" />');
		  	}
		  });		
}


function get_get_country_facet_completions(st,filter){

	if(st == ''){
			return false;	
	}

	if(filter == false || filter == ''){
		filter_string = '&filter='+get_filter_mode();
	}else{
		filter_string = '&filter='+filter
	}
	//console.log('get_get_country_facet_completions: '+filter_string );	
	//console.log('filter: '+filter);	
		$.ajax({
			  url: "modules/rp24_global/ajax/ajax.hitengine_get_country_completions.php",
			  dataType: "json",
			  data: "q="+st+filter_string,
			  success: function(data){
				  
				$('#review').empty();
				$('.country_completions').empty();
				$('#review').addClass('country_completions');
				$('#review').removeAttr('id');
				$('.country_completions').append('<h2>'+$('#tl_treffer_in_laendern').val()+'</h2>');
				  if(typeof(data[0])!="undefined"){	
						$('.country_completions').append('<li class="completions3"><a href="#" class="completions3_link" onclick="reset_filter();highlight_obj(this)">Alle ('+data[0][4]['TOTAL']+')</a></li>');
	
						for(i=0;i<data.length;i++){
							$('.country_completions').append('<li class="completions3"><a href="#" class="completions3_link" onclick="add_filter(\':facet:offers_country:\',false,\''+data[i][3]+'\');highlight_obj(this)">'+data[i][2]+' ('+data[i][1]['DC']+')</a></li>');
						}
						
	
				  }else{
					$('.country_completions').append('<li class="completions3"><a href="#" class="completions3_link">'+$('#tl_leider_keine_treffer').val()+'</a></li>');						  
				  }
				  $('.completions3').wrapAll('<ul class="sf-menu sf-vertical sf-js-enabled sf-shadow" />');
			 	}
			  });		
}


function get_filter_mode(){
	searchmode = $('input[name=searchmode]:checked').val();
	if(searchmode == 'full'){
		filter = '';	
	}else if(searchmode == 'title'){
		filter = ':filter:offers_title:';
	}else if(searchmode == 'text'){
		filter = ':filter:offers_text:';
	}
	return filter;			
}


var total,sent;
function generate_grid_pager(st,facet,filter,f,hits,order){
		
	if(facet == false){
		facet = '';
	}
	
	if(f == false){
		f = 0;
	}
	
	if(filter == false){
		filter = get_filter_mode();
	}
	
	if(order == false){
		order = get_order();
	}
	
			
	f = parseInt(f);
	
	total	= parseInt(hits['TOTAL']);
	sent 	= parseInt(hits['SENT']);
	first 	= parseInt(hits['FIRST']);
	
	items = 10;
			
			$('.livesearch_pager').empty();

			f_zurueck 	=  f-items;
			f_weiter 	= f+items;
			
			if(first > 0){
				$('.livesearch_pager').append('<a href="#" id="livesearch_pager_back" onclick="get_main_grid(\''+st+'\',\''+facet+'\',\''+filter+'\','+f_zurueck+',false,false)">'+$('#tl_pager_prev').val()+'</a>');
			}
			//console.log(total);
			if(total - first >= items){
				$('.livesearch_pager').append('<a href="#" id="livesearch_pager_forward" onclick="get_main_grid(\''+st+'\',\''+facet+'\',\''+filter+'\','+f_weiter+',false,false)">'+$('#tl_pager_next').val()+'</a>');
			}
/*				console.log('######');
			console.log('fweiter: '+f_weiter);
			console.log('fzurueck: '+f_zurueck);
			console.log('total: '+total);
			console.log('sent: '+sent);
			console.log('first: '+first);
			console.log('f: '+f);*/
	
}




function store_product_alert_user(){
	$.ajax({
	   type: "GET",
	   url: "modules/rp24_global/ajax/ajax.store_alert.php",
	   data: "search_phrase="+$('#livesearch_searchtext').val(),
	   success: function(msg){
		   $('#product_alert_msg_p').html(msg);
				$( "#dialog_message_product_alert" ).dialog({
					modal: true,
					buttons: {
						Ok: function() {
							$( this ).dialog('close');
							$(this).dialog('destroy');
						}
					}
				});
				//alert(msg);
	   }
	 });
}

function store_product_alert(){
	user_email = prompt('Bitte geben Sie hier Ihre E-Mail Adresse an.');
			if(user_email){
					$.ajax({
						   type: "GET",
						   url: "modules/rp24_global/ajax/ajax.store_alert.php",
						   data: "search_phrase="+$('#livesearch_searchtext').val()+"&user_email="+user_email,
						   success: function(msg){
							    $('#product_alert_msg_p').html(msg);
							   				$( "#dialog_message_product_alert" ).dialog({
												modal: true,
												buttons: {
													Ok: function() {
														$( this ).dialog('close');
														$(this).dialog('destroy');
													}
												}
											});
						   }
						 });
			}
	
}
