/*
 * All script logic for product comparison.
 *
 * The code relies on the jQuery JS library to be also loaded.
 *
 * The logic extends the JS namespace app.*
 */

(function(app){
	if (app) {
   		var products;
   		var count = 0;
		var emptyImgSrc = '';
		var emptyImgAlt = '';
		var baseButtonLabel = '';
		var confirmationMessage = '';
		var openUrl = '';
		var addUrl = '';
		var removeUrl = '';
		var suppressRefresh = false;

		var refresh = function() {
			if (suppressRefresh) {
				return;
			}
			
			// commenting out per request from design
	   		//var buttonLabel = baseButtonLabel;
	   		/*if (count > 0) {
	   			buttonLabel += ' (' + count + ')';
	   		}*/
	
	   		//var compareItemsButton = jQuery('#compareItemsButton');
	   		//compareItemsButton.html(buttonLabel);
	   		/*compareItemsButton.each(function() {
	   			jQuery(this)[0].disabled = (count < 2);
	   		});
	
	   		jQuery('#clearComparedItemsButton').each(function() {
	   			jQuery(this)[0].disabled = (count < 2);
	   		});
	   		*/
	   		/*if (count > 0) {
	   			jQuery('#compareItems').show();
	   		} 
	   		else {
	   			jQuery('#compareItems').hide();
	   		}*/
	   		
	   	};
	
		var reset = function(options) {
			products = new Array( app.compare.maxProductCompare );
			count = 0;
			emptyImgSrc = options.emptyImgSrc;
			emptyImgAlt = options.emptyImgAlt;
			baseButtonLabel = options.baseButtonLabel;
			confirmationMessage = options.confirmation;
			openUrl = options.openUrl;
			addUrl = options.addUrl;
			removeUrl = options.removeUrl;

			refresh();
		};

		var addProduct = function(options) {
	   		var addIndex = count;
			products[addIndex] = {id:options.id, category:options.category, varAttrValueID:options.varAttrValueID};
	   		count++;
	   		return addIndex;
		};
		/*
		var setProductImage = function(options) {
			jQuery('#compareItemsProduct' + options.index).each(function() {
		   		var productImage = jQuery(this)[0];
				productImage.src = options.src;
				productImage.alt = options.alt;
			});

	   		jQuery('#compareItemsClear' + options.index).show();
		};
		*/
		app.compare = {
			// the next two entries are default vaules, but they will be 
			// overwritten in the productCompareWidget.isml
			maxProductCompare: 6,
			// numberCompareColumns: -6,
			
			initialize: function(options) {
				reset(options);

				// Buttons to remove compared products individually	
				/*for (var i = 0; i < 6; i++) {
					// new Function() syntax ensures loop index is used correctly
					jQuery('#compareItemsClear' + i).click(new Function('app.compare.removeProduct({index: ' + i + '})'));
				}*/
	
				// Button to go to compare page
				jQuery('#compareItemsButton').click(function() {
					if ( !jQuery( this ).hasClass( 'disabled' ) )
						window.location.href = options.openUrl;
				});
				
				// set he initial state on the compare link
				// commenting out this logic, not needed, - do not initialize button class value just based on js count..   
				//if ( app.compare.getSelectedCount() == 0 )
				//{
				//	jQuery( '#compareItemsButton' ).addClass( "disabled" );
				//}

				// Button to clear all compared items
				jQuery('#clearComparedItemsButton').click(function() {
					suppressRefresh = true;

					//jQuery('#compareItems').hide();
					
					for (var i = count - 1; i >= 0; i--) {
						app.compare.removeProduct({index: i});
					}

					suppressRefresh = false;

					refresh();
				});
	
				// Check checkboxes for compared products on the current page 
				for (var i = 0; i < options.products.length; i++) {
					var product = options.products[i];
					var addIndex = addProduct({id:product.id, category:product.category, varAttrValueID:product.varAttrValueID});
					//setProductImage({index:addIndex, src:product.imgSrc, alt:product.imgAlt});
	
					jQuery('#compareCheck' + product.id).each(function() {
						jQuery(this)[0].checked = true;
					});
				}
	
				refresh();
			},
	
			addProduct: function(options){
		  		if (count >= app.compare.maxProductCompare) {
		  			if (!confirm(confirmationMessage)) {
		  				jQuery('#compareCheck' + options.id).each(function() {
		  					jQuery(this)[0].checked = false;
		  				});
		  				return;
		  			}
		
		  			app.compare.removeProduct({index: 0});
		  		}
		
		  		var complete = function() {
		  			var addIndex = addProduct(options);
		  			/*
		  			jQuery('#productThumbnail' + options.id).each(function() {
						var thumbnail = jQuery(this)[0];
						//setProductImage({index:addIndex, src:thumbnail.src, alt:thumbnail.alt});
		  			});
					*/
		  			// disable all checkboxes if we already reached he 
		  			// max of comparable products
					if ( app.compare.getSelectedCount() >= app.compare.maxProductCompare )
					{
						jQuery( 'input[type=checkbox]:[checked=false]' ).attr('disabled', true);
					}
					// if we have at least one item selected, enable the compare link
					// well, it should be always enabled here...
					if ( app.compare.getSelectedCount() > 0 )
					{
						jQuery( '#compareItemsButton' ).removeClass( "disabled" );
					}

			   		refresh();
		  		};
		
				var uncheck = function() {
	  				jQuery('#compareCheck' + options.id).each(function() {
	  					jQuery(this)[0].checked = false;
	  				});
				};
	
		   		jQuery.ajax({
					type: 'POST',
					url: addUrl,
					data: {'pid':options.id, 'category':options.category, 'varAttrID':options.varAttrValueID},
					dataType: 'json',
					success: function(data){
						if (data.success === true) {
							complete();
						}
						else {
							uncheck();
						}
					},
					failure: function(data) {
						uncheck();
					}
				});
			},
	
			removeProduct: function(options) {
				
				var index = null;
				if (options.index != null) {
					index = options.index;
				}
				else {
			   		for (var i = 0; i < count; i++) {
			   			if (products[i].id === options.id) {
			   				index = i;
			   			}
			   		}
				}
	
				var clearedProduct = products[index];
				
				var complete = function() {
			   		for (var i = index; i < count - 1; i++) {
			   			products[i] = products[i + 1];
			   		}
	
					var clearedIndex = count - 1;
			   		products[clearedIndex] = null;
			   		count--;
			
	  				jQuery('#compareCheck' + clearedProduct.id).each(function() {
	  					jQuery(this)[0].checked = false;
	  				});
	  				
	  				// Note: Mattha - added this to trigger the mouse out event so that deselected items get their hover state
	  				// removed (to fix the unselect all link)
	  				jQuery('#' + clearedProduct.id).each(function() {
	  					jQuery(this).trigger('mouseout');
	  				});
	  				
	  				jQuery('#compareItemsProduct' + clearedIndex).each(function() {
	  					var productImage = jQuery(this)[0];
				   		productImage.src = emptyImgSrc;
				   		productImage.alt = emptyImgAlt;
	  				});
	
			   		jQuery('#compareItemsClear' + clearedIndex).hide();
			
			   		// enable all checkboxes if we have less then the max selected
					if ( app.compare.getSelectedCount() < app.compare.maxProductCompare )
					{	
						jQuery( 'input[type=checkbox]' ).attr('disabled', false );
					}
					
					// if we there is no more items selected disable the buton
					if ( app.compare.getSelectedCount() == 0 )
					{
						jQuery( '#compareItemsButton' ).addClass( "disabled" );
					}

					refresh();
				};
	
				var check = function() {
	  				jQuery('#compareCheck' + clearedProduct.id).each(function() {
	  					jQuery(this)[0].checked = true;
	  				});
				};
							
		   		jQuery.ajax({
					type: 'POST',
					url: removeUrl,
					data: {'pid':clearedProduct.id, 'category':clearedProduct.category, 'varAttrID':clearedProduct.varAttrValueID},
					dataType: 'json',
					success: function(data){
						if (data.success === true) {
							complete();
						} else {
							
							check();
						}
					},
					failure: function(data) {
						
						check();
					}
				});
			},
			
			getSelectedCount: function() {
				return count;
			},
			
			getSelectedProductIDs: function() {
				var ret = {};
				for ( var i = 0; i < count; i++ )
				{
					ret[products[i].id] = products[i].category;
				}
				return ret;
			}
			
		}
	} else {
		// namespace has not been defined yet
		alert("app namespace is not loaded yet!");
	}
})(app);