/*
 * 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 = [null, null, null, null, null, null];
    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;
      }

      var buttonLabel = baseButtonLabel;
      if (count > 0) {
        buttonLabel += ' (' + count + ')';
      }

      jQuery('#clearComparedItemsButton').each(function() {
        jQuery(this)[0].disabled = (count < 1);
      });

      /*if (count > 0) {
        jQuery('#compareItems').show();
      }
      else {
        jQuery('#compareItems').hide();
      }*/
    };

    var reset = function(options) {
      products = [null, null, null, null, null, null];
      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 addProductIndex = function(options) {
      var addIndex = count;
      products[addIndex] = {id:options.id, category:options.category, boxId: options.boxId};
      count++;
      return addIndex;
    };

    var setProductImage = function(options) {
        var imgUrl = options.src; // libImageServer.ds "compareThumb"

        imgUrl = imgUrl.replace(/sw=\d+/,'sw=42');
        imgUrl = imgUrl.replace(/sh=\d+/,'sh=42');
        jQuery('#compareItemsProductLarge' + options.index).attr("src", imgUrl);
        jQuery('#compareItemsProductLarge' + options.index).attr("alt", options.alt);
        
        if(jQuery.browser.msie && jQuery.browser.version<7){
        	jQuery('#compareItemsProductLarge' + options.index).css("visibility", "visible");
        }
        
        imgUrl = options.src; // libImageServer.ds "compareSmall"
        imgUrl = imgUrl.replace(/sw=\d+/,'sw=20');
        imgUrl = imgUrl.replace(/sh=\d+/,'sh=20');
        jQuery('#compareItemsProduct' + options.index).attr("src", imgUrl);
        jQuery('#compareItemsProduct' + options.index).attr("alt", options.alt);
        
        if(jQuery.browser.msie && jQuery.browser.version<7){
        	jQuery('#compareItemsProduct' + options.index).css("visibility", "visible");
        }

        jQuery('#compareItemsClear' + options.index).show();
    }

    app.compare = {
      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 (count==0) {
        		alert("No products are selected!");
        		return false;
        	}
        	window.location.href = options.openUrl;
        });

        // 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();
        });

        var checked = jQuery('input:checkbox[checked]');

        // given a pid, find the corresponding checkbox id
        var findBoxId = function(pid) {
          for (var i = 0; i< checked.length; i++) {
            var data = jQuery(checked[i]).data("data");
            if (data != null && data.id === pid) {
              return data.boxId;
            }
          }
        }

        // 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 = addProductIndex({id:product.id, category:product.category, boxId: findBoxId(product.id)});
          setProductImage({index:addIndex, src:product.imgSrc, alt:product.imgAlt});
        }

        refresh();
      },

      addProduct: function(options){
        if (count >= 6) {
          if (!confirm(confirmationMessage)) {
            jQuery('#' + options.boxId).each(function() {
              jQuery(this)[0].checked = false;
            });
            return;
          }

          app.compare.removeProduct({index: 0});
        }

        var complete = function() {
          var addIndex = addProductIndex(options);

          jQuery(options.img).each(function() {
            var thumbnail = jQuery(this)[0];
            setProductImage({index:addIndex, src:thumbnail.src, alt:thumbnail.alt});
          });

          refresh();
        };

        var uncheck = function() {
        	jQuery('#' + options.boxId).attr("checked", false);
        };

        jQuery.ajax({
          type: 'POST',
          url: addUrl,
          data: {'pid':options.id, 'category':options.category},
          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];

            //remove comment productImage - jalvarez
            jQuery('#compareItemsProduct' + (i + 1)).each(function() {
              var thumbnail = jQuery(this)[0];
              jQuery('#compareItemsProduct' + i).each(function() {
                var productImage = jQuery(this)[0];
                productImage.src = thumbnail.src;
                productImage.alt = thumbnail.alt;
              });
            });
            
            //added compare items product large - jalvarez
            jQuery('#compareItemsProductLarge' + (i + 1)).each(function() {
                var thumbnail = jQuery(this)[0];
                jQuery('#compareItemsProductLarge' + i).each(function() {
                  var productImage = jQuery(this)[0];
                  productImage.src = thumbnail.src;
                  productImage.alt = thumbnail.alt;
                });
              });
          }

          var clearedIndex = count - 1;
          products[clearedIndex] = null;
          count--;

       	  jQuery('#' + clearedProduct.boxId).attr("checked", false);

          jQuery('#compareItemsProductLarge' + clearedIndex).attr("src", emptyImgSrc.replace('REPLACE_MEsm',clearedIndex+1));
          jQuery('#compareItemsProductLarge' + clearedIndex).attr("alt", emptyImgAlt);

          if(jQuery.browser.msie && jQuery.browser.version<7){
        	  jQuery('#compareItemsProductLarge' + options.index).css("visibility", "visible");
          }

          jQuery('#compareItemsProduct' + clearedIndex).attr("src", emptyImgSrc.replace('REPLACE_ME',clearedIndex+1));
          jQuery('#compareItemsProduct' + clearedIndex).attr("alt", emptyImgAlt);
            		
          if(jQuery.browser.msie && jQuery.browser.version<7){
        	  jQuery('#compareItemsProduct' + options.index).css("visibility", "visible");
          }

          jQuery('#compareItemsClear' + clearedIndex).hide();

          refresh();
        };

        var check = function() {
        	jQuery('#' + clearedProduct.boxId).attr("checked", true);
        };

        jQuery.ajax({
          type: 'POST',
          url: removeUrl,
          data: {'pid':clearedProduct.id, 'category':clearedProduct.category},
          dataType: 'json',
          async: false,
          success: function(data){
            if (data.success === true) {
              complete();
            } else {
              check();
            }
          },
          failure: function(data) {
            check();
          }
        });
      }
    }
  } else {
    // namespace has not been defined yet
    alert("app namespace is not loaded yet!");
  }
})(app);

