/* Which? Product finder js */
/* Last updated: 20 August 2008 */

// comparison basket and filter panels
jQuery(function($) {

	// intitalise vars
	var shortList = [];	
	var itemsPerRow = 4;	
	var emptyItemStr = '<li class="empty"><span class="removed">Empty</span></li>';
	var urlMarkers = ['product-finder', 'from-product-finder', 'compare'];
	
	// get dom elements
	var $filterList = $('#filter-tabs ul');
	var $filterPanelGroup = $('#filter-panel-group');
	var $filterPanelList = $('#filter-panel-group > div');	
	var activeFilterId = $filterList.find('li.on').attr('id');

	// build shortlist array from page-reload render
	$('#shortlist ul').children('li:not(.empty)').each(function () {	
		shortList.push($(this).attr('class'));
	});	

	// event delegation (all clicks handled here)...
	$('#productFinder').click(function(event) {

		// get target
		var $tgt = $(event.target);
			 
		// condition : is add
		if ($tgt.parent().is('a.add')) {
			return add($tgt.parent());	
			
		// condition : either of the remove buttons
		} else if ($tgt.parent().is('a.remove') || $tgt.is('a.remove')) {
			return remove($tgt.parent());
			
		// condition : is filter panel tab
		} else if ($tgt.parents('#filter-tabs').length == 1) {
			return swapFilterPanel($tgt);
			
		// condition : is form button
		} else if ($tgt.is('input.button')) {
			return submitForm($tgt);
		}
		
		// condition : is a page reload link (excluding start again)
		if ($tgt.parents('#start-again').length == 0) {
			if ($tgt.is('a')) {
				return reload($tgt);
			} else if ($tgt.parent().is('a')) {
				return reload($tgt.parent());		
			}
		}
	
		return true;
	});
	
	/*
	 * Function to add a product to shortlist
	 * 
	 * @param int $link Clicked link
	 */
	function add($link) {

		// condition : first item to be added then flag?
		if (shortList.length == 0) {
			var isFirstTime = true;
		} else {
			var isFirstTime = false;
		}
	
		// add name to shortlist array
		shortList.push($link.parent().attr('id'));	

		// change classes
		$link.removeClass('add').addClass('remove');
		
		// dom changes
		_renderFeedback($link.parent(), "added", isFirstTime);
			
		// swap image
		_swapImage($link, 'remove-cross2.png', "Remove this product from the comparison basket");
		
		// dom changes
		_renderShortList();

		return false;
	}	
	
	/*
	 * Function to remove a product from shortlist
	 * 
	 * @param int $link Clicked link
	 */
	function remove($link) {

		// 2 remove buttons - try id first (table remove) then class (shortlist remove)
		var productName = $link.parent().attr('id') || $link.parent().attr('class');	
		
		// find product in shortlist array
		var productIndex = jQuery.inArray(productName, shortList);	
	
		// get the link in the table
		var $cellLink = $('#'+productName+' a');
		
		// dom changes
		_renderFeedback($cellLink.parent(), "removed");
		
		// change classes
		$cellLink.removeClass('remove').addClass('add');	
		
		// swap image
		_swapImage($cellLink, 'add-plus2.png', "Add this product to the comparison basket");
		
		// remove add from shortlist array
		shortList.splice(productIndex, 1);
			
		// fade out before changing dom so user is sure which item was removed		
		$('.'+productName).fadeOut(1000, function () {

			// dom changes
			_renderShortList();	
				
      	});
	
		return false;
		
	}	
	
	/*
	 * Function to build urls to maintain state through reloads
	 * 
	 * @param int $link Clicked link
	 */
	function reload($link) {

		// initalise vars
		var productIndex = -1;
		var parts = $link.attr('href').split('/');

		// loop through trying to find products marker
		for (i in urlMarkers) {
			if (productIndex == -1) {
				productIndex = jQuery.inArray(urlMarkers[i], parts);	
			}
		}

		// reload
		window.location.href = _buildUrl(parts, productIndex);
			
		return false;
	}
	
	/*
	 * Function to build actions to maintain state through reloads
	 * 
	 * @param int $link Clicked link
	 */
	function submitForm($link) {
		
		// get id from string
		var activeFilterIdInt =  activeFilterId.split('-');
		activeFilterIdInt = activeFilterIdInt[activeFilterIdInt.length - 1];
		
		// update hidden form vars
		$('#productList').val(shortList.join(','));
		$('#activeForm').val(activeFilterIdInt);

		// submit the parent form of the link clicked
		$($link.parents('form').get(0)).submit();
		
		return false;
	}
	
	
	/*
	 * Function to swap filter panels
	 * 
	 * @param int $link Clicked link
	 */
	function swapFilterPanel($tgt) {

		var $tgtListItem = $tgt.parent().parent();
		
		// condition : only continue if non-active		
		if ($tgtListItem.hasClass('off')) {
		
			// get data on clicked item
			var index = $filterList.children('li').index($tgtListItem[0]);
			var text = $tgtListItem.text();
			activeFilterId = $tgtListItem.attr('id');
			
			// get data on previously active item
			$on = $filterList.find('li.on:first');
			var onHTML = $on.html();		
			var onText = $on.text();
			var onIndex = $filterList.children('li').index($on[0]);
		
			// swap the html over between previously active and selected, then reset the correct text
			$tgtListItem.children().clone().prependTo($on.empty()).find('span').text(onText);
			$tgtListItem.empty().html(onHTML).find('span').text(text);
			
			// set off state to all filter tabs
			$filterList.children('li').removeClass('on').addClass('off');
					
			// set on state
			$tgtListItem.removeClass('off').addClass('on');
			
			// set a height on the group to avoid jump
			$filterPanelGroup.css('height', $filterPanelList.eq(onIndex).css('height'));
			
			// hide all the panels
			$filterPanelList.hide();
			
			// show only the corresponding panel
			$filterPanelList.eq(index).show();
			
			// reset jump fix
			$filterPanelGroup.css('height', 'auto');	
		}
		
		return false;
	}
	
	
	/*
	 * Private function to reconsturct a url from parts
	 * 
	 * @param array parts Parts of url
	 * @param int index Product marker
	 */
	function _buildUrl(parts, index) {
		
		// condition : no product slot yet (page is always 2nd param)
		var prefix = 'basket-';
		if (parts[index].match(/compare/)) index++;
		if (parts[index+1].match(/page-[0-9]/)) {	
			// add in the joined shortlist
			parts.splice(index+1, 0, prefix + shortList.join(','));
		} else {
			// replace existing products
			parts[index+1] = prefix + shortList.join(',');
		}
		
		// update activefilter data
		var activeFilterIndex = 0;
		jQuery.each(parts, function(i, value) {
			// condition : not empty?
			if (value.match(/activefilter-/)) {
				activeFilterIndex = i;
			}
		});
		
		// condition : only update activefilterid if present in original url
		if (activeFilterIndex != 0) {
			parts[activeFilterIndex] = activeFilterId;
		}
		
		// join back together	
		return parts.join("/");
	}
	
	/*
	 * Private function to swap an image src
	 * 
	 * @param object $link The owning link
	 * @param string imageFileName The filename
	 * @param string altText Alt text for image
	 */
	function _swapImage($link, imageFileName, altText) {
		if ($link.children("img").length) {
			var pathToImage = $link.children("img").attr("src").split("/");
			pathToImage[pathToImage.length-1] = imageFileName;
			$link.children("img").attr("src", pathToImage.join("/"));
			$link.children("img").attr("alt", altText);
			$link.children("img").attr("title", altText);
		}
	}
	
	/*
	 * Private function to render feedback
	 * 
	 * @param object $cell The cell to apply feedback to
	 * @param string message The message to display
	 * @param bool isFirstTime First item to be added flag
	 * 
	 */
	function _renderFeedback($cell, message, isFirstTime) {
		
		var $feedback = $('<div id="feedback" class="'+message+'fb">Item '+message+' above</div>');
		
		$cell.append($feedback);
		
		// condition : if firstime then longer fadeout
		if (isFirstTime) {
			var fadeTime = 5000;
		} else {
			var fadeTime = 1500;
		}

		$feedback.fadeOut(fadeTime, function () {
        	$feedback.remove();				
      	});
	}
	
	/*
	 * Private function to build the dom based on the shortlist array
	 */
	function _renderShortList() {
		
		// contains the built dom objects
		var shortListObjs = [];
		
		// loop through each item in the shortlist building the dom objects
		jQuery.each(shortList, function(i, val) {

			// condition : already in the shortlist dom? then use that
			if ( $('#shortlist .' + val).length ) {
				
				shortListObjs.push($('#shortlist .' + val));
		
			// else : build from the table element	
			} else if ($('#' + val).length ) {
				
				// get image path
				var imagePath = ($('#' + val + ' + td.product-name a:eq(0) img').attr('src'));
				
				// condition : not a placeholder then rewrite path
				if (!imagePath.match(/_placeholders/)) {	
					// build thumbnail image path
					imagePath = imagePath.split('/');
					imagePath[imagePath.length - 2] = 'product60x60';
					imagePath = imagePath.join("/");
				}
				
				// get the product name from the cell
				var name = $('#' + val + ' + td.product-name a:eq(1)').html();
				
				//get url			
				var parts = $('#' + val + ' a').attr('href').split('/'); 
				var productIndex = jQuery.inArray('product-finder', parts);	
				var url = _buildUrl(parts, productIndex);
			
				// build the html object
				var $html = $('<li class="'+val+'"><div class="product-image"><img src="'+imagePath+'" alt="" height="35" width="35" /></div><div class="details"><a class="remove" href="'+url+'">Remove</a>'+name+'</div></li>');
				
				// add object to array
				shortListObjs.push($html)
			}
    	});
		
		// condition : not a complete row?  then build empty items
		if (shortList.length % itemsPerRow != 0) {
			
			// calculate number required
			var empties = ((Math.floor(shortList.length / itemsPerRow) + 1) * itemsPerRow) - shortList.length;
			
			// add the required number to the obj array
			for (var x = 1; x <= empties; x++) {
				shortListObjs.push(emptyItemStr);
			}				
		}
	
		// condition : not items? then rmeove the shortlist from the dom
		if (shortListObjs.length == 0) {
			$('#shortlist').remove();
			$('.compare-button a').remove();	
		} else {
			// condition : if already exists then empty
			if ($('#shortlist').length) {
				$('#shortlist').empty().append('<ul></ul>');
			// else : create shortlist
			} else {	
				$('#select-for-comparison').prepend('<div id="shortlist"><ul></ul></div>');	
				var compare = shortListObjs[0].find('a').attr('href');
				compare = compare.replace(/\/product-finder\//g, '/compare/page-1/');
				$('.compare-button').prepend('<a href="' + compare + '"><img alt="Compare Features" src="/assets/images/buttons/btn-compare-features.png" /></a>');
			}	
			// compare buttons		
		}
		
		// loop through all the objs (products and empty cells) and split into lists
		jQuery.each(shortListObjs, function(i, val){
			
			// condition : start new list?
			if (i > 0 && i % 4 == 0) {
				$('#shortlist ul li:last').parent().after('</ul><ul>')
			}
	
			// add the item to the correct list
			$('#shortlist ul:eq('+(Math.floor(i/itemsPerRow))+')').append(val);
			
		});			
	}
});
 
// which ratings sort by dropdown
jQuery(function($) {
 	
	// condition : got options array render to page?
	if (typeof pfSortOptions=="object") {
		
		// init vars
		var $columnHeadings = $('th.which-ratings');	
		var $sortContainer = $('<div class="sortby-ratings"><span><a href="#">Sort by:</a></span><ul></ul></div>');	
				
		// build options from array
		jQuery.each(pfSortOptions, function () {
			$sortContainer.children('ul').append(this);
		});	
		
		// append options to heading cell and fix position
		$columnHeadings.append($sortContainer);
		$('.sortby-ratings ul li:last-child').addClass('last');
		var $sortLists = $('.sortby-ratings ul');
		
		// hide it
		$sortLists.hide();
		
		// condition : tweak position if ie6 (doesn't repect right css value)
		if (jQuery.browser.msie && parseInt(jQuery.browser.version) == 6 ) {
 			$('.sortby-ratings ul').css('margin-right', 125+"px");
		}	
		
		// disable action on link
		$('.sortby-ratings span a').click(function(event){
		  event.preventDefault();
		  return false;
		});
		
		// on hover...
		$('.sortby-ratings').hoverIntent(function() {
			
			// dom objects
			$sortContainer = $(this);		
			$sortContainer.addClass('active');
			var $span = $sortContainer.find('span');
			var $sortList = $sortContainer.children('ul');
			
			// calculations
			var height = $sortList.height() + $sortContainer.outerHeight();
			var winHeight = $(window).height();
			var winYScroll = $(window).scrollTop();
			var yOfSort = $sortContainer.offset().top;
			
			// presentation border around "sort by"
			$span.css('border', '1px solid #8C9DA5');
			
			// condition : close to bottom fold
			if (height + yOfSort > winHeight + winYScroll) {
				
				// condition : ie needs height tweaks
				if (jQuery.browser.msie) {
					// ie 6
					if (parseInt(jQuery.browser.version) == 6) {
						heightAdjust = -33;
					} else if (parseInt(jQuery.browser.version) == 7) {
						// ie 7
						heightAdjust = -37;
					}
					
				} else {
					// all other browsers
					heightAdjust = -12;
				}
						
				// show upwards and render border on span
				$span.css('border-top', '1px solid #FFFFFF');		
				$sortList.css('top', (height * -1 - ($span.outerHeight() + heightAdjust))+'px');
				
			} else {
						
				// show downwards and render border on span
				$span.css('border-bottom', '1px solid #FFFFFF');
				$sortList.css('top', ($span.outerHeight() - 5)+'px');

			}
			
			// show it
			$sortList.show();
			
		}, function() {
			// hoverout then reset borders and hide list
			$(this).find('span').css('border', '1px solid #FFF');
			$(this).children('ul').hide();	
		});
		
	}   
});
  