/*
 * 
 *
 * Version 1.0.0  (28.01.2008)
 *
 * Dual licensed under the MIT and GPL licenses.
 *
 * http://www.golocal.de
*/

//
// create closure
//
if (typeof console == "undefined" || typeof console.log == "undefined") var console = { log: function() {} };

(function($) {
	  
	
	/*****************************************/
	/***         plugin definition         ***/
	/*****************************************/

	
	// Begin fn.glCityHist
	jQuery.fn.glCityHist = function(options){
		
		/*****************************************/
		/***         plugin defaults           ***/
		/*****************************************/
	
		var defaults = {
			historyTrigger: null, 					// e.g. "$(#myTrigger)"
			historyVisibilityClass: "hist_active"
		};	
		
		//console.log("glCityHist(", options, ") called");
		
		// build main options before element iteration
		var options = $.extend({}, defaults, options);
		
		//console.log("options nach extention: ", options);
		
		return this.each (function() {
								   
			var $this = $(this);
			var nHistAmount = 0;
			
			
			// Support the metadata-plugin 
			var o = $.meta ? $.extend({}, options, $this.data()) : options;
			
			// otherwise set hover-handler for layer
			var $lis = $this.find("li", "ul.citiesList");
			
			var $lisHist = $("ul.histCities li", $this);

			if($lisHist.size() > 0){
				// is historyList
				nHistAmount = $lisHist.size();
				//console.log("histAmount =", nHistAmount);
			}
				
			
			$lis
				.wrapInner("<div class='statusWrap'></div>")
				.hover(
					function(){
						//console.log("hover", $this);
						$(".statusWrap", this)
							.addClass("hover");
						
					},
					function(){
						//console.log("hover out", $this);
						$(".statusWrap", this)
							.removeClass("hover");
					}
				);
			
			
			function setActionHandlers(){
				// remove-button
				$this.listen('click', "a.removeCityEntry", function(){
					//console.log("btn remove (", this, ") clicked");
					$(this)
						.closest("li")
						.fadeOut(500, function(){
							$(this).remove();
							
							// check hiding of removeList-link when there are no entries in history
							checkLink_removeCityList();
							
							updateRecentCityCookie("remove");
						});
						
					return false;
				});
				
				$this.listen('click', "a.removeAddressEntry", function(){
					//console.log("btn remove (", this, ") clicked");
					$(this)
						.closest("li")
						.fadeOut(500, function(){
							$(this).remove();
							
							// check hiding of removeList-link when there are no entries in history
							checkLink_removeAddressList();
							
							updateRecentAddressCookie("remove");
						});
						
					return false;
				});
				
				// stick-button
				$this.listen('click', "a.stickyCityEntry", function(){
					//console.log("btn stick (", this, ") clicked");
					var $anchor = $(this);
					var $targetList;
					
					if($anchor.parents("#cityHistList").size() > 0){
						// is cities history list
						//console.log("is history list");
						
						// set target list to 'sticky' (for adding element)
						$targetList = $("#cityStickyList", $this);
						
						$anchor
							.closest("li")
							.appendTo($targetList)
							.find(".statusWrap")
							.removeClass("hover");
					} else {
						// sticky list
						//console.log("is sticky list");
						
						// set target list to 'history' (for adding element)
						$targetList = $("#cityHistList", $this);	
						
						$anchor
							.closest("li")
							.prependTo($targetList)
							.find(".statusWrap")
							.removeClass("hover");
					}

					// check hiding of removeList-link when there are no entries in history
					checkLink_removeCityList();
					
					updateRecentCityCookie("sticky");
						
					return false;
				});
				
				// stick-button
				$this.listen('click', "a.stickyAddressEntry", function(){
					//console.log("btn stick (", this, ") clicked");
					var $anchor = $(this);
					var $targetList;
					
					if($anchor.parents("#addressHistList").size() > 0){
						// is cities history list
						//console.log("is history list");
						
						// set target list to 'sticky' (for adding element)
						$targetList = $("#addressStickyList", $this);
						
						$anchor
							.closest("li")
							.appendTo($targetList)
							.find(".statusWrap")
							.removeClass("hover");
					} else {
						// sticky list
						//console.log("is sticky list");
						
						// set target list to 'history' (for adding element)
						$targetList = $("#addressHistList", $this);	
						
						$anchor
							.closest("li")
							.prependTo($targetList)
							.find(".statusWrap")
							.removeClass("hover");
					}

					// check hiding of removeList-link when there are no entries in history
					checkLink_removeAddressList();
					
					updateRecentAddressCookie("sticky");
						
					return false;
				});
				
				
				// empty city list
				$this
					.listen('click', "#emptyCityHistList", function(){
						//console.log("btn emptyList (", this, ") clicked");
						$("#cityHistList li")
							.fadeOut(500, function(){
								$(this).remove();
								checkLink_removeCityList();
							});
							
						updateRecentCityCookie ("empty");
							
						return false;
					});
					
				// empty address list
				$this
					.listen('click', "#emptyAddressHistList", function(){
						//console.log("btn emptyList (", this, ") clicked");
						$("#addressHistList li")
							.fadeOut(500, function(){
								$(this).remove();
								checkLink_removeAddressList();
							});
						
						updateRecentAddressCookie ("empty");	
							
						return false;
					});
				
				if(options.historyTrigger){
					// click on user defined button to open history
					$(options.historyTrigger).click(function(e){
						var $trigger = $(this);
	
						if (e.stopPropagation)
							e.stopPropagation();
						
						if( $this.is(':visible') ) {
							$this.hide();
							$trigger.removeClass(options.historyVisibilityClass);
						} else {
							$this.show();
							$trigger.addClass(options.historyVisibilityClass);
						}
					});
				}

				
				// Oli: hide results on click
				$("body").click(function(){
					//console.log("body clicked");
					$this.hide();
					// reset arrow if defined button available
					options.historyTrigger ? options.historyTrigger.removeClass(options.historyVisibilityClass) : 0;
				});	
			};
			
			function checkLink_removeCityList(){
				// check if there are entries left in history
				// if that's the case show "empty list"-link
				nHistAmount = $this
					.find("#cityHistList li")
					.size();
					
				if (nHistAmount > 0)
					showLink_removeCityList();
				else
					hideLink_removeCityList();
			};
			
			function showLink_removeCityList(){
				$this
					.find("#emptyCityHistList")
					.show();
			};
			
			function hideLink_removeCityList(){
				$this
					.find("#emptyCityHistList")
					.hide();
			};
			
			function checkLink_removeAddressList(){
				// check if there are entries left in history
				// if that's the case show "empty list"-link
				nHistAmount = $this
					.find("#addressHistList li")
					.size();
					
				if (nHistAmount > 0)
					showLink_removeAddressList();
				else
					hideLink_removeAddressList();
			};
			
			function showLink_removeAddressList(){
				$this
					.find("#emptyAddressHistList")
					.show();
			};
			
			function hideLink_removeAddressList(){
				$this
					.find("#emptyAddressHistList")
					.hide();
			};

			setActionHandlers();
		});

	}; // End fn.glCityHist	



	/*****************************************/
	/***         private functions         ***/
	/*****************************************/


	
	/*****************************************/
	/***          public functions         ***/
	/*****************************************/
	
	function updateRecentAddressCookie (action)
	{
		var recentAddress = "";
		var onlySticky=0;

		if (action=="empty")
			onlySticky = 1;
	
		// 1. get stickyCities
		var stickyCities = $("#addressStickyList li");
		var histCities = $("#addressHistList li");
		
		var stickyCitiesListSize = stickyCities.size() - 1;
		var histCitiesListSize = histCities.size();
		var citiesListSize = stickyCitiesListSize + histCitiesListSize;
		
		var zipcodeList = $("span.zipcode", stickyCities);
		var cityList = $("span.city", stickyCities);
		var streetList = $("span.street", stickyCities);
		var housenoList = $("span.houseno", stickyCities);
		var subdList = $("span.subd", stickyCities);

		for (var i=0;i<cityList.size();++i)	
		{
			var zip = $(zipcodeList[i]).text();
			var city = $(cityList[i]).text();
			var street = $(streetList[i]).text();
			var houseno = $(housenoList[i]).text();
			var subd = $(subdList[i]).text();
			
			if (zip==null || zip=="")
				zip="-";
			if (city==null || city=="")
				city="-";
			if (street==null || street=="")
				street="-";
			if (houseno==null || houseno=="")
				houseno="-";
			if (subd==null || subd=="")
				subd="-";

			recentAddress = recentAddress + zip + "|" + city + "|" + street + "|" + houseno + "|" + subd;

			if (i<stickyAddressMaxLength)
				recentAddress = recentAddress + "|s";
			else
				recentAddress = recentAddress + "|-";
			
			if ( ((histCitiesListSize>0 || i<cityList.size()-1) && onlySticky == 0) || (i<cityList.size()-1 && onlySticky == 1))
				recentAddress = recentAddress + "#";
		}
		
		// 2. get histCities
		if (onlySticky==0)
		{
			zipcodeList = $("span.zipcode", histCities);
			cityList = $("span.city", histCities);
			streetList = $("span.street", histCities);
			housenoList = $("span.houseno", histCities);
			subdList = $("span.subd", histCities);
			
			for (var i=0;i<cityList.size();++i)
			{
				var zip = $(zipcodeList[i]).text();
				var city = $(cityList[i]).text();
				var street = $(streetList[i]).text();
				var houseno = $(housenoList[i]).text();
				var subd = $(subdList[i]).text();
				
				if (zip==null || zip=="")
					zip="-";
				if (city==null || city=="")
					city="-";
				if (street==null || street=="")
					street="-";
				if (houseno==null || houseno=="")
					houseno="-";
				if (subd==null || subd=="")
					subd="-";

				recentAddress = recentAddress + zip + "|" + city + "|" + street + "|" + houseno + "|" + subd + "|-";

				if (i<cityList.size()-1)
					recentAddress = recentAddress + "#";
			}
			
			//handle stickyAddressMaxLength limit
			if (stickyCitiesListSize>=stickyAddressMaxLength)
				$("div.cityActions a.stickyAddressEntry", histCities).hide();
			else
				$("div.cityActions a.stickyAddressEntry", histCities).show();
		}
		
		console.log("recentAddress="+recentAddress);
		
		//ajax request to set recent address cookie
		var paramMap = {};
		
		if (recentAddress!="")
			paramMap = { recentAddress: recentAddress };

		$.get("/recentAddress/", paramMap, function(txt) { console.log("address cookie set!"); });
	}
	
	function updateRecentCityCookie (action)
	{
		var recentCity = "";
		var onlySticky=0;

		if (action=="empty")
			onlySticky = 1;
	
	  	// 1. get stickyCities
		var stickyCities = $("#cityStickyList li");
		var histCities = $("#cityHistList li");
		
		var stickyCitiesListSize = stickyCities.size() - 1;
		var histCitiesListSize = histCities.size();
		var citiesListSize = stickyCitiesListSize + histCitiesListSize;

		var cityList = $("a.cityItem", stickyCities);
		var subdList = $("span.subd", stickyCities);

		for (var i=0;i<cityList.size();++i)	
		{
			var city = $(cityList[i]).text();
			var subd = $(subdList[i]).text();
			
			if (city==null || city=="")
				city="-";
			if (subd==null || subd=="")
				subd="-";

			recentCity = recentCity + city + "|" + subd;

			if (i<stickyCityMaxLength)
				recentCity = recentCity + "|s";
			else
				recentCity = recentCity + "|-";
			
			if ( ((histCitiesListSize>0 || i<cityList.size()-1) && onlySticky == 0) || (i<cityList.size()-1 && onlySticky == 1))
				recentCity = recentCity + "#";
		}
		
		// 2. get histCities
		if (onlySticky==0)
		{
			cityList = $("a.cityItem", histCities);
			subdList = $("span.subd", histCities);
			
			for (var i=0;i<cityList.size();++i)
			{
				var city = $(cityList[i]).text();
				var subd = $(subdList[i]).text();

				if (city==null || city=="")
					city="-";
				if (subd==null || subd=="")
					subd="-";

				recentCity = recentCity +  city + "|" + subd + "|-";

				if (i<cityList.size()-1)
					recentCity = recentCity + "#";
			}
			
			//handle stickyCityMaxLength limit
			if (stickyCitiesListSize>=stickyCityMaxLength)
				$("div.cityActions a.stickyCityEntry", histCities).hide();
			else
				$("div.cityActions a.stickyCityEntry", histCities).show();
		}
		
		console.log("recentCity="+recentCity);
		
		//ajax request to set recent cities cookie
		var paramMap = {};
		
		if (recentCity!="")
			paramMap = { recentCity: recentCity };

		$.get("/recentCity/", paramMap, function(txt) { console.log("city cookie set!"); });
	}
//
// end of closure
//
})(jQuery);
