var ajaxProductCompareRequestObj = new Request({method: 'get', url: '/js/ajax/product_comparison_updater.php'});
var ProductCompareEventHandlers = {
	initialiseProductCompareHandlers : function() {
		var productCompareLinks = ($('associated_products')) ? $('associated_products').getElements('div.compare a') : false;
		if(productCompareLinks) {
			productCompareLinks.each(function(productCompareLink, index) {
				productCompareLink.addEvent('click', ProductCompareEventHandlers.addRemoveToggle);
			});
		}
	},
	enableDisableProductCompareHandlers : function() {
			var noOfComparedProducts = ProductCompareComparisonList.getElements('li').length;
			if(noOfComparedProducts == ecommerce_maximum_no_of_comparison_products) {
				var productCompareLinks = ($('associated_products')) ? $('associated_products').getElements('div.compare a.add') : false;	
				if(productCompareLinks) {
					productCompareLinks.each(function(addLink, index) {
						addLink.removeClass('add').addClass('full').setStyle('cursor', 'default');
						addLink.getElement('span').set('text','comparison list full');
						addLink.removeEvent('click', ProductCompareEventHandlers.addRemoveToggle);
						addLink.addEvent('click', function(){return false;})
					});
				}
			} else if(noOfComparedProducts < ecommerce_maximum_no_of_comparison_products) {
				var productCompareLinks = ($('associated_products')) ? $('associated_products').getElements('div.compare a.full') : false;
				if(productCompareLinks) {
					productCompareLinks.each(function(fullLink, index) {
						fullLink.removeClass('full').addClass('add').setStyle('cursor', 'pointer');;
						fullLink.getElement('span').set('text','add to comparison list');
						fullLink.addEvent('click', ProductCompareEventHandlers.addRemoveToggle);
					});
				}
			}
	},
	transitionToList : function(product) {
		var bodyElement = document.body;
		var newPosition = $('ProductComparisonPlugin').getPosition($('wrapper'));
		var startingSize = product.getComputedSize();
		var newProduct = product.clone().setPosition(product.getPosition($('wrapper'))).setStyles({
			'position':'absolute',
			'width':startingSize.width,
			'height':startingSize.width,
			'min-height':startingSize.width,
			'opacity':1
		});
		$('wrapper').grab(newProduct);
		var transition = new Fx.Morph(newProduct, {
			duration: 500,
			transition: Fx.Transitions.Linear,
			onComplete: function(){
				newProduct.destroy();
        	}
		});
		transition.start({
			'top':newPosition.y,
			'left':newPosition.x,
			'opacity':0
		});
	},
	addRemoveToggle : function(event) {
		event.stop();
		var URLDataArr = this.get('href').split('?');
		var action_ProductId = URLDataArr[1];
		var productId = action_ProductId.split('=')[1];
		var product = ($('product'+productId)) ? $('product'+productId) : false;
		var ajaxSuccess = false;
		if(this.hasClass('add')) { // 'this' references a product element
			ajaxProductCompareRequestObj.send(action_ProductId + '&ajax_request=1');
			ajaxSuccess = ajaxProductCompareRequestObj.success = (function() {
				var productToAdd = new ProductCompareListItemElement($('product'+productId)).getListItem().setStyle('opacity',0);
				ProductCompareComparisonList.grab(productToAdd, 'bottom');
				var productFadeIn = new Fx.Tween(productToAdd, {property: 'opacity', onComplete:function(){
					if(ConstrainedSidebar) {
						/* Co-operate with the Constrained sidebar plugin, because the size of the container may have changed */
						setTimeout(ConstrainedSidebar.reposition.bind(ConstrainedSidebar), ConstrainedSidebar.options.speed);
					}
				}});
				productFadeIn.start(0,1);
				
				//productToAdd.tween('opacity',0,1);
				this.removeClass('add').addClass('remove').set('href', URLDataArr[0] + '?del=' + productId);
				this.getElement('span').set('text', 'remove from comparison list');
				$('noProductComparisonItems').setStyle('display', 'none');
				if($('compareButton').getStyle('display') == 'none') $('compareButton').setStyle('display','block');
				if(product) ProductCompareEventHandlers.transitionToList(product);
				ProductCompareEventHandlers.enableDisableProductCompareHandlers();
				return true;
			}).bind(this, productId);
		} else if (this.hasClass('remove')) { // 'this' could reference a list item or a product element
			ajaxProductCompareRequestObj.send(action_ProductId + '&ajax_request=1');
			ajaxSuccess = ajaxProductCompareRequestObj.success = (function() {
				var productToRemove = ProductCompareComparisonList.getElement('li.product' + productId);
				var slider = new Fx.Slide(productToRemove);
				slider.addEvent('complete', function() {
					productToRemove.destroy();
					ProductCompareComparisonList.getChildren('div').destroy();// Remove the slide wrapper div for tidy HTML
					if(ProductCompareComparisonList.getElements('li').length == 0) {
						$('noProductComparisonItems').setStyle('display', 'block');
						$('compareButton').setStyle('display','none');
					}
					ProductCompareEventHandlers.enableDisableProductCompareHandlers();
					if(ConstrainedSidebar) {
						/* Co-operate with the Constrained sidebar plugin, because the size of the container may have changed */
						setTimeout(ConstrainedSidebar.reposition.bind(ConstrainedSidebar), ConstrainedSidebar.options.speed);
					}
				});
				slider.slideOut();
				if(product)	{
					product.getElement('div.compare a').removeClass('remove').addClass('add').set('href', URLDataArr[0] + '?add=' + productId);
					product.getElement('div.compare span').set('text', 'add to comparison list');
				}
				return true;
			}).bind(this, productId, product);
		}
		if(ajaxSuccess) {
			if(product) {
				product.toggleClass('compared');
				setTimeout(ProductCompareComparisonList.renderStripes, 500);//Persist row styling re-classing each li
			}
			if(ConstrainedSidebar) {
				/* Co-operate with the Constrained sidebar plugin, because the size of the container may have changed */
				setTimeout(ConstrainedSidebar.reposition.bind(ConstrainedSidebar), ConstrainedSidebar.options.speed);
			}
		}
		
	}
}
// Product list item object definition
var ProductCompareListItemElement = function(productInfoEl) { // pass in the product element
	this.productId = productInfoEl.get('id').replace(/product/i, '');
	this.removeLink = new Element('a',{
		'href':productInfoEl.getElement('div.compare a').get('href').split('?')[0] + '?del=' + this.productId,
		'html':'<span>remove</span>',
		'class':'remove',
		'events' : {
			'click':ProductCompareEventHandlers.addRemoveToggle
		}
	});
	this.imageContainer = productInfoEl.getElement('div.image').clone();
	this.image = this.imageContainer.getElement('img');
	this.imageContainer.getElement('a').setStyles({width:ProductCompareImageObj.width,height:ProductCompareImageObj.height});
	// Resize the image as per the box settings provided by the CMS
	this.getImageSize = function (imgSizeObj) {
		if(!(parseInt(ProductCompareImageObj.width) > 0) && !(parseInt(ProductCompareImageObj.height) > 0)) return;
		if(imgSizeObj.x > ProductCompareImageObj.width) {
			imgSizeObj.x = ProductCompareImageObj.width;
			imgSizeObj.y = parseInt(ProductCompareImageObj.width*(imgSizeObj.y/imgSizeObj.x));
		}
		if(imgSizeObj.y > ProductCompareImageObj.height) {
			imgSizeObj.y = ProductCompareImageObj.width;
			imgSizeObj.x = parseInt(ProductCompareImageObj.height*(imgSizeObj.x/imgSizeObj.y));
		}
		return imgSizeObj
	}
	var currentThumbSize = productInfoEl.getElement('img').getSize();
	this.imageSizeObj = this.getImageSize(currentThumbSize);
	this.image.set('width', this.imageSizeObj.x);
	this.image.set('height', this.imageSizeObj.y);
	this.image.setStyles({
		left: parseInt((ProductCompareImageObj.width-this.imageSizeObj.x)/2) + 'px',
		top: parseInt((ProductCompareImageObj.height-this.imageSizeObj.y)/2) + 'px'
	});
	this.viewDetailsLink = productInfoEl.getElement('h3 a').clone().set('html', '<span>View details</span>').addClass('viewdetails');
	this.heading =	productInfoEl.getElement('h3').clone();
	this.getListItem = (function() {
		//Build the li element and return it
		var listItem = new Element ('li', {'class':'product'+this.productId});
		var summary = new Element('div', {'class':'summary'});
		var maintenance = new Element('div', {'class':'maintenance'})
		listItem.grab(this.imageContainer);
		listItem.grab(summary);
			summary.grab(this.heading);
			summary.grab(this.viewDetailsLink);
			summary.grab(maintenance);
				maintenance.grab(this.removeLink);
		return listItem;
	}).bind(this);
} 
window.addEvent('domready', function() {
	ProductCompareComparisonList = $('ProductComparisonPlugin').getElement('ul'); // Create a global variable for our UL
	ProductCompareComparisonList.renderStripes = function() {
		var row = 'oddrow';
		ProductCompareComparisonList.getElements('li').each(function(element, index) {
			if(element.hasClass('oddrow')) element.removeClass('oddrow');
			if(element.hasClass('evenrow')) element.removeClass('evenrow');
			element.addClass(row);
			row = (row != 'oddrow') ? 'oddrow' : 'evenrow';
		})
	}
	var comparisonListRemoveButtons = ProductCompareComparisonList.getElements('a.remove');
	if(comparisonListRemoveButtons) {
		comparisonListRemoveButtons.each(function(removeLink, index) {
			removeLink.addEvent('click', ProductCompareEventHandlers.addRemoveToggle);
		});
	}
	ProductCompareEventHandlers.initialiseProductCompareHandlers();
	ProductCompareEventHandlers.enableDisableProductCompareHandlers();
	if(typeof(ProductCategoryFilters) != "undefined") {
		ProductCategoryFilters.onInitProducts.push(ProductCompareEventHandlers.initialiseProductCompareHandlers, ProductCompareEventHandlers.enableDisableProductCompareHandlers);
	}
});
