/**
 * @author Alex Greenland
 * 
 * Provides base functionality for the smart filtering 
 */
SmartFilter = function(){

	function implode (glue, pieces) {
    	return ( ( pieces instanceof Array ) ? pieces.join( glue ) : pieces );
	}

	function setBlockingParams() {
		$.blockUI.defaults.overlayCSS = {};
		$.blockUI.defaults.centerY = false;
		$.blockUI.defaults.css.width = '90%';
		$.blockUI.defaults.css.padding = '5px 0px 5px 0px';
	}

    function getURI(href) {
    	var thisURL = document.location.href;
    	var QueryString = '';
    	var i = (thisURL+'').indexOf('?');
    	if (i !== -1) {
    		var temp = thisURL.split('?');
    		QueryString = temp[1];
    		thisURL = temp[0];
    	}
    	if (href !== null) {
			if (href.charAt(0) === '?' || href.charAt(0) === '&') {
				href = href.substring(1);
			}
			thisURL += '?' + href + '&' + QueryString;
    	} else {
    		if (QueryString !== '') {
    			thisURL += '?' + QueryString;
    		}
    	}
    	return thisURL;
    }
    
    return {
		/**
		 * Sets the base paramaters
		 * 
		 * containerelement - The container to show the results within
		 * filterelement - The element to show the modified filters in
		 * 
		 * @param {Object} params
		 */
        setParams: function(params){
            this.params = {};
            $.extend(this.params, {
                containerelement: 'filterresultscontainer',
                filterelement: 'filterscontainer'
            }, params);
        },
        
		/**
		 * Update the container element
		 * 
		 * @param {Object} href
		 */
        update: function(href){

			if ($.unblockUI) {
				setBlockingParams();

				$('#' + this.params.filterelement).block({
					message: '<h2 class="loading"><img src="/images/indicator.gif" /> <span>Loading</span> </h2>'
				});
			}
			
			var me = this; // NASTY hack to overcome scope issues in jQuery
			var fullURL = getURI(href);
            $('#' + this.params.containerelement).load(fullURL, {}, function(){
                $('#' + me.params.filterelement).load('/action.php?cdx=smartfilter&t=filters&ismd5=true',{},function(){
					me.setResetButtons();
					if ($.unblockUI) {
						$('#' + me.params.filterelement).unblock();
					}
				});
            });
        },
		
		/**
		 * Loads a new page of products
		 * @param {Object} pageNumber
		 */
		loadPage : function(element) {

			if ($.unblockUI) {
				setBlockingParams();
				$('#' + this.params.filterelement).block({
					message: '<h2 class="loading"><img src="/images/indicator.gif" /> <span>Loading</span> </h2>'
				});
			}

            var me = this; // NASTY hack to overcome scope issues in jQuery
			var fullURL = getURI(null);
			$('#' + this.params.containerelement).load(element.href, {}, function(){
				if ($.unblockUI) {
					$('#' + me.params.filterelement).unblock();
				}
			});
			
			return false;
		},

		/**
		 * Reset the number of results per page
		 * 
		 * @param {Object} href This is the <a> tag with an href to indicate page size
		 */
		productsPerPage : function(href) {
            var me = this; // NASTY hack to overcome scope issues in jQuery
			var fullURL = document.location + $(href).attr('href');
			$('#' + this.params.containerelement).load(fullURL, {}, function(){
				$('#' + me.params.filterelement).unblock();
			});
		},
		
		/**
		 * Resets all of the filters under the selected heading
		 * 
		 * @param {String} elementName The name of the element to find and erset children under
		 */
		reset : function(elementName) {
			var element = $('ul#'+elementName);
			
			if (element && element.length > 0) {
				var resetElements = $('ul#'+elementName+' li');
				
				var values = [];
				
				for (i=0; i < resetElements.length; i++) {
					if ($(resetElements[i]).attr('md5')) {
						values.push($(resetElements[i]).attr('md5'));
					}
				}
				
				var resetValues = implode(',',values);			

				if ($.unblockUI) {
					setBlockingParams();
					$('#' + this.params.filterelement).block({
						message: '<h2 class="loading"><img src="/images/indicator.gif" /> <span>Loading</span> </h2>'
					});
				}
	
				var thisURL = document.location.href;
				var me = this; // NASTY hack to overcome scope issues in jQuery
	            $('#' + this.params.containerelement).load(thisURL, {type:'reset',values:resetValues}, function(){
	                $('#' + me.params.filterelement).load('/action.php?cdx=smartfilter&t=filters&ismd5=true',{},function(){
						me.setResetButtons();
						if ($.unblockUI) {
							$('#' + me.params.filterelement).unblock();
						}
					});
	            });				
				return false;
			}	
		},
		
		setResetButtons : function() {
			var filterHeadings = $('ul.sfilters');

			if (filterHeadings && filterHeadings.length > 0) {
				for (i = 0; i < filterHeadings.length; i++) {
					var id = $(filterHeadings[i]).attr('id');
					var selectedFilters = $('ul#' + id + ' > li.active');
					var imageTag = $('ul#' + id + ' img.clearf');
					if (selectedFilters && selectedFilters.length > 0) {
						imageTag.removeClass('hidden');
					} else {
						imageTag.addClass('hidden');
					}
				}
			}
						
			
		}
    };
};

var smartFilter = new SmartFilter();

$(document).ready(function(){
	smartFilter.setResetButtons();
});
