/**
 * All Functionality related to the Filter Flyouts in SPD
 * @author Laura Martinez.
 * @version 0.0.1
 * var FilterFlyOut = new FilterFlyOut();
 */

 function FilterFlyOut(){
 
 	/**
	 * Public Methods 
	 */
	var filterFly = $(document).find('#filterFly');
	var filterWrapper = $(document).find('#filterWrapper');
	var filterFlyContent = $(document).find('#filterFlyContent');
	var buttons = $(document).find('.product_finder a');
	var previousButton = $(document).find('.navigationLinks #previousBtn');
	var moreButton = $(document).find('.navigationLinks #moreBtn');
	var continueButton = $(document).find('#continueBtn');
	var productFinderForm = $(document).find('#productFinderForm');
	var loader = $(document).find('.loaderImg');
	var helpFlag = $(document).find('#helpFlag');
	var errorMessage = $(document).find('.errorMessage', filterFlyContent);
	var pagesNumber;
	var currentPosition = 1;
	var identificator;
	var truncateLimit = 15;
	var ajaxProcess = null;
	var buttonsCopy;
	var errorExists = false;
	
	
	/**
	 * Private Methods
	 */
	var init = function(){
		void showFilter();
		void navigateFlyOut();
		void resetFlyOut();
		void validateForm();	
		
		$('input', productFinderForm).val('');
	};
	
	/**
	 * Method that handles the conditions for displaying and hiding the flyouts.
	 */			
	var showFilter = function(){
	
		var flyOutTimer = null;
		var regretingTimer = null;
		var buttonTimer = null;
	
		$('li.showFilterFly').hover(function() {
						
			clearTimeout(flyOutTimer);
			clearTimeout(regretingTimer);
			clearTimeout(buttonTimer);
								
			var scope = $(this);
			var activeFilterButton = $('.activeFlyout', scope);
			$(helpFlag).hide();
			
			buttonTimer = setTimeout(function() {
				
				resetFlyOut();
				
				identificator = $(scope).attr('id');
				buttonsCopy = (identificator == 'category') ? 'categorie' : identificator;
				
				if ((ajaxProcess != identificator) && (!errorExists)) {
					$(loader).hide();
					populateFlyout(identificator);
				}	
					
				$(filterFly).show();
				$('span', activeFilterButton).html($('a', scope).text());
				$(activeFilterButton).show();
				$('a', scope).css('visibility','hidden');
				
				selectFlyoutOption(scope);					
				
			}, 500);
				
		}, function(){
		
			flyOutTimer = setTimeout(function(){
				resetFlyOut();
			}, 500);
	
		});	
		
		$(filterFly).hover(function(){
		
			clearTimeout(flyOutTimer);
			clearTimeout(regretingTimer);
			clearTimeout(buttonTimer);
			
		}, function(){		
			
			regretingTimer = setTimeout(function() {
				resetFlyOut();
			}, 1000);
			
		});	
	};
	
	
	var populateFlyout = function(selection){
	
		var content;
		var listItems;		
	
		content = $('#' + selection + 'Content').html();			
		listItems = $('#' + selection + 'Content ul li');

		$(filterFlyContent).html(content);
					
		if ($(listItems).length > 28) {
					
			$(previousButton).html('&lt; previous ' + buttonsCopy + 's');
			$(moreButton).html('more ' + buttonsCopy + 's &gt;');
			$(moreButton).show();
			$(filterFlyContent).addClass('long_list');				
			
			pagesNumber = Math.ceil($(listItems).length/28);
			
		}
		
		if ($(listItems).length > 7) {
			splitFilterCol();
		}
	
	};
	
	/**
	 * Method that splits the list in columns.
	 */	
	
	var splitFilterCol = function(){
		var count = 0;
		var maxItems = 6;
		var itemsPerCol = Math.ceil($('ul li', filterFlyContent).length / 7);			
					
		
		for (var i = 1; i <= itemsPerCol; i++) {		
			$('ul li', filterFlyContent).filter(function(index) {
				return index >= count && index <= maxItems
			}).wrapAll('<ul></ul>');
			
			count += 7;
			maxItems += 7;
		}
	};
	
	/**
	 * Method that contains the events for the navigation links in the flyout.
	 */	
	
	var navigateFlyOut = function()
	{	
		$(moreButton).click(function(){
		
			var rate;
		
			if ($(filterWrapper).width() <= 685){		
				rate = 711;
			}
			else
			{
				rate = 948;
			}
		
			if (currentPosition < pagesNumber) {
				$(filterFlyContent).animate({left: '-=' + rate}, 700);
				$(previousButton).show();
				currentPosition++;
				
				if (currentPosition == pagesNumber)
				{
					$(moreButton).hide();
				}
			}
		
		});
		
		$(previousButton).click(function(){
		
			var rate;
		
			if ($(filterWrapper).width() <= 710){		
				rate = 711;
			}
			else
			{
				rate = 948;
			}
		
			if (currentPosition > 1) {
				$(filterFlyContent).animate({left: '+=' + rate}, 700);
				currentPosition--;
				
				if (currentPosition == 1)
				{
					$(previousButton).hide();
				}
				
				if (currentPosition == (pagesNumber - 1))
				{
					$(moreButton).show();
				}
			}
		
		});
		
	};
	
	/**
	 * Method that sets the form depending on the selection made by the user in the flyout.
	 */	
	
	var selectFlyoutOption = function(activeButton)
	{	
		$('a', filterFlyContent).click(function(){
			$('a', activeButton).addClass('product_finder_selected');
			$('a', activeButton).html(truncateCopy($(this).text()) + '<span></span>');
			$('input', activeButton).val($(this).text());
			ajaxCall($(this).attr('href'), identificator);
			resetFlyOut();
			
			return false;
		});
	
	};
	
	/**
	 * Method that resets content and states for reusing the flyout.
	 */	
	
	var resetFlyOut = function()
	{
		$(filterFly).hide();
		$(filterFlyContent).html('');
		$(filterFlyContent).removeClass('long_list');
		$(previousButton).hide();
		$(moreButton).hide();
		$(buttons).css('visibility','visible');
		$(filterFlyContent).css('left', 0);
		currentPosition = 1;	
		$('.activeFlyout').hide();				
		$(filterFlyContent).empty();
	};
	
	/**
	 * Method that filters the content using Ajax depending on a previous selection.
	 */	
	
	var ajaxCall = function(newUrl, trigger)
	{	
		
		$(errorMessage).hide();	
		$(loader).show();
		var activeBtn;
		
		
		$.ajax({
			type: "POST",
			url: newUrl,
			success: function(response) {		
				
				var responseString = response;
				
				if(trigger == 'category'){		
					ajaxProcess = 'brand';			
				}
		
				if(trigger == 'brand'){		
					ajaxProcess = 'category';
				}

				if ((responseString.indexOf("Error") != -1) || (response == ''))
				{		
					$(loader).hide();
					$(errorMessage).show();
					errorExists = true;
					$('a', errorMessage).click(function(){
						ajaxCall(newUrl, trigger);
					});		
				}
				else {
					errorExists = null;
					
					$('#'+ ajaxProcess +'Content').html(response);
					
					if (identificator != ajaxProcess) {
						displayFlag(ajaxProcess);
					}
					
					if (identificator != trigger)
					{
						populateFlyout(ajaxProcess);
						activeBtn = $('li#' + ajaxProcess);	
					}
									
					selectFlyoutOption(activeBtn);
					$(loader).hide();
					ajaxProcess = null;
				}
				
			},
			error: function()
			{	
				$(loader).hide();
				$(errorMessage).show();
				errorExists = true;
				$('a', errorMessage).click(function(){
					ajaxCall(newUrl, identificator);
				});								
			}   
		});	
	};
	
		
	 /**
	 * Method that validates the form and submits it.
	 */	
	
	var validateForm = function()
	{
		$(continueButton).click(function(event){
		
			event.preventDefault();
			
			if(($('input#brandInput', productFinderForm).val() == '') && ($('input#categoryInput', productFinderForm).val() == ''))
			{
				event.preventDefault();
			}
			else
			{
				(productFinderForm).submit();
			}
		});	
	
	};
	
	/**
	 * Method that shows the help flag depending on the selection.
	 */	
	
	var displayFlag = function(identificator)
	{		
		$(helpFlag).css('opacity', 0);
		
		var distance = 10;
		var timer = 250;
		
		if ($('#' + identificator + 'Input').val() == ''){		
			$('span', helpFlag).html('Now select a ' + identificator);
			$(helpFlag).css('top', $('li#' + identificator).offset().top - 196 + 'px');

			$(helpFlag).css({
            	display: 'block'
			}).animate({
				top: '-=' + distance + 'px',
				opacity: 1
			}, timer);
		}
		
		setTimeout(function() {
			
			$(helpFlag).animate({
				top: '-=' + distance + 'px',
				opacity: 0
			}, timer, function () {
				$(helpFlag).hide();
			}); 

			
		}, 3500);
	}
	
	/**
	 * Method that truncates the copy when it doesn't fit in the buttons.
	 */	
	
	var truncateCopy = function(name)
	{
		if (name.length > truncateLimit)
		{
			return (name.substring(0, truncateLimit) + " ...");
		}
		else
		{
			return name;
		}
	
	};
		
	init();
	return this;
};

