// Global variables
var searchResults = new Array();
var memorizedProducts = new Array();
var queryString = '';
var rememberCount = 0;
var categoryId = 0;

// XXX wird im Moment nicht genutzt -> hochscrollen nach Pagination-Click
var anim_speed = 100;

// aktuelle Seite der Pagination
var currentPage = 1;

// Gesamtzahl der Seiten beim Bl�ttern (nicht bei Suche)
var overallPages = 0;

var order_by = '';
var order_dir = '';
var show_all = '';
var shopId = 0;

var global_http_request_id = 0;
(function($) {
	$.fn.dropdownMenu = function(){
		var top_parent = this;
		this.find('a').click( function(event){
			event.preventDefault();
			event.stopPropagation();
			 //if( $(this).parent().attr('isHidden') == 'true' ||  $(this).parent().children().filter('ul').length == 0 )
			 //{		
				categoryId = $(this).attr('category_id');
				currentPage = 1;
				queryString = $('#query').attr('value');
				showAll(queryString,false);
				
				top_parent.find('a').each( function(){ $(this).removeClass('dropdown_menu_item_selected');});
				$(this).addClass('dropdown_menu_item_selected');
			 //}
			 if(  $(this).parent().parent().children().length > 0 )
			 {
				 if( $(this).parent().parent().attr('isHidden') == 'true' )
				 {
					 $(this).parent().parent().attr('isHidden','false');
					 $(this).siblings().filter('.category_closed').addClass('category_opened').removeClass('category_closed');
					 //$(this).parent().parent().children().filter('ul, li').slideDown('slow');
					 $(this).parent().parent().children().filter('ul, li').css('display','block');
				 }
				 else
				 {
					 $(this).parent().parent().attr('isHidden','true');
					 $(this).siblings().filter('.category_opened').removeClass('category_opened').addClass('category_closed');
					 //$(this).parent().parent().children().filter('ul, li').slideUp('slow');
					 $(this).parent().parent().children().filter('ul, li').css('display','none');
				 }
			 }
		});
		
		this.find('.category_opened, .category_closed').each( function(event){
			$(this).css('cursor','pointer');
			if($(this).parent().parent().children().length > 0 )
			{
				$(this).parent().parent().attr('isHidden','true');
				$(this).parent().parent().children().filter('ul, li').css('display','none');
			}
		});	
		
		this.find('.category_opened, .category_closed').click( function(event){
			if(  $(this).parent().parent().children().length > 0 )
			{
				 if( $(this).parent().parent().attr('isHidden') == 'true' )
				 {
					 $(this).parent().parent().attr('isHidden','false');
					 $(this).addClass('category_opened').removeClass('category_closed');
					 //$(this).parent().parent().children().filter('ul, li').slideDown('slow');
					 $(this).parent().parent().children().filter('ul, li').css('display','block');
				 }
				 else
				 {
					 $(this).parent().parent().attr('isHidden','true');
					 $(this).removeClass('category_opened').addClass('category_closed');
					 //$(this).parent().parent().children().filter('ul, li').slideUp('slow');
					 $(this).parent().parent().children().filter('ul, li').css('display','none');
				 }
			}
		});
	};
	return this;
})(jQuery);	


function init(initial_pages){
	$('#categories').dropdownMenu();
	
	$('#search_form').bind('submit',function(event) {
		event.preventDefault();
		event.stopPropagation();
		return false;
	});
	
	var timeout;
	$('#query').keyup(function(event) {
		//console.log('keyup');
		// Falls QueryString komplett gel�scht wurde => alle Ergebnisse anzeigen
		if($('#query').attr('value') == "") {
			currentPage = 1;
			showAll();
			window.location.hash = '';
			$('.teaser').remove();
			$('#results').html('<img class="loading_image" src="'+base_url+'images/loading.gif">');
			return false;
		}
		clearTimeout(timeout);
		// falls return gedr�ckt wurde => Suche direkt ausf�hren und queryString in DB speichern
		if(event.keyCode == 13)
		{
			doSearch(true);
			return false;
		}
		timeout = setTimeout(function(){
			doSearch();
		},400);
		return false;
	});
		
	if( window.location.hash != '' ){
		var query = (window.location.hash).replace(/_/g,' ').replace('#','');
		currentPage = 1;
		showAll(query,true);
		$('#query').attr('value',query);
		$('.teaser').remove();
		$('#results').html('<img class="loading_image" src="'+base_url+'images/loading.gif">');
	} else {
		// initial wird jetzt über php erledigt, hier müssen aber listener etc. gesetzt werden
		appendSorter();
		overallPages = initial_pages;
		showPagination(true);
		setEmailQuery( query );
		highlightAndShowDescription();
	}
	$('#top_searches li').click(function(){
		currentPage = 1;
		showAll($(this).text(),false);
		window.location.hash = $(this).text();
		$('#query').attr('value', $(this).text() );
		$('.teaser').remove();
		$('#results').html('<img class="loading_image" src="'+base_url+'images/loading.gif">');
	}).hover(
		function(){
			$(this).css('cursor','pointer');
			$(this).css('color','#000000');
		},function(){
			$(this).css('color','#777777');
		}
	);
	
	$('.menu-item').hover( function(){
		//$(this).css('background-color','#CCCCCC');
		$(this).find('ul').slideDown('fast');
	},function(){
		//$(this).css('background-color','white');
		$(this).find('ul').slideUp('fast');
	});
	$('.menu-item-link').hover(function(){
		$(this).css('color','#969696');
	}, function(){
		$(this).css('color','black');
	}).css('cursor', 'pointer').click( function(event){
		var isSelected = false;
		if( $(this).parent().hasClass('menu-item-selected') ){
			categoryId = 0;
			$('.menu-item-selected').removeClass('menu-item-selected').addClass('menu-item');		
		} else {
			categoryId = $(this).attr('category_id');
			$('.menu-item-selected').removeClass('menu-item-selected').addClass('menu-item');
			$(this).parent().removeClass('menu-item').addClass('menu-item-selected');			
		}
		currentPage = 1;
		queryString = $('#query').attr('value');
		showAll(queryString,false);
	});
	$('.menu-item-sublink').hover(function(){
		$(this).css('color','#969696');
	}, function(){
		$(this).css('color','black');
	}).css('cursor', 'pointer').click( function(event){
		$('.menu-item-selected').removeClass('menu-item-selected').addClass('menu-item');
		$(this).parent().parent().removeClass('menu-item').addClass('menu-item-selected');	
		categoryId = $(this).parent().parent().find('span').attr('category_id');
		currentPage = 1;
		queryString = $(this).attr('data');
		$('#query').attr('value',queryString);
		showAll(queryString,false);
	});	
};

function sortProducts(sorter){
	if(sorter == 'preis') {
		// sortieren nach Preis
		order_by = 'new';
		order_dir = 'asc';
	} else if(sorter == 'rabatt') {
		// sortieren nach Rabatt
		order_by = 'percentage';
		order_dir = 'desc';
	} else if(sorter == 'datum') {
		// sortieren nach Datum
		order_by = 'date';
		order_dir = 'desc';
	} else {
		order_by = '';
		order_dir = 'desc';
	}
	currentPage = 1;
	showAll($('#query').attr('value'));
}

function filterShops(shop){
	shopId = shop;
	clearResults();
	appendSorter();
	currentPage = 1;
	showAll($('#query').attr('value'));
	$('#results').html('<img class="loading_image" src="'+base_url+'images/loading.gif">');
}


function streamPublish(title,price,pricePercentage,description,image,pid)
{
	var attachment = {	'name' : '"'+title+'" um '+pricePercentage+'% reduziert f&uuml;r nur '+(price/100)+'&euro;',
						'href' : 'http://apps.facebook.com/dealio_app/index/'+pid, 
						'description' : description,
						'media': [{'type':'image',
								'src':image,
								'href':'http://apps.facebook.com/dealio_app/index/'+pid}]};
 FB.Connect.streamPublish('', attachment,null,null,'Deine Meinung...');
}

function swap(array,pos1,pos2){
	var tempVariable = array[pos1];
	array[pos1] = array[pos2];
	array[pos2] = tempVariable;
	//return array;
}

function sort(arrayToSort,ascendent,type) {
	for ( var k = 0; k < arrayToSort.length - 1; k++) {
		var isSorted = true;

		for ( var i = 1; i < arrayToSort.length - k; i++) {
			if (ascendent) {
				switch(type){
				case "price":
					if (arrayToSort[i].price < arrayToSort[i - 1].price) {
						swap(arrayToSort,i,i-1);
						isSorted = false;
					}	
					break;
				case "percentage":
					if (arrayToSort[i].pricePercentage < arrayToSort[i - 1].pricePercentage) {
						swap(arrayToSort,i,i-1);
						isSorted = false;
					}					
					break;
				defaukt:
					break;
				}
			} else {
				switch(type){
				case "price":
					if (arrayToSort[i].price/100 > arrayToSort[i - 1].price/100) {
						swap(arrayToSort,i,i-1);
						isSorted = false;
					}	
					break;
				case "percentage":
					if (arrayToSort[i].pricePercentage > arrayToSort[i - 1].pricePercentage) {
						swap(arrayToSort,i,i-1);
						isSorted = false;
					}					
					break;
				defaukt:
					break;
				}
			}
		}

		if (isSorted)
			return true;
	}
};

function doSearch(saveQuery) {
	// bei return wird queryString gespeichert
	saveQuery = typeof(saveQuery) != 'undefined' ? saveQuery : false;
	clearResults();
	appendSorter();
	
	queryString = $('#query').attr('value');
	// keine Suche ausf�hren, falls QueryString mittlerweile leer ist => es wird eh nichts gefunden
	if(queryString == ''){
		return;
	}
	currentPage = 1;
	showAll( queryString, saveQuery );
	queryString = queryString.replace(/ /g,"_").replace (/^_+/, '').replace (/_+$/, '');;
	window.location.hash = queryString;
	$('.teaser').remove();
	$('#results').html('<img class="loading_image" src="'+base_url+'images/loading.gif">');
}

function clearResults(){
	$('#results').html('');
	$('.sort_container').remove();
	$('#pagination').remove();
}

function appendSorter(){
	var html = "";
	html += '<div class="sort_container">';
	html += '<div class="sort_type_price"> <div class="sort_description">Preis </div> <div class="sort" id="sortByPriceAscendent"></div><div class="sort" id="sortByPriceDescendent"></div></div>';
	html += '<div class="sort_type_percentage"> <div class="sort_description">Rabatt </div> <div class="sort" id="sortByPercentageAscendent"></div><div class="sort" id="sortByPercentageDescendent"></div></div>';
	html += '</div>';
	$('#sorting').html(html);
}

function showResults(response, page, merken, ajax) {
	pageTracker._trackEvent('Suchergebnisse', 'Show', queryString);
	ajax = typeof(ajax) != 'undefined' ? ajax : false;
	numberOfItemsPerPage = typeof(numberOfItemsPerPage) != 'undefined' ? numberOfItemsPerPage : 12;
	currentPage = page;
	
	html = "";
	html += '<div class="main_container">';
	if( response.length > 0 ){
		if(!ajax) {
			$('#ergebnisse').html(queryString);
			for ( var i = (page - 1) * numberOfItemsPerPage; i < Math.min(page * numberOfItemsPerPage, response.length); i++) {
				if( merken ){
					html += createResultStructure(response, i);
				}else{
					html += createResultStructureRemember(response, i);
				}
			}
		} else {
			$('#ergebnisse').html(queryString);
			for ( var i = 0; i < Math.min(numberOfItemsPerPage, response.length); i++) {
				if( merken ){
					html += createResultStructure(response, i);
				}else{
					html += createResultStructureRemember(response, i);
				}
			}
		}
	}else{
		html+= '<div class="result_header">Keine Suchergebnisse.</div>';
	}
	html += '</div>';
	$('#results').html(html);
	$('.remember_selected_item').click(function() {		
		rememberCount++;
		if( rememberCount <= 0 ){
			rememberCount = 0;
		}
		$('#remember_count').html(rememberCount);
		
		showRemList($(this).attr('data'));
		return false;
	}).hover(function() {
		$(this).css('cursor', 'pointer');
		return false;
	});
	$('.post_selected_item').click(function() {		
		$i = $(this).attr('data');
		if( $i != -1 )
		{
			streamPublish(	searchResults[$(this).attr('data')].title,
							searchResults[$(this).attr('data')].price,
							searchResults[$(this).attr('data')].pricePercentage,
							searchResults[$(this).attr('data')].content,
							searchResults[$(this).attr('data')].image,
							searchResults[$(this).attr('data')].pid );
		}
		return false;
	}).hover(function() {
		$(this).css('cursor', 'pointer');
		return false;
	});
	
	$('.remember_delete').click(function(event){
		event.preventDefault();
		rememberCount--;
		
		if( rememberCount <= 0 ){
			rememberCount = 0;
		}
		$('#remember_count').html(rememberCount);
		
		$(this).parent().parent().remove();
		
		var i = $(this).attr('data');
		var data = 'id='+i;
		$.post(base_url + 'fb/deleteRememberItem', data);
		showRemList(-1);
		return false;
	}).hover(function() {
		$(this).css('cursor', 'pointer');
	});		
	
	if(!ajax){
		initSortHandlers();
	} else {
		initSortHandlersAjax();
	}
	
	highlightAndShowDescription();

	/*interne verlinkung mit popup
	 * $(".product_link").fancybox({
		//'transitionIn'	:	'elastic',
		//'transitionOut'	:	'elastic',
		'speedIn'		:	600, 
		'speedOut'		:	200, 
		'overlayShow'	:	true,
		'hideOnContentClick': false
	});*/
	$("#fancy_link").fancybox({
		//'transitionIn'	:	'elastic',
		//'transitionOut'	:	'elastic',
		'speedIn'		:	600, 
		'speedOut'		:	200, 
		'overlayShow'	:	true,
		'hideOnContentClick': false,
		onClosed	:	function() {
            $('#fancy_link').click();
		}
	});
		
}

function highlightAndShowDescription() {
	$('.desc').mouseenter(function(){
		$(this).css('display','none');
	});

	// verdunklung
	$('.shadow').css('display','inline').css('opacity','0');
	$('.shadow').addClass('activeShadow');
	
	$('.gridItem').hover(
		function(e){
			$(this).find('.desc').css('display','block');
			//$(this).animate({ display: 'none'}, 50, function() {console.log('done')});
			
			$(this).find('.shadow').removeClass('activeShadow');
			
			$('.shadow.activeShadow').animate({
				opacity: 0.6
			}, { duration: 500, queue: false });
			
			$(this).find('.desc').css('opacity','0').animate({
				opacity: 1
			}, { duration: 500, queue: false });
		},
		function(){
			$(this).find('.desc').css('display','none');
		
			$('.shadow.activeShadow').animate({
				opacity: 0
			}, { duration: 500, queue: false });
			
			$(this).find('.shadow').addClass('activeShadow');
		}
	);
}

function initSortHandlers(){
	$('#sortByPriceAscendent').click(function() {
		sort(searchResults,true,"price");
		showResults(searchResults, 1,true);
		showPagination();
	}).hover(function() {
		$(this).css('cursor', 'pointer');
	});
	$('#sortByPercentageAscendent').click(function() {
		sort(searchResults,true,"percentage");
		showResults(searchResults, 1,true);
		showPagination();
	}).hover(function() {
		$(this).css('cursor', 'pointer');
	});
	$('#sortByPriceDescendent').click(function() {
		sort(searchResults,false,"price");
		showResults(searchResults, 1,true);
		showPagination();
	}).hover(function() {
		$(this).css('cursor', 'pointer');
	});
	$('#sortByPercentageDescendent').click(function() {
		sort(searchResults,false,"percentage");
		showResults(searchResults, 1,true);
		showPagination();
	}).hover(function() {
		$(this).css('cursor', 'pointer');
	});
}

function initSortHandlersAjax(){
	$('#sortByPriceAscendent').click(function() {
		currentPage = 1;
		order_by = 'new';
		order_dir = 'asc';
		showAll($('#query').attr('value'));
	}).hover(function() {
		$(this).css('cursor', 'pointer');
	});
	$('#sortByPercentageAscendent').click(function() {
		currentPage = 1;
		order_by = 'percentage';
		order_dir = 'asc';
		showAll($('#query').attr('value'));
	}).hover(function() {
		$(this).css('cursor', 'pointer');
	});
	$('#sortByPriceDescendent').click(function() {
		currentPage = 1;
		order_by = 'new';
		order_dir = 'desc';
		showAll($('#query').attr('value'));
	}).hover(function() {
		$(this).css('cursor', 'pointer');
	});
	$('#sortByPercentageDescendent').click(function() {
		currentPage = 1;
		order_by = 'percentage';
		order_dir = 'desc';
		showAll($('#query').attr('value'));
	}).hover(function() {
		$(this).css('cursor', 'pointer');
	});
}

function createResultStructure(response, i){
	showRememberButton = typeof(showRememberButton) != 'undefined' ? showRememberButton : true;
	showPostButton = typeof(showPostButton) != 'undefined' ? showPostButton : true;
	
	var html = '';
	// interne verlinkung mit popup
	//html+='<a class="product_link" href="'+base_url+'rabatt/product/'+response[i].shop+'/'+response[i].in_shop_id+'"  target="_blank">';
	//externe verlinkung direkt zu produkt
	//html+='<a class="product_link" href="'+response[i].path+'"  target="_blank">';
	//html+='<a class="product_link" href="'+base_url+'rabatt/product_link?address='+encodeURIComponent(response[i].path)+'"  target="_blank">';
	var encoded_in_shop_id = encodeURIComponent(response[i].in_shop_id);
	encoded_in_shop_id = encoded_in_shop_id.replace(/%23/gi,"+" );
	html+='<a class="product_link" href="'+base_url+'rabatt/product_link/'+response[i].shop+'/'+encoded_in_shop_id+'"  target="_blank">';
	html+='	<div class="gridItem" data-pid="'+response[i].pid+'">';
	html+='		<div class="price transparent">';
	html+='			<span><b>'+(response[i].price/100).toFixed(2)+'&euro;</b></span>';
	html+='		</div>';
	
	var cl = 'transparent';
	if(response[i].pricePercentage >= 50) {
		cl = 'superhot';
	} else if(response[i].pricePercentage >= 20) {
		cl = 'hot';
	} 
	html+='		<div class="percentage '+cl+'">';
	html+='			<span><b>'+response[i].pricePercentage+'%</b></span>';
	html+='		</div>';
	
	var updateDate = new Date(response[i].date * 1000);
	var currentDate = new Date();
	currentDate.setDate( currentDate.getDate() -3 );
//	console.log("current-3"+currentDate);
//	console.log("update"+updateDate);
	if( currentDate < updateDate ){
	html+='		<div class="new">';
	html+='			<img src="'+base_url+'images/new.png"/>';
	html+='		</div>';
	}
	
	if( showRememberButton ){
		html+='		<div class="remember_selected_item rounded grey_bg" data="'+ i +'">';
		html+='			Merken';
		html+='		</div>';
	}
	
	if( showPostButton ){
		html+='		<div class="post_selected_item rounded grey_bg" data="'+ i +'" title="Zeig es deinen Freunden!">';
		html+='			Post';
		html+='		</div>';
	}
	
	html+='		<div class="info rounded transparent">';
	html+='			<span class="title">'+ response[i].title +'</span>';

	html+='		</div>';
	html+='		<div class="image rounded" data="'+ response[i].imageBig +'">';
	html+='			<img class="product_image" src="'+response[i].image+'" style="display:block; margin-left:auto; margin-right:auto; margin-top:2px;"/>';
	html+='		</div>';
	if(response[i].content != null){
		html +='<div class="desc"><p>';
		html+='			<span class="title"><b>'+ response[i].title +'</b></span>';
		html+='			<span class="credit">'+response[i].content+'</span>';
		html+='			<br/><br/><span>reduziert um '+response[i].pricePercentage+'%</span>';
		html+='			<span style="float:right"><b>'+(response[i].price/100).toFixed(2)+'&euro;</b></span>';
		html+='</p></div>';
	}		
	html+='<div class="shadow"></div>'
	html+='	</div>';
	html+='</a>';
	
	return html;
}

function createResultStructureRemember(response, i){
	showRememberButton = typeof(showRememberButton) != 'undefined' ? showRememberButton : true;
	showPostButton = typeof(showPostButton) != 'undefined' ? showPostButton : true;
	
	var html = '';
	var link = (response[i].pid).replace('@','/');
	
	html+='<a class="product_link" href="http://ufashion.de/dout/'+link+'" target="_blank">';
	html+='	<div class="gridItem rounded" data-pid="'+response[i].pid+'">';
	html+='		<div class="price rounded transparent">';
	html+='			<span>'+(response[i].price/100).toFixed(2)+'&euro;</span>';
	html+='		</div>';
	
	html+='		<div class="percentage rounded transparent">';
	html+='			<span>'+response[i].pricePercentage+'%</span>';
	html+='		</div>';
	
	if( showRememberButton ) {
		//html+='		<div class="remember_delete rounded transparent" data="'+  response[i].id +'">';
		html+='		<div class="remember_delete rounded grey_bg" data="'+  response[i].pid +'">';
		html+='			X';
		html+='		</div>';
	}
	
	if( showRememberButton ){
		html+='		<div class="post_selected_item rounded grey_bg" data="'+ i +'" title="Zeig es deinen Freunden!">';
		html+='			Post';
		html+='		</div>';
	}
	
	html+='		<div class="info rounded transparent">';
	html+='			<span class="title">'+ response[i].title +'</span>';

	html+='		</div>';
	html+='		<div class="image rounded" data="'+ response[i].imageBig +'">';
	html+='			<img class="product_image" src="'+response[i].image+'" style="display:block; margin-left:auto; margin-right:auto; margin-top:2px;"/>';
	html+='		</div>';
	if(response[i].content != null){
		html +='<div class="desc"><p>';
		html+='			<span class="title"><b>'+ response[i].title +'</b></span>';
		html+='			<span class="credit">'+response[i].content+'</span>';
		html+='			<br/><br/><span>reduziert um '+response[i].pricePercentage+'%</span>';
		html+='			<span style="float:right"><b>'+(response[i].price/100).toFixed(2)+'&euro;</b></span>';
		html+='</p></div>';
	}		
	html+='	</div>';
	html+='</a>';
	
	
	
	return html;
}

// ajax:false oder undefined => pagination f�r json-Suche
// ajax:true => pagination f�r ajax-Katalog
function showPagination(ajax,rememberList) {
	ajax = typeof(ajax) != 'undefined' ? ajax : false;
	rememberList = typeof(rememberList) != 'undefined' ? rememberList : false;
	numberOfItemsPerPage = typeof(numberOfItemsPerPage) != 'undefined' ? numberOfItemsPerPage : 12;
	
	$('#pagination').remove();
	
	var length = searchResults.length;
	
	var pages = Math.ceil(length/numberOfItemsPerPage);
	if(ajax) {
		pages = overallPages;
	} else if(rememberList){
		pages = overallPages;
	}
	var html = '<div id="pagination">';
	var page = currentPage;
	
	// vorher
	var before = Math.min(3,page-1);
	if(page-before>1) {
		html += '<div class="pager">1</div>';
		if(page-before>2) {
			html += '<div>...</div>';
		}
	}
	for(var i=before;i>0;i--) {
		html += '<div class="pager">' + (page - i) + '</div>';
	}

	// current
	html += '<div>' + (page) + '</div>';
	
	// nachher
	var after = Math.min(3,pages-page);
	for(var i=1;i<=after;i++) {
		html += '<div class="pager">' + ((page-0) + (i-0)) + '</div>';
	}
	if((page-0)+(i-0)<=pages) {
		if((page-0)+(i-0)<=pages-1) {
			html += '<div>...</div>';
		}
		html += '<div class="pager">' + (pages) + '</div>';
	}

	html += '</div>';
	$('#pagination_bar').html(html);	
	
	$('#pagination div').each(function(){
		if($(this).html() == currentPage){
			$(this).addClass('current');
		}
	});
	if(ajax) {
		initPaginationHandlerAjax();
	} else if(rememberList) {
		initPaginationHandlerRememberList();
	} else {
		initPaginationHandler();
	}
}

function initPaginationHandler() {
	$('.pager').click(function() {
		pageTracker._trackEvent('Pagination', 'Click', ($(this).html()-0));
		showResults(searchResults, ($(this).html()-0),true);
		showPagination();
		$('html, body').animate({scrollTop:0}, 'slow');
	}).hover(function() {
		$(this).css('cursor', 'pointer');
	});
}

function initPaginationHandlerAjax() {
	$('.pager').click(function() {
		currentPage = ($(this).html()-0);
		showAll($('#query').attr('value'));
		$('html, body').animate({scrollTop:0}, 'slow');
	}).hover(function() {
		$(this).css('cursor', 'pointer');
	});
}

function initPaginationHandlerRememberList() {
	$('.pager').click(function() {
		currentPage = ($(this).html()-0);
		showRemList(-1);
	}).hover(function() {
		$(this).css('cursor', 'pointer');
	});
}

function showAll( searchQuery, saveQuery ){
	numberOfItemsPerPage = typeof(numberOfItemsPerPage) != 'undefined' ? numberOfItemsPerPage : 50;
	var data = {
		perpage : numberOfItemsPerPage,
		page : currentPage,
		order_by : order_by,
		order_dir : order_dir,
		search_query : searchQuery,
		save : saveQuery,
		show_all : show_all,
		brand : $('#brand').attr('value'),
		category_id : categoryId,
		shop_id: shopId
	};
	$.post(base_url + 'rabatt/all', data, function(response) {
		appendSorter();
		overallPages = response.pages;
		searchResults = response.results;
		showResults(response.results, currentPage, true, true);
		showPagination(true);
		setEmailQuery( searchQuery );
	}, 'json');
	
}

// setzt die Bezeichnung zum eMail abonnieren
function setEmailQuery( searchQuery ){
	if(typeof searchQuery=='undefined' || searchQuery == 'undefined' || searchQuery == '' ){
		searchQuery = 'Mode';
	}
	$('#email_query').html(searchQuery);
}

function showProduct(productId){
	var data = {
		pid : productId
	};
	$.post(base_url + 'fb/show_product', data, function(response) {
		appendSorter();
		overallPages = response.pages;
		searchResults = response.results;
		showResults(response.results, currentPage, true, true);
		showPagination(true);
	}, 'json');
}

function showRemList(i){
	var data;
	global_http_request_id++;
	if( i >= 0 ){
		data = {
			page : currentPage,
			order_by : order_by,
			order_dir : order_dir,
			pid : searchResults[i].pid,
			id : global_http_request_id
		};
	} else {
		data = {
			page : currentPage,
			order_by : order_by,
			order_dir : order_dir,
			id : global_http_request_id
		};
	}
	$.post(base_url + 'fb/remember_test', data, function(response) {
		if( response.id != global_http_request_id )
		{
			return false;
		}
		rememberCount = (response.items - 0);
		if( rememberCount <= 0 ){
			rememberCount = 0;
		}
		$('#remember_count').html(rememberCount);
		
		if( i == -1 ){
				appendSorter();
				overallPages = response.pages;
				searchResults = response.results;
				showResults(response.results, currentPage, false, true);
				showPagination(false,true);
		}
		$('#remember_item').click(function(){
				clearResults();
				currentPage = 1;
				showRemList(-1);
		}).hover(function(){$(this).css('cursor','pointer');});
	}, 'json');
}

function selectAll(all) {
	show_all = all;
	currentPage = 1;
	showAll($('#query').attr('value'));
	
	$('#sort_rabatt').toggle();
	$('#sort_datum').toggle();
}

// verkürzt die Results, die per PHP angezeigt werden
function shrinkResults() {
	$('#results').children().each(function(index, me){
		if(index >= numberOfItemsPerPage) $(me).remove();
	});
}


function getBrowserDimensions() {
    var dimensions = {width: 0, height: 0};
    if (document.documentElement) {
        dimensions.width = document.documentElement.offsetWidth;
        dimensions.height = document.documentElement.offsetHeight;
    } else if (window.innerWidth && window.innerHeight) {
        dimensions.width = window.innerWidth;
        dimensions.height = window.innerHeight;
    }
    return dimensions;
}

// Message anzeigen, falls gesetzt
function showMessage() {
	$('#message').lightbox_me({
		background: 'black', 
	   	opacity: .6,
	   	centered: true, 
	    onLoad: function() {}
    });
}
// Registrierung
function initRegistration() {
	$('#email').animate({ right: '-100'}, { duration: 2000, queue: false });
	$('#email').hover(
		function(){
			$('#email').animate({ right: '10'}, { duration: 300, queue: false });
		},
		function(){
			$('#email').animate({ right: '-100'}, { duration: 300, queue: false });
		}
	).css('cursor', 'pointer').click(function() {
		$('#sign_up_status').html();
	    $('#sign_up').lightbox_me({
	    	background: 'black', 
	    	opacity: .6,
	        centered: true, 
	        onLoad: function() { 
	            $('#sign_up').find('input:first').focus()
	            }
	    });
	    return false;
	});
	$('#sign_up_form').submit(function(event){
		event.preventDefault();
		event.stopPropagation();

		$('#sign_up_status').html('Daten werden gesendet');
		data = {
			email: $('#username').attr('value'),
			password: $('#password').attr('value')
		}
		$.post(base_url + 'auth/register', data, function(response) {
			if(response.status == '1') {
				// Registrierung okay
				$('.close').click();
				$('#success').lightbox_me({
			    	background: 'black', 
			    	opacity: .6,
			        centered: true, 
			        onLoad: function() {} 
			    });
			} else {
				// Registrierung fehlgeschlagen
				message = response.message
				if(message == false){
					message = 'Die eMail Adresse ist bereits vorhanden';
				}
				$('#sign_up_status').html('Registrierung fehlgeschlagen<br />'+message);
				
			}
		}, 'json');
	});
}

// Click Listener fuer Marken
function initBrandListener() {
	$('#brands').find('a').click(function(e){
		e.preventDefault();
		var href = $(this).attr('href');
		var slug = href.substring(href.lastIndexOf('/')+1,href.length);
		var data = 'name='+slug;
		$.post(base_url + 'rabatt/brand_id', data, function(response) {
			$('#brand').attr('value',response['id']);
			if(response['content'] != '' && response['title'] != '') {
				$('#infobox').html('<div class="search-tip"><h3>'+response['title']+'</h3><div>'+response['content']+'</div></div>');
			}
			currentPage = 1;
			showAll();
		}, 'json');
		return false;
	});
}
/*
 * JavaScript Debug - v0.3 - 6/8/2009
 * http://benalman.com/projects/javascript-debug-console-log/
 * 
 * Copyright (c) 2009 "Cowboy" Ben Alman
 * Dual licensed under the MIT and GPL licenses.
 * http://benalman.com/about/license/
 * 
 * With lots of help from Paul Irish!
 * http://paulirish.com/
 */
window.debug=(function(){var c=this,e=Array.prototype.slice,b=c.console,i={},f,g,j=9,d=["error","warn","info","debug","log"],m="assert clear count dir dirxml group groupEnd profile profileEnd time timeEnd trace".split(" "),k=m.length,a=[];while(--k>=0){(function(n){i[n]=function(){j!==0&&b&&b[n]&&b[n].apply(b,arguments)}})(m[k])}k=d.length;while(--k>=0){(function(n,o){i[o]=function(){var q=e.call(arguments),p=[o].concat(q);a.push(p);h(p);if(!b||!l(n)){return}b.firebug?b[o].apply(c,q):b[o]?b[o](q):b.log(q)}})(k,d[k])}function h(n){if(f&&(g||!b||!b.log)){f.apply(c,n)}}i.setLevel=function(n){j=typeof n==="number"?n:9};function l(n){return j>0?j>n:d.length+j<=n}i.setCallback=function(){var o=e.call(arguments),n=a.length,p=n;f=o.shift()||null;g=typeof o[0]==="boolean"?o.shift():false;p-=typeof o[0]==="number"?o.shift():n;while(p<n){h(a[p++])}};return i})();