/**
 * @author jolyr
 */

(function($){
	
	var alreadyLoadedFacets = false;
	var CLOSED = 1;
	var OPEN = 2;
	var EXPANDED = 3;
	var status = CLOSED;
	
	/**
	 * This plugin manages the facet widget on the left side of hibe.com. It handles loading additional facets, expanding and collapsing the widget, and
	 * hover and click events.<p><strong>Requirements:</strong>chili-1.7.pack.js<br />
	 * 															jquery-1.3.1.js<br />
	 *															jquery.accordion.js<br />
	 *															jquery.dimensions.js<br />
	 *															jquery.easing.js<br />
	 *															jquery.tooltip.js<br /></p>
	 
	 * @author Daniel Roberts (http://www.hibe.com)
	 * @class FacetWidget
	 * @constructor

	 * @param moreFacetsUrl url to load additional facets from
	 * @param facetListItemSelector selector for facet list item - default: '.facetsListItem'
	 * @param imageTooltip Text to be displayed when hovering over the image
	 * @param facetTooltip Text to be displayed when hovering over body of the facet
	 * @param editTooltip Text to be displayed when hovering over the edit icon in the facet
	 * @param onFacetClick function which controls if the facet click action should run. Needs to return true or false.
	 * @param onImageClick function which controls if the image click action should run. Needs to return true or false.
	 * @param onEditClick function which controls if the edit click action should run. Needs to return true or false.
	 * @param onFacetFilter function which is run when there is a successful click on the facet
	 * @param onFacetHover function which is run on mouseover of the whole facet list item
	 * @param onFacetMouseOut function which is run on mouseout of the whole facet list item
	 * 
	 * @type jQuery
	 *
	 * @cat Plugins/DateSeletc
	 * 
	 */        
	$.fn.facetWidget = function(options) {
	
		// Extends the default options with the users parameters
		var opts = $.extend({}, $.fn.facetWidget.defaults, options);
	
		// Initialize the plugin
		function init($this){
			// $this is an array of dom objects which were passed by jquery selector to the plugin. 
			// There should only be one per page.
			return $this.each(function() {
				/*Iterate through each matched item and attach the appropriate events*/
				$(opts.facetListItemSelector).each(function(){
					attachEvents(this);
				});

				$('#showMoreFacets').click(function(e) {
					showMoreFacets();
				})
				
				$this.accordion({ 
					header: '#facetListTop',
				    event: true, 
				    collapsible: true,
				    alwaysOpen: false,
				    active: 0, //set to false if you want it to initialize closed
				    autoheight: false
				}); 
				
				$('#facetListTop span').click(function() {
					//console.log("Close!");
					if(status == CLOSED) {
						$this.activate(0);
						status = OPEN;
					} else {
						$this.activate(); //closes the accordion
						status = CLOSED;
					}
				});
			});
		};
		
		/**
		 * This function will take a li of a facet, and attach all the necessary hover and click events that it needs
		 * 
		 * @param facetDOM - a DOM object representation (i.e. *not* jquery) of a single facet li
		 */
		function attachEvents(facetDOM) {
			
			// facet is a jQuery object representing one facet <li>
			var facet = $(facetDOM);
			
			/*
			 * Capture each click and dispatch it to the private click handler function
			 */
			facet.click(function(e){
			//	e.preventDefault();
				_onFacetClick(facet, e)				
			})
			
			//hooks for custom events.
			facet.hover(
				function(){ opts.onFacetHover(facet); },
				function(event){ opts.onFacetMouseOut(facet); }
			);
			
			/*
			 * attach the tooltip plugin - jQuery tooltip 
			 * http://bassistance.de/jquery-plugins/jquery-plugin-tooltip/
			 */
			var tooltip = opts.facetTooltip;
			facet.tooltip({
				 track: true,
				 delay: 0,
				 fade: 100,
				 positionLeft: false,
				 bodyHandler: function() { 
			        return tooltip; 
			    }
			});
			
			/*
			 * Change the tooltip message based on what element you are hovering over.
			 */
			//image hover
			$('img', facet).hover(
				function(){ tooltip = opts.imageTooltip	},
				function(){	tooltip = opts.facetTooltip;}
			);
			//edit hover
			$('.facetActions', facet).hover(
				function(){	tooltip = opts.editTooltip;	},
				function(){	tooltip = opts.facetTooltip;}
			);
			
		}
		
		/**
		 * This private click handler will check a user defined function for 'true', and then 
		 * detect the source of the click, dispatching the appropriate function.
		 * 
		 * @param $this - the jQuery object representing the list item the click is originating from
		 * @param e - the click event
		 */
		function _onFacetClick($this, e) {
			if(opts.onFacetClick($this, e)) {
				var target = $(e.target);
				if(target.is('img')) {
					opts.onImageClick($this, e);
				} else if(target.is('.facetActions,.editIcon')){
					opts.onEditClick($this, e);
				} else {
					opts.onFacetFilter($this, e);
				};  
			}
		}
		
		/**
		 * This function gets called every time the user clicks on 'show more/less'. It determines if the additional facets
		 * have already been loaded, and what the current state of the widget is, and take appropriate action.
		 */
		function showMoreFacets() {
			if(!alreadyLoadedFacets) {
				loadAndAppendFacets();
			} else {
				if(status == OPEN) {
					$('.additionalFacet').show();
					$('#showMoreFacets').text('Less');
					status = EXPANDED;
				} else if(status == EXPANDED){
					showLessFacets();
				} else if(status == CLOSED) {
					$('#facetsListCtn').activate(0);
					$('#showMoreFacets').text('Less');
					status = EXPANDED;
				}
			}
		}
		
		/**
		 * Contracts the widget, and hides all the facets that have been marked as additional
		 */
		function showLessFacets() {
			$('#showMoreFacets').text('More');
			$('.additionalFacet').hide();
			status = OPEN;
		}
		
		/**
		 * This will load the JSON object of additional facets, pass them to be turned into HTML, and the append
		 * the result onto the page, and then expand the widget.
		 * 
		 * AB: this is no longer required. The facets will be paged instead.
		 */
/*		function loadAndAppendFacets() {
			$.getJSON(opts.moreFacetsUrl,
				function(data) {
					var facets = $(data.facets);
					var facetList = $('#facetsListBd');
					facets.each(function(i) {
						var newFacet = generateFacetHTML(facets[i]);
						facetList.append(newFacet);
						attachEvents(newFacet);
					});
					alreadyLoadedFacets = true;
					showMoreFacets();
				}
			);
		} */
		
		/**
		 * Will generate html from a JSON object of a facet
		 * @param facet - a JSON object with the following properties: photoSrc, name, socialContext
		 * @return a DOM object of a single Facet li
		 */
		function generateFacetHTML(facet) {
			var html = '<li class="facetsListItem additionalFacet">'
			html += '<a href="" class="facetPhotoLnk"><img src="' + facet.photoSrc + '" alt="" /></a>'
			html += '<a href="test" class="facetActions"><span class="editIcon"></span>Edit</a>'
			html += '<div class="facetInfo">'
			html += '<span class="facetName">' + facet.name + '</span>'
			html += '<span class="facetContext">' + facet.socialContext + '</span></div></li>'
			
			return $(html);
		}

		//trigger the init() function now that all functions have been declared
		init(this);
	};
	
	$.fn.facetWidget.defaults = {
		facetListItemSelector: '.facetsListItem:not(.emptyList)',
		imageTooltip: 'Preview Facet',
		facetTooltip: 'Filter Feeds',
		editTooltip: 'Edit Facet',
		onFacetClick: function($this, e){
			//Use this function to control weather or not the click functions will excecute.
            console.log('facet clicked')
			return true;
		},
		onImageClick: function($this, e){
			//Use this function to control the image click.
            console.log('image clicked')
			return true;
		},
		onEditClick: function($this, e){
			//Use this function to control the edit click
            console.log('edit clicked')
			return true;
		},
		onFacetFilter: function($this, e){
			//Use this function to control the filter action
            console.log('facet filter')
		},
		onFacetHover: function($this) {
			$this.addClass('hoverOn');
		},
		onFacetMouseOut: function($this) {
			$this.removeClass('hoverOn');
		}
	};
})(jQuery);

$j(function(){
 
	var elem = $j("#facetsListCtn");
	if(elem.length > 0) {
		elem.facetWidget({
			onFacetFilter : function($this, e) {

                // Get the 'preview facet' url and use this to create the 'filter feed' url
                var previewFacetUrl = $j($this).find('a.showFacetLnk').get(0).href;
                var filterFeedUrl = previewFacetUrl.replace('preview', 'filterFeedHideSummary');
                document.location.href = filterFeedUrl;
			}
		});
	}
});