/*jslint evil: true, forin: true */

/**
* @fileOverview Core functions of search application, and can normally not be resused
* @author Holger Hellinger
* @version 0.1 
* @class
 */

/** 
* pol
* @namespace pol
*/
if (typeof(app) == "undefined" ) {
	var app = { }; //abusing JS's strange block level scoping
}
pol = {

	triggered: false,

	/**
	* Initialization function that adds additional information to the application
	* @function
	*/
	init: function() {
	
		/**
		* Adds a class jsEnabled to the body. So the application knows with extra testing that js is there. 
		* Used for displaying js only functional elements
		* @field
		*/
		$("body").addClass("jsEnabled");
		
		//Live Event for each button and anchor that looks like this. 
		$('a.external').live("click", function(){
			window.open($(this).attr("href"));
			return false;
		});
		
		$(window).scroll(function(){
			var scrollTop = $(window).scrollTop();
			var docHeight = $(document).height() - $(window).height();
			if  (scrollTop >= docHeight-1){
				pol.triggerNewContent();
			}
		}); 

				
	},
	
	/**
	* getScrollDepth
	* @function
	*/
	triggerNewContent: function() {
	
		if (pol.triggered===false) { 
			pol.triggered = true;
	
			if ($("li.emptyCell").length<1) {
				$("<li class='emptyCell'></li>").appendTo('ul.result');
			}
			try {
				var dataStr = $("#untilID").val();
				dataStr = dataStr.replace(/\?q=/g, "?s=");
				//console.log(dataStr);
				var dataStrSplitted = dataStr.split("?");
				//console.log(dataStrSplitted[1]);
				$("li.hiddenForm").remove();
				$.ajax({
						url: "/json.php",
						type: "GET",
						data: dataStrSplitted[1],
						dataType: "html",
						success: function(data){
							
							if (data === "<li class='empty'>Kein weiteres Ergebnis gefunden!</li>") {
								$("li.emptyCell").replaceWith(data);
								pol.triggered = true;	
							} else {
							
								var preLast = $("li.emptyCell").prev();
								preLast.remove();
								$("li.emptyCell").replaceWith(data);
								pol.triggered = false;
							}
						}
					}
				)
			} catch(e) {}
		}
	
	},
	
	/**
	* get results
	* @function
	*/
	getResult: function() {
	
		
	
	},
	
	/**
	* show results
	* @function
	*/
	displayResult: function() {
	}
}; 

/**
* Initialisation function
*/
(function($) {	
	$(document).ready(pol.init);
})(jQuery);
