var Shop = {
  _isRTW: null,
  _duration: 0.5,
  _lightboxes: {},
  _avails: {},
  _defaultAvail: 'unavailable',
  _sizeGuideOpen: false,
  _goingToBag: null,
  _iconText: null,
  currentSort: 'all',
  thumbs: [],
  FULL_PHOTO_UNAVAILABLE_URL: '/images/photo-unavailable-full.jpg',
  MINI_THUMB_PHOTO_UNAVAILABLE_URL: '/images/photo-unavailable-mini-thumb.jpg',
  THUMB_PHOTO_UNAVAILABLE_URL: '/images/photo-unavailable-thumb.jpg',
  THUMB_PHOTO_UNAVAILABLE_URL_3: '/images/photo-unavailable-thumb-3.jpg',
  THUMB_PHOTO_UNAVAILABLE_URL_4: '/images/photo-unavailable-thumb-4.jpg',
  THUMB_EMPTY: "/images/empty.gif", 
  SLIDER_RIGHT_BACKGROUND: 'url(/images/slider-right.png) center center no-repeat',
  SLIDER_LEFT_BACKGROUND: 'url(/images/slider-left.png) center center no-repeat',
  SLIDER_IDLE_BACKGROUND: 'url(/images/slider-idle.png) center center no-repeat',
  SLIDER_EMPTY_BACKGROUND: 'url(/images/viewall-empty.png) center center no-repeat',
  SLIDER_NON_SHOWING: '-----',
  DomIdToDisplayGroup: new Hash(),   // stores information about which displaygroup is in which dom id
  lightboxToActiveStyle: new Hash() // stores the active style to a lightbox
};

// effect queues
Shop.queue = {
  position:'end',
  scope:'shop'
};

Shop.queueLast = { 
  position:'with-last',
  scope:'shop'
};

Shop.isRTW = function() {
  if (Shop._isRTW === null) {
    if ($$('div.rtw').length > 0) {
      Shop._isRTW = true;
    } else {
      Shop._isRTW = false;
    }
  }
  return Shop._isRTW;
};
Shop.getLightboxObject = function(id) {
	return Shop._lightboxes[id];
};
Shop.initialize = function() {
  if (Shop.isRTW()) {
    return;
  }
  Shop.options =  Object.extend({
    thumbStyleFormat: /^[^_]+_[^_]+_(.*)$/,
    thumbnailWidth: 130
  }, arguments[0] || {});
  
  var lightboxes = $$('div.lightbox');
  lightboxes.each(function(lightbox, i){
  
  lightbox.isBusy = function () {
    return Shop.isBusy(lightbox);
  };  

	lightbox.writeAttribute('id', 'lightbox_' + i);

	lightbox.down('div.container').insert('<div class="product-details-border"></div>' +
      '<div class="product-image loading" id="lightbox_' + i + '_product_image"> </div>' +
      '<div class="details-wrapper" id="lightbox_' + i + '_details-wrapper"><div class="details" id="lightbox_' + i + '_details"> </div></div>' +
      '<div class="shopper-wrapper"><div class="shopper" id="lightbox_' + i + '_shopper"> </div></div>');

	Shop._lightboxes[lightbox.id] = {
      open: false,
      activeProduct: null,
	  variationPanel: null
    };
    Shop._lightboxes[lightbox.id].variationPanel = new GUCCI.VariationPanel(Shop, lightbox, Shop._lightboxes[lightbox.id], {
		DomIdToDisplayGroup: Shop.DomIdToDisplayGroup, 
		getDisplayGroupFromThumbId: Shop.getDisplayGroupFromThumbId,
		getThumbIdFromDisplayGroupId: Shop.getThumbIdFromDisplayGroupId
	});
  });
  
  var thumbnails = $$('div.lightbox div.products img');
  
  for (i = 0; i < thumbnails.length; i++) {
    var img = thumbnails[i];
    var thumbnail = img.up();
    var darkener = new Element('div', { className: 'darkening' }).setOpacity(0);
    var tooltip = new Element('div', { className: 'tooltip'}).update(Shop.SLIDER_NON_SHOWING).hide();
    
    thumbnail.addClassName('highlight');
    thumbnail.id = ['thumbnail_', i].join('');
    thumbnail.insert(darkener);
    thumbnail.insert(tooltip);
    // clean up
    darkener = null;
    thumbnail = null;
    img = null;
    tooltip = null;
  }
  
  var lastLightbox = lightboxes.last();
  var numberOfProducts = 0;
  var formats = ['format-2x3','format-2x2','format-1x3'];

  for (i = 0; i < formats.length; i++) {
    if (lastLightbox.hasClassName(formats[i])) {
      numberOfProducts = [6, 4, 3][i];
    }
  }

  (numberOfProducts - lastLightbox.select('div.thumbnail').length).times(function() {
    lastLightbox.down('div.products').insert('<div class="thumbnail"><img src="'+Shop.THUMB_EMPTY+'" alt="" /><div class="darkening empty-darkening"></div></div>');
  });
  lastLightbox.select('div.empty-darkening').invoke('setOpacity', 0);
  
  // save current mousepos for tooltips in variations drawer
  document.observe('mousemove', function(event) {
    Shop._currentMousePosX = event.clientX;
    Shop._currentMousePosY = event.clientY;
  });
  
  Shop.initializeThumbsFromProductList();
  Shop.initializeThumbsLoader();
  
  Shop.preloadImages();
  
  Shop.registerProductEvents();
};

Shop.preloadImages = function() {
  Loader.load('/images/slider-idle.png');
  Loader.load('/images/viewall-empty.png');
  Loader.load('/images/slider-left.png');
  Loader.load('/images/slider-right.png');
};

Shop.calcLayoutWidth = function() {
  // Formula: width of all lightboxes + width of all spacers + 2 menus
  var width = 0;
  
  // width of all lightboxes
  Object.keys(Shop._lightboxes).each(function(lightbox) {
    width += $(lightbox).getWidth();
  });
  
  // spacers
  width += (Object.keys(Shop._lightboxes).length) * 65;
  
  // menus
  width += 2 * 236;

  return width;
};

// recalculates the width of the layout components and sets their width
Shop.adjustLayoutWidth = function() {
  var width = Shop.calcLayoutWidth() + 'px';
  $('wrapper').setStyle({ width: width });
  $('layout').setStyle({ width: width });
};

Shop.insertVariationSliderForPanel = function(lightbox) {
  var lightboxObject = Shop._lightboxes[lightbox.id];
  
  if (lightboxObject.variationSlidersInserted) {
    return;
  }
  lightboxObject.variationSlidersInserted = true;

  var thumbnails = $(lightbox).select('div.products div.thumbnail');

  for (var i = 0; i < thumbnails.length; i++) {
    var tooltip = thumbnails[i].down('.tooltip');
    
    if (tooltip) {
      tooltip.observe('mousemove', Shop.handlers.variationSliderMouseMove.bindAsEventListener(this));
      
      // clean up
      tooltip = null;
    }
  }
};

Shop.registerProductEvents = function() {
  document.observe('click', function(event) {
   if (event.element().hasClassName('darkening') || Engine.isMSIE8) {
      var thumbnail = event.element().up();
      if (!thumbnail) return;
      if (!Engine.isMSIE8 || (thumbnail.hasClassName("thumbnail") && thumbnail.hasClassName("highlight")) || thumbnail.hasClassName("variants")) {
     	 var img = thumbnail.down('img');  // if no image available there is no img.
	      if (img && (/empty.gif$/.test(img.src))) return;
	      Shop.showProduct(thumbnail.down('img') || thumbnail.down('div.panel-thumb-unavailable'));
	  }
    }
      if (event.element().hasClassName('tooltip')) {
        Shop.handlers.variationSliderOnClick(event);
      }
  });

  document.observe('mouseout', function(event) {
    if (event.element().hasClassName('darkening')) {
      var relatedTarget = $(event.relatedTarget);
      if (relatedTarget && relatedTarget.hasClassName && relatedTarget.hasClassName('tooltip')) {
        return;
      }
      var darkening = event.element();
      if (darkening.getOpacity() > 0.001) {
        return;
      }
      Shop.hideTooltip(darkening.up().down('.tooltip'));
      // clean up
      darkening = null;
    }
    if (event.element().hasClassName('tooltip')) {
      var relatedTarget = $(event.relatedTarget);
      if(relatedTarget && relatedTarget.hasClassName('darkening')) {
          var darkening = event.element().up().down('div.darkening');
           if (darkening.getOpacity() > 0.001) {
             return;
           }
           Shop.hideTooltip(darkening.up().down('.tooltip'));
           // clean up
           darkening = null;
       }
    }
  });

  document.observe('mouseover', function(event) {
    if(event.element().hasClassName('darkening')) {
      var darkening = event.element();
      var tooltip = darkening.up().down('.tooltip');
      if (!tooltip) return;
      if (darkening.getOpacity() > 0.001) return;
      Shop.showTooltip(tooltip);
      if (Shop.helpers.displayGroupHasVariations(darkening.up())) {
        tooltip.setStyle({ background: Shop.SLIDER_IDLE_BACKGROUND });
        if (Engine.isMSIE6) Shop.redrawBackgroundAsPng(tooltip, '/images/slider-idle.png');
      }
      else {
        tooltip.setStyle({ background: Shop.SLIDER_EMPTY_BACKGROUND });
        if (Engine.isMSIE6) Shop.redrawBackgroundAsPng(tooltip, '/images/viewall-empty.png');
      }
    }
  });
};

Shop.handlers = {
  variationSliderMouseMove: function(event) {
    if (!Shop.helpers.displayGroupHasVariations(event.element().up('.thumbnail'))) return;
    
    var x = event.layerX || event.offsetX;
    if (x >= 0 && x < 15) {
      event.element().setStyle({ background: Shop.SLIDER_LEFT_BACKGROUND });
      if (Engine.isMSIE6) Shop.redrawBackgroundAsPng(event.element(), '/images/slider-left.png');
    }
    if (x >= 15 && x < 80) {
      event.element().setStyle({ background: Shop.SLIDER_IDLE_BACKGROUND });
      if (Engine.isMSIE6) Shop.redrawBackgroundAsPng(event.element(), '/images/slider-idle.png');
    }
    if (x >= 80 && x <= 95) {
      event.element().setStyle({ background: Shop.SLIDER_RIGHT_BACKGROUND });
      if (Engine.isMSIE6) Shop.redrawBackgroundAsPng(event.element(), '/images/slider-right.png');
    }
  },

  variationSliderOnClick: function(event) {
    event.stop();
    var thumbnail = event.element().up('.thumbnail');
    var x = event.layerX || event.offsetX;
    
    if (Shop.helpers.displayGroupHasVariations(thumbnail)) {
      if (x >= 0 && x < 15) {
        Shop.switchThumbnail(thumbnail, -1);
      }
      if (x >= 15 && x < 80) {
        Shop.showProduct(thumbnail.down('img') || thumbnail.down('div.panel-thumb-unavailable'));
      }
      if (x >= 80 && x <= 95) {
        Shop.switchThumbnail(thumbnail, 1);
      }  
    }
    else {
      if (x >= 0 && x < 95) {
        Shop.showProduct(thumbnail.down('img') || thumbnail.down('div.panel-thumb-unavailable'));
      }
    }
  }
};

Shop.helpers = {
  displayGroupHasVariations: function(thumbnail) {
    var displayGroupInfo = Shop.DomIdToDisplayGroup.get(thumbnail.id);
    if (!displayGroupInfo) {
      return;
    }
    var displayGroup = gucci.DataHelper.getPanelDisplayGroup(displayGroupInfo.displayGroup_id);
    
    return (displayGroup.getAllThumbUrls().length != 1);
  }
};

Shop.changeActiveStyleForSendToAFriend = function() {
	if ($("send_to_a_friend")) {
	sendToFriend = $("send_to_a_friend");
	var selected_product = Shop.lightboxToActiveStyle.get(sendToFriend.up("div.lightbox").id);
	var selectedDisplayGroup = gucci.DataHelper.getPanelDisplayGroupByStyleNumber(selected_product);
	$("send_to_a_friend_style_number").setAttribute("value", selected_product);	
	$("send_to_a_friend_link_id").setAttribute("value", selectedDisplayGroup.link_id);
}
};

Shop.showSendToAFriend = function(displayGroup_id, trigger) {
  var dg = gucci.DataHelper.getPanelDisplayGroup(displayGroup_id);
  var current_lightbox = $(trigger).up('div.lightbox');
  var selected_product = Shop.lightboxToActiveStyle.get($(trigger).up('div.lightbox').id);
if ($("send_to_a_friend")) {
	if ($("send_to_a_friend").visible()) {
		if ($("send_to_a_friend").up('div.lightbox').id != current_lightbox.id) {
		new Effect.Fade($("send_to_a_friend"), {duration: 0.4, afterFinish: function() {
		current_lightbox.insert({bottom: $("send_to_a_friend")});
		Shop.changeActiveStyleForSendToAFriend();
		$("send_response").hide();
			$("send_to_a_friend").setStyle({
				left: 520 +'px',
				opacity: 1
			});
			$("send_to_a_friend_form").hide();
				new Effect.Parallel([
					new Effect.Appear($("send_to_a_friend"),{duration: 0.4, sync: true}),
					new Effect.Move("send_to_a_friend",{x: 0, y: 0, mode: 'absolute', sync: true}),
					new Effect.Appear($("send_to_a_friend_form"),{duration: 0.4, delay: 0.4})
				], {duration: 1});
		}});
	}
	} else {
		current_lightbox.insert({bottom: $("send_to_a_friend")});
		Shop.changeActiveStyleForSendToAFriend();
		$("send_to_a_friend").setStyle({
			left: 520 +'px',
			opacity:1
		});	
		new Effect.Parallel([
			new Effect.Appear($("send_to_a_friend"),{duration: 0.4, sync: true}),
			new Effect.Move("send_to_a_friend",{x: 0, y: 0, mode: 'absolute', sync: true}),
			new Effect.Appear($("send_to_a_friend_form"),{duration: 0.4, delay: 0.4})
		], {duration: 1});
	}
} else {
	var selectedDisplayGroup = gucci.DataHelper.getPanelDisplayGroupByStyleNumber(selected_product);
new Ajax.Request('/send_to_a_friend_form.asp?style_number='+selected_product+'&display_group_id='+selectedDisplayGroup.link_id,{ method: 'get',
	onSuccess: function(transport){
		current_lightbox.insert({ bottom: transport.responseText});
		$("send_to_a_friend").setStyle({
			left: 520 +'px',
			opacity:1
		});	
		new Effect.Parallel([
			new Effect.Appear($("send_to_a_friend"),{duration: 0.4, sync: true}),
			new Effect.Move("send_to_a_friend",{x: 0, y: 0, mode: 'absolute', sync: true}),
			new Effect.Appear($("send_to_a_friend_form"),{duration: 0.4, delay: 0.4})
		], {duration: 1});
	},
	onFailure: function(transport){
		console.log("FAILED TO LOAD SEND TO A FRIEND FORM");
	}});
}
return;
};

Shop.hideSendToAFriend = function(quickHide) {
	var quickHide = (quickHide == 'undefined' || quickHide==null) ? false : quickHide;
	if ($("send_to_a_friend") && $("send_to_a_friend").visible()) {
		if (quickHide) {
			new Effect.Fade($("send_to_a_friend"), {afterFinish: function() {$("send_response").hide();}});
		} else {
			new Effect.Parallel([
				new Effect.Fade($("send_to_a_friend_form"), {sync: true}),
			new Effect.Move($("send_to_a_friend"), {x: 520, y: 0, sync: true}),
			new Effect.Fade($("send_to_a_friend"), {sync: true, delay: 0.4, afterFinish: function() {$("send_response").hide();}})
			], {duration: 1, queue: 'front'});
		}
}
};

Shop.tellAnotherFriend = function() {
	$("send_response").hide();
	$("send_to_a_friend_form").show();
};

Shop.toggleSendToAFriendBusyButton = function(link) {
	$(link).up(".bottom").down(".cancel.button").toggle();
	if ($(link).up(".bottom").down(".submit.button").hasClassName('busy')) {
	$(link).up(".bottom").down(".submit.button").removeClassName('busy');	
	} else {
	$(link).up(".bottom").down(".submit.button").addClassName('busy');	
	}
};

Shop.sendToAFriend = function(link) {
	Shop.toggleSendToAFriendBusyButton(link);
	form_elements = $("send_to_a_friend_form").getInputs();
	$("send_to_a_friend_form").down("p.error").hide();
	form_elements.each(function(ele) {
		if (ele.hasClassName('validate')) {
		$$("#send_to_a_friend_form label[for="+ele.id+"]")[0].removeClassName("error");
		}
	});
	var missing = [];
	form_elements.each(function(ele) {
	if (ele.hasClassName('validate') && !ele.present())
	missing.push(ele);
	});
	missing.each(function(ele) {
	$$("#send_to_a_friend_form label[for="+ele.id+"]")[0].addClassName("error");
	});
	if (missing.length > 0) {
	$("send_to_a_friend_form").down("p.error").show();
	Shop.toggleSendToAFriendBusyButton(link);
	} else {
		new Ajax.Request('/send_to_a_friend.asp', {asynchronous:true, evalScripts:true, parameters:Form.serialize($("send_to_a_friend_form")), onSuccess: function() {Shop.toggleSendToAFriendBusyButton(link);}, onFailure: function() {Shop.toggleSendToAFriendBusyButton(link);}}); return false;	
	}
};

Shop.redrawBackgroundAsPng = function(element, background) {
  element = $(element);
  element.setStyle({ background: 'none' });
  element.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + background + "',sizingMethod='crop')";
};

Shop.updateVariationSlidersForPanel = function(lightbox) {
  var lightboxObject = Shop._lightboxes[lightbox.id];
  if (lightboxObject.variationSlidersUpdated) {
    return;
  }
  lightboxObject.variationSlidersUpdated = true;
  
  var tooltips = lightbox.select('div.products div.thumbnail div.tooltip');
    
  lightboxObject.variationSlidersUpdated = true;
  
  for (var i = 0; i < tooltips.length; i++) {
    var tooltip = tooltips[i];
    var displayGroupInfo = Shop.DomIdToDisplayGroup.get(tooltip.up('div.thumbnail').id);
    
    if(!displayGroupInfo) {
	  tooltip.update(Shop.SLIDER_NON_SHOWING);	
      return;
    }
    
    var displayGroup = gucci.DataHelper.getPanelDisplayGroup(displayGroupInfo.displayGroup_id);
    
    if (displayGroup.getAllThumbUrls().length == 1) {
      tooltip.update(Gucci.getTerm('variation slider label one variation'));
    } else {
      tooltip.update(
        new Template(Gucci.getTerm('variation slider label')).evaluate({
          n: displayGroup.variations.length
        })
      );
    }
  }
};

Shop.updateVariationSliders = function() {
  var tooltips = $$('div.lightbox div.products div.thumbnail div.tooltip');
  for (var i = 0; i < tooltips.length; i++) {
    var tooltip = tooltips[i];
    var displayGroupInfo = Shop.DomIdToDisplayGroup.get(tooltip.up('div.thumbnail').id);
    if (!displayGroupInfo) {
	  tooltip.update(Shop.SLIDER_NON_SHOWING);
      return;
    }
    //link_id = displayGroupInfo.link_id;
    var displayGroup = gucci.DataHelper.getPanelDisplayGroup(displayGroupInfo.displayGroup_id);

    if (displayGroup.getAllThumbUrls().length == 1) {
      tooltip.update(Gucci.getTerm('variation slider label one variation'));
    } else {
      tooltip.update(
        new Template(Gucci.getTerm('variation slider label')).evaluate({
          n: displayGroup.variations.length
        })
      );
    }
  }
};

Shop.activateVariationSlider = function(thumbContainer) {
  var displayGroupInfo = Shop.DomIdToDisplayGroup.get(thumbContainer.id);
  displayGroupInfo.variationSliderBusy = false;
};

Shop.deactivateVariationSlider = function(thumbContainer) {
  var displayGroupInfo = Shop.DomIdToDisplayGroup.get(thumbContainer.id);
  displayGroupInfo.variationSliderBusy = true;
};

Shop.switchThumbnail = function(thumbContainer, switchCount) {
  var displayGroupInfo = Shop.DomIdToDisplayGroup.get(thumbContainer.id);
  
  // check if there is already some sliding going on
  if (displayGroupInfo.variationSliderBusy) {
    return;
  }
  // set it to busy, to prevent other actions
  Shop.deactivateVariationSlider(thumbContainer);
      
  var displayGroup = gucci.DataHelper.getPanelDisplayGroup(displayGroupInfo.displayGroup_id);
  
  //var nextThumbIndex = (displayGroupInfo.currentThumbIndex == displayGroup.variations.length-1) ? 0 : (displayGroupInfo.currentThumbIndex + 1);
  var newIndex = displayGroupInfo.currentThumbIndex + switchCount;
  
  if (newIndex < 0) {
    newIndex += displayGroup.variations.length;
  } else if (newIndex > displayGroup.variations.length-1) {
    newIndex -= displayGroup.variations.length;
  }
  
  //var nextThumbSrc = displayGroup.getAllThumbUrls()[nextThumbIndex];
  var newThumbSrc = displayGroup.getAllThumbUrls()[newIndex];
  
  var newThumb;
  var oldThumb = thumbContainer.down('div.panel-thumb-unavailable') || thumbContainer.down('img');
  var newThumbPrefix = switchCount < 0 ? '-' : '';
  
  if(!newThumbSrc || newThumbSrc === '') {
    newThumb = new Element('div', {
      className: 'panel-thumb-unavailable'
    }).setStyle({
      background: 'url(' + Shop.photoUnavailableThumbUrlForLightbox(thumbContainer.up('div.lightbox')) + ')',
      position: 'absolute',
      left: newThumbPrefix + thumbContainer.getStyle('width')
    }).update(Gucci.getTerm('photo unavailable'));
  } else {
    newThumb = new Element('img', {
      src: newThumbSrc
    }).setStyle({
      position: 'absolute',
      left: newThumbPrefix + thumbContainer.getStyle('width')
    });
  }
  
  thumbContainer.insert({top:newThumb});
  thumbContainer.down('.tooltip').update((newIndex+1)+'/'+displayGroup.getAllThumbUrls().length);
  
  displayGroupInfo.currentThumbIndex = newIndex;
  displayGroupInfo.currentStyle = displayGroup.getStyleNumbersWithLeadStyleFirst()[newIndex];
  
  setTimeout(function() {
    var effectPrefix = switchCount > 0 ? '-' : '';
    new Effect.Parallel([
      new Effect.Morph(oldThumb, { style: { left: effectPrefix+thumbContainer.getStyle('width') } }),
      new Effect.Morph(newThumb, { style: { left: '0px' } })
    ], {
      transition: Gucci.cubic,
      afterFinish: function() {
        oldThumb.remove();
        Shop.activateVariationSlider(thumbContainer);
      }
    });
  }, 3);
};

Shop.changeThumbnail = function(thumbContainer, variation) {
  var displayGroupInfo = Shop.DomIdToDisplayGroup.get(thumbContainer.id);
  var displayGroup = gucci.DataHelper.getPanelDisplayGroup(displayGroupInfo.displayGroup_id);
  if (!variation)
    variation=displayGroup.getProduct(displayGroupInfo.currentStyle);
  var thumbSrc = variation.images.panel_thumb;
  var oldThumb = thumbContainer.down('div.panel-thumb-unavailable') || thumbContainer.down('img');
  var newThumb;
  if (!thumbSrc || thumbSrc == '') {
    newThumb = new Element('div', {
      className: 'panel-thumb-unavailable'
    }).setStyle({
      background: 'url('+ Shop.photoUnavailableThumbUrlForLightbox(thumbContainer.up('div.lightbox')) +')',
      position: 'absolute',
      left: thumbContainer.getStyle('width')
    }).update(Gucci.getTerm('photo unavailable'));
  } else {
    newThumb = new Element('img',{
      src: thumbSrc
    }).setStyle({
      position: 'absolute',
      left: thumbContainer.getStyle('width')
    });
  }
  
  var thumbIndex;
  var thumbUrls = displayGroup.getAllThumbUrls();
  for (var i = 0; i < thumbUrls.length; i++) {
    if (thumbUrls[i] == thumbSrc) {
      thumbIndex = i;
      break;
    }
  }
  oldThumb.remove();
  thumbContainer.insert({ top: newThumb });
  if (!Engine.isMSIE8)
  	thumbContainer.down('.tooltip').update((thumbIndex+1)+'/'+thumbUrls.length);
  
  displayGroupInfo.currentThumbIndex = thumbIndex;
  displayGroupInfo.currentStyle = displayGroup.getStyleNumbersWithLeadStyleFirst()[thumbIndex];
  return newThumb;
};

Shop.photoUnavailableThumbUrlForLightbox = function(lightbox) {
  if (lightbox.hasClassName('format-2x2')) {
    return Shop.THUMB_PHOTO_UNAVAILABLE_URL_4;
  } else if (lightbox.hasClassName('format-1x3')) {
    return Shop.THUMB_PHOTO_UNAVAILABLE_URL_3;
  } else {
    return Shop.THUMB_PHOTO_UNAVAILABLE_URL;
  }
};

Shop.showTooltip = function(tooltip) {
  if (!tooltip) {
    return;
  }
  if (tooltip._timeout) {
    clearTimeout(tooltip._timeout);
    tooltip._timeout = null;
  }
  if (tooltip.visible()) {
    return;
  }
  var thumb = tooltip.parentNode.down('img') || tooltip.parentNode.down('div.panel-thumb-unavailable');
  
  if (thumb.offsetLeft > 0) {
    return;
  }
  if (tooltip.innerHTML!='' && !tooltip._timeout && tooltip.innerHTML!=Shop.SLIDER_NON_SHOWING) {
    tooltip._timeout = setTimeout(function(){ 
      tooltip.show();
    }, 300);
  }
};

Shop.hideTooltip = function(tooltip){
  if (!tooltip) {
    return;
  }
  if (tooltip._timeout) {
    clearTimeout(tooltip._timeout);
    tooltip._timeout = null;
  }
  tooltip._timeout = setTimeout(function(){
    tooltip.hide();
  }, 50);
};

Shop.initializeCatalog = function(){
  this.isCatalog = true;

  Gucci.Zoomer.expand = false;

  Shop.options =  Object.extend({
    thumbStyleFormat: /^[^_]+_[^_]+_(.*)$/,
    thumbnailWidth: 130
  }, arguments[0] || {});

  $$('div.lightbox').each( function(lightbox, i) {
    lightbox.setAttribute('id', 'lightbox_' + i);
    lightbox.down('div.container').insert('<div class="product-image loading" id="lightbox_' + i + '_product_image"> </div>' +
      '<div class="details-wrapper"><div class="details" id="lightbox_' + i + '_details"> </div></div>' +
      '<div class="styles-wrapper"><div class="styles" id="lightbox_' + i + '_styles"> </div></div>' +
      '<div class="shopper-wrapper"><div class="shopper" id="lightbox_' + i + '_shopper"> </div></div>');
    Shop._lightboxes[lightbox.id] = {
      open: false,
      activeProduct: null
    };
  });
};

Shop.setStyles = function(lightbox, styles) {
  lightbox = $(lightbox);
  Shop._lightboxes[lightbox.id].styles = styles;
};

Shop.getStyles = function(lightbox) {
  lightbox = $(lightbox);
  return Shop._lightboxes[lightbox.id].styles;
};

Shop.getStyle = function(lightbox, style) {
  return this.getStyles(lightbox).detect(function(s) {
    return s.style == style;
  });
};

Shop.setAvailability = function(style, availability) {
  Shop._avails[style] = availability;
};

Shop.getAvailability = function(style) {
  return Shop._avails[style];
};

Shop.printStyle = function(displayGroup_id, trigger) {
  Shop.printItems = gucci.DataHelper.getPanelDisplayGroup(displayGroup_id);
  Shop.print_selected_product = Shop.lightboxToActiveStyle.get($(trigger).up('div.lightbox').id);
  var url = "/" + Cookie.get('site') + "/templates/print.html";
  if (Shop.printItems.variations.size() < 8)
  	Shop.printWindow = window.open(url,'printStyle', 'height=520,width=820,location=no,menubar=no,resizable=yes');
  else if (Shop.printItems.variations.size() < 14)
	Shop.printWindow = window.open(url,'printStyle', 'height=700,width=820,location=no,menubar=no,scrollbars=yes,resizable=yes');
  else
	Shop.printWindow = window.open(url,'printStyle', 'height=900,width=820,location=no,menubar=no,scrollbars=yes,resizable=yes');
   
};

Shop.printCallback = function() {
  var w = this.printWindow;
  var selectedProduct = this.printItems.leadStyle;
  var variations = this.printItems.variations;

  // determine chosen variation
  for (var i = 0; i < variations.length; i++) {
	if (variations[i].style_number == this.print_selected_product) {
		selectedProduct = variations[i];
		break;
	}
  }

  // layout main print info
  var d = w.document.getElementById("mainDescription");
  d.innerHTML = selectedProduct.text.grpdesc;
  d = w.document.getElementById("productShot");
  d.src = selectedProduct.images.full;


  // layout variations, selected item
  var placeindex = 1;
  for (var i = 0; i < variations.length; i++) {
	var currplaceindex;
	if (variations[i].style_number == this.print_selected_product)
		currplaceindex = 0;
	else {
		currplaceindex = placeindex;
		placeindex++;
	}
		
    d = w.document.getElementById("variationDescription"+currplaceindex);
    d.innerHTML = variations[i].text.vardesc;
    d = w.document.getElementById("style"+currplaceindex);
    d.innerHTML = variations[i].style_number;
    d = w.document.getElementById("price"+currplaceindex);
    var p = variations[i].priceNum;
    if (p) {
      d.innerHTML = new Template(Gucci.getTerm('price-template')).evaluate({price:p});
    } else {
      d.innerHTML = "";
    }
    d = w.document.getElementById("group"+currplaceindex);
    d.style.display = "block";
	if (currplaceindex > 0 && currplaceindex % 2 == 0) {
		d = w.document.getElementById("break"+currplaceindex);
		d.style.display = "block";
	}
  }
};


Shop.getPossiblyAvailableShopper = function() {

	var possiblyAvailableShopper = true;
	var siteData =  siteStuff.getSiteData(siteStuff.getSiteFromCookie());
	if(siteData) {
		possiblyAvailableShopper = siteData.possiblyAvailableShopper;
	}

	return(possiblyAvailableShopper);
};

Shop.checkScrolling = function(detailcontainer) {	
  if (typeof detailcontainer != 'object') return;
  var vardesc = detailcontainer.down('div.description-variation');
  if (typeof vardesc != 'undefined') {
  	var scrollheight = vardesc.down('div.scrollbar').getHeight();
	  if (vardesc.getHeight()-10 > scrollheight) {
		vardesc.setStyle({height: scrollheight + 'px'});
		Gucci.scrollPanel(
			vardesc,
		  	vardesc.down('div.handle'),
		  	vardesc.down('div.scrollbar'),
		  	vardesc.getHeight()
		);
	  }
  }
};

Shop.selectStyle = function(thumbImg, style_number, options) {
  options = options || {};
  var thumbId = options.thumbId || thumbImg.up('div').id;
  var lightbox = options.lightbox || thumbImg.up('div.lightbox');
  
  var displayGroup = Shop.getDisplayGroupFromThumbId(thumbId);
  var displayGroupInfo = Shop.DomIdToDisplayGroup.get(thumbId);
  var product = displayGroup.getProduct(style_number);
  //gucci.DataHelper.getPanelProduct(displayGroup.id, style_number);

  var oldDetails = $('details_' + lightbox.id + '_' + Shop.lightboxToActiveStyle.get(lightbox.id));
  if (oldDetails) {
    oldDetails.hide();
  }
  var newDetails = $('details_'+lightbox.id+'_'+style_number).show();

  // add scrollbar if needed
  Shop.checkScrolling(newDetails);
  
  Shop.lightboxToActiveStyle.set(lightbox.id, style_number);
  var initialSkuWasSet = false;
  
  if (product.skus) {
    if (product.skus.length > 1) {
      
      var dropdown = newDetails.down('select.size-select');

	  for(var j=1; j < dropdown.options.length; j++){
      	var size = dropdown.options[j].value;

		var availtemp = product.skus[j-1].status;
       	if(!availtemp || availtemp=="" || availtemp=="unavailable") {
        	Shop.disableOption(dropdown, j);
        }
       	else {
       		if(availtemp=="possibly unavailable") {
				if(Shop.getPossiblyAvailableShopper()) {
					Shop.enableOption(dropdown, j);
				}
				else {
					Shop.disableOption(dropdown, j);
				}			
			}
       		else {
          		Shop.enableOption(dropdown, j);
          	}
        }
      }
      if (displayGroupInfo.initialSku) {
        setTimeout(function() {
          dropdown.value = displayGroupInfo.initialSku;
          Shop.selectSize(dropdown);
          displayGroupInfo.initialSku = null;
          initialSkuWasSet = true;
        }, 5);
      } else {
        dropdown.selectedIndex = 0;  
      }
      if (oldDetails) {
        this.hideAvailabilityInformation(lightbox);
      }
    } else {
      var sku = product.skus.first();
      if (sku) {
        this.updateAvailabilityInformationBySku(lightbox, displayGroup.displayGroup_id, sku.sku);
      }
      // capture availability status for cm, only record non sized items
      var availstatus;
      var availability = sku;
      
      if(!availability) {
        availability = Shop.getDefaultAvailability();
      }
      availstatus = availability.status.replace(/\s/g,'_');
      
	  if (typeof CmCustom != 'undefined') {
		(function() { 
			CmCustom.productView(style_number);
		}).defer();
	  }     
    }
  }
    
  this.updateZoomerWithImages(lightbox, product.images);
  
  if (!initialSkuWasSet) {
    Gucci.setPageFragmentIdentifier({
      panelId: 0, //FIXME: need panel id from data
      displayGroupId: displayGroupInfo.displayGroup_id,
      styleNumber: style_number
    });
  } 
  Shop.changeActiveStyleForSendToAFriend();
  
  if (!product.skus || product.skus.length > 1) { 
	if (typeof CmCustom != 'undefined') {
		(function() { 
			CmCustom.productView(style_number);
		}).defer();
	}
  }
 	
};

Shop.selectSize = function(element) {
  if($(element.selectedIndex)==0 || (element.options[$(element.selectedIndex)].disabled && (!Engine.isKHTML || Engine.isWebKit3))) {
    element.selectedIndex = element.oldSelectedIndex;
    return;
  }
  
  var lightbox = $(element).up('div.lightbox');
  var displayGroup = Shop.DomIdToDisplayGroup.get(lightbox.activeThumbnail.id);
  element.oldSelectedIndex = element.selectedIndex;
  Shop.updateAvailabilityInformationBySku(lightbox, displayGroup.displayGroup_id, $F(element));
  if(element.value != null && element.value != "") {
    Gucci.setPageFragmentIdentifier({
      panelId: 0,
      displayGroupId: displayGroup.displayGroup_id,
      styleNumber: displayGroup.currentStyle,
      sku: element.value
    });
  }
  var availstatus;
  
  var activeStyle = Shop.lightboxToActiveStyle.get(lightbox.id);
  var displayGroupTemp = gucci.DataHelper.getPanelDisplayGroup(displayGroup.displayGroup_id);
  var availability = displayGroupTemp.getProduct(activeStyle).getSku($F(element));
  if (!availability) {
    availability = Shop.getDefaultAvailability();
  }
  availstatus = availability.status.replace(/\s/g,'_');
  
  var buttons = $$('div.button');
  for (var i = 0; i < buttons.length; i++) {
    buttons[i].setStyle('height: 24px;');
  }
};

Shop.getSize = function(lightbox, style){
  var select = lightbox.down('div#details_' + lightbox.id + '_' +style+' select.size-select');
  if (!select) {
    return null;
  }
  return $H({
    sku: $F(select),
    size: select.options[select.selectedIndex].text
  });
};

Shop.getSkuFromSelectedSize = function(lightbox, style){
  var select = lightbox.down('div#details_'+lightbox.id + '_'+style+' select.size-select');
  if (!select) {
    return null;
  }
  return $H({
    sku: $F(select),
    size: select.options[select.selectedIndex].value
  });
};

Shop.setDefaultAvail = function(d){
  Shop._defaultAvail = d;
};

Shop.getDefaultAvailability = function() {
  var availability = {};
  availability.status = Shop._defaultAvail;
  availability.info   = Gucci.getTerm(Shop._defaultAvail);
  return availability;
};

Shop.updateAvailabilityInformationBySku = function(lightbox, displayGroup_id, sku) {
  var activeStyle = Shop.lightboxToActiveStyle.get(lightbox.id);
  //var availability = gucci.DataHelper.getSku(link_id, activeStyle, sku);
  var displayGroup = gucci.DataHelper.getPanelDisplayGroup(displayGroup_id);
  var availability = displayGroup.getProduct(activeStyle).getSku(sku);
  
  if(!availability) {
    availability = Shop.getDefaultAvailability();
  }
  Shop.updateAvailabilityInformation(lightbox, availability);
};

Shop.updateAvailabilityInformation = function(lightbox, avail) {
  var addtobag  = false;
  var backorder = false;
  var shopper   = true;

  switch (avail.status) {
    case 'available':
      addtobag = true;
      break;
    
    case 'available soon':
      addtobag = true;
      break;
    
    case 'backorder':
      backorder = true;
      break;
    
    case 'in transit':
      addtobag = true;
      break;
    
    case 'in transit soon':
      addtobag = true;
      break;
    
    case 'warehouse transfer':
      addtobag = true;
      break;
    
    case 'store transfer':
	  addtobag = true;
      break;
      
    case 'possibly available':
	  shopper = Shop.getPossiblyAvailableShopper();
      break;
    
    case 'jewelry possibly available':
      break;
    
    case 'unavailable':
      shopper = false;
      break;
    
    case 'no threshold':
      shopper = false;
      break;
    
    case 'unknown sku':
      shopper = false;
  }

  if (typeof salenav!="undefined" && salenav)
	shopper = false;

  var c = lightbox.down('div#details_' +lightbox.id+'_'+ Shop.lightboxToActiveStyle.get(lightbox.id) +' div.configuration-info');
  c.down('p.availability').update(avail.info);
  c.down('div.checkout').removeClassName('busy').hide();
  c.down('div.addtobag')[ addtobag ? 'show' : 'hide']().removeClassName('busy').down('div.content').update(Gucci.getTerm('add to bag'));
  c.down('div.backorder')[ backorder ? 'show' : 'hide']().removeClassName('busy').down('div.content').update(Gucci.getTerm('register for wait list'));
  c.down('p.info')[ shopper ? 'show' : 'hide']().update(Shop.buildPersonalShopperTerm());
};

Shop.buildPersonalShopperTerm = function() {
  var text = new Template(Gucci.getTerm('personal shopper text'));
  return text.evaluate({link: '<a onclick="Shop.showShopper(this); return false" href="#">'+Gucci.getTerm('personal shopper link text')+'</a>'});
};

Shop.hideAvailabilityInformation = function(lightbox) {
  var c = lightbox.down('div#details_' +lightbox.id+'_'+ Shop.lightboxToActiveStyle.get(lightbox.id) +' div.configuration-info');
  if (!c) {
    return;
  }
  c.down('p.availability').update();
  c.down('div.checkout').removeClassName('busy').hide();
  c.down('div.addtobag').removeClassName('busy').hide();
  c.down('div.backorder').removeClassName('busy').hide();
  c.down('p.info').hide();
};

Shop.getProductInfo = function(thumbnail) {
  return Shop.thumbs[thumbnail.id.split('_')[1]];
};

Shop.isOpen = function(lightbox) {
  return Shop._lightboxes[$(lightbox).id].open;
};

Shop.isActive = function(product) {
  return (product && product == Shop._lightboxes[$(product).up('div.lightbox').id].activeProduct);
};

Shop.updateZoomerWithImages = function(lightbox, images) {
	var fullUrl = images.full;
	var zoomUrl = images.zoom;
	var delay = 0;

	var productImage = $(lightbox.id + '_product_image');
	productImage.addClassName('loading');

	var lightboxObject = Shop._lightboxes[lightbox.id];
	if(!lightboxObject.zoomer){
		this.updateZoomer(lightbox, fullUrl, zoomUrl, images);
		return;
	}
	if (lightboxObject.zoomer && lightboxObject.zoomer._zoomed) {
		lightboxObject.zoomer.zoomOutAndDestroy();
		delay = Gucci.Zoomer.ZOOM_OUT_SPEED + 0.01;
	} else if (lightboxObject.zoomer) {
		lightboxObject.zoomer.destroy();
	}
	// If rotator instance exist, destroy it
	if (lightboxObject.rotator) lightboxObject.rotator.destroy();

  // TODO add/remove image unavailable notice in the right time
  new Effect.Opacity(lightbox.id+'_full_image', {
    delay: delay,
    from: 1,
    to: 0,
    transition: Gucci.cubic,
    afterFinish: function() {		
      var availstatus = '';
      var activeStyle = Shop.lightboxToActiveStyle.get(lightbox.id);
      if (activeStyle != null) {
        var thumb = lightbox.activeThumbnail;
        var displayGroup = Shop.getDisplayGroupFromThumbId(thumb.id);
        
        var producttemp = displayGroup.getProduct(activeStyle);
        var pricetemp = producttemp.price;
        var skutemp = (producttemp.skus.length > 1) ? producttemp.getSku(Shop.getSkuFromSelectedSize(lightbox, activeStyle).get('sku')) : producttemp.skus[0];
        
        if (!skutemp) {
          availstatus = '';
        } else {
          availstatus = '/' + skutemp.status.replace(/\s/g,'_');
        }
      }
      productImage.update();
      if (!zoomUrl) { //TODO: check if unavailable
        Loader.cacheOrLoad(fullUrl, {
          onComplete: function() {
            var fullProductImage = (fullUrl == '' || !fullUrl) ? Shop.FULL_PHOTO_UNAVAILABLE_URL : fullUrl;
            var imageTag = '<img id="'+lightbox.id+'_full_image" src="'+fullProductImage
                           + '" alt="" style="opacity:0;filter:alpha(opacity=0)" />';
            productImage.update(imageTag);
            new Effect.Opacity($(lightbox.id + '_full_image'), {
              from: 0,
              to: 1 ,
              transition: Gucci.cubic,
              afterFinish: function() {
                if(fullUrl == '' || !fullUrl) {
                  productImage.insert('<div class="product-image-unavailable">' + Gucci.getTerm('photo unavailable') + '</div>');
                }
              }
            });
            productImage.removeClassName('loading');
          }
        });

        if (Engine.isMSIE6 || Engine.isMSIE) { //HACK ie
          var fullProductImage = (fullUrl == '' || !fullUrl) ? Shop.FULL_PHOTO_UNAVAILABLE_URL : fullUrl;
          var imageTag = '<img id="'+lightbox.id+'_full_image" src="' + fullProductImage +'" alt=""' +
            ' style="opacity:0;filter:alpha(opacity=0)" />';
          productImage.update(imageTag);
          new Effect.Opacity($(lightbox.id + '_full_image'), {
            from: 0,
            to: 1 ,
            transition: Gucci.cubic,
            afterFinish: function() {
              if (!fullUrl) {
                productImage.insert('<div class="product-image-unavailable">' + Gucci.getTerm('photo unavailable') + '</div>');
              }
            }
          });
          productImage.removeClassName('loading');
        }
        return;
      }
      Loader.cacheOrLoad(fullUrl, {
        onComplete: function() {
          var imageTag = '<div class="full_image_wrapper"><img id="'+lightbox.id
                         + '_full_image" src="'+fullUrl+'" alt="" style="opacity:0;filter:alpha(opacity=0)" /></div>'
                         + ((fullUrl == '' || !fullUrl) ? ('<div class="product-image-unavailable">' + Gucci.getTerm('photo unavailable') + '</div>') : '');
          productImage.update(imageTag);
          new Effect.Opacity($(lightbox.id + '_full_image'), {
            from: 0,
            to: (fullUrl == '' || !fullUrl) ? 0.5 : 1,
            transition: Gucci.cubic,
			afterFinish: function() {				
				productImage.removeClassName('loading');
				
				lightboxObject.rotator = new Gucci.Rotator({
					wrapperElement: productImage,
					imagesObj: images
				});

				lightboxObject.zoomer = new Gucci.Zoomer(
					productImage,
					productImage.down('img'),
					new Date().getTime(),
					zoomUrl, 
					{
						rotator: lightboxObject.rotator
					}
				);
			}
          });
        }
      });
    }
  });
};

Shop.updateZoomer = function(lightbox, fullurl, zoomurl, images) {
  var availstatus = '';
  var activeStyle = Shop.lightboxToActiveStyle.get(lightbox.id);
  var lightboxObject = Shop._lightboxes[lightbox.id];
  var productImage = $(lightbox.id + '_product_image') || lightbox.down('.full_image_wrapper');
  
  if (activeStyle != null) {
    var thumb = lightbox.activeThumbnail;
    var displayGroup = Shop.getDisplayGroupFromThumbId(thumb.id);
    
    var producttemp = displayGroup.getProduct(activeStyle);
    var pricetemp = producttemp.price;
    var skutemp = (producttemp.skus.length > 1) ? producttemp.getSku(Shop.getSkuFromSelectedSize(lightbox, activeStyle).get('sku')) : producttemp.skus[0];
    
    if (!skutemp) {
      availstatus = '';
    } else {
      availstatus = '/' + skutemp.status.replace(/\s/g,'_');
    }
  }
  if (!zoomurl) {
    if (lightboxObject.zoomer) {
      lightboxObject.zoomer.zoomOutAndDestroy();
    }
    lightboxObject.zoomer = null;
    var fullProductImage = (fullurl == '' || !fullurl) ? Shop.FULL_PHOTO_UNAVAILABLE_URL : fullurl;
    Loader.cacheOrLoad(fullProductImage, { 
      onComplete: function() {
        if (!fullurl) { // image is unavailable
          productImage.update(
            '<img style="right:0px; opacity:0" id="'
            + lightbox.id + '_full_image" src="' + fullProductImage + '" alt="" />'
          );
          setTimeout(function() { // needed for safari 2.0  
          $(lightbox.id+'_full_image').morph("opacity: 1", {
             afterFinish: function() {
              productImage.insert('<div class="product-image-unavailable">' + Gucci.getTerm('photo unavailable') + '</div>');
            }
          });
          },10);
        } else {
          productImage.update(
            '<img style="right:260px" id="'
            + lightbox.id + '_full_image" src="' + fullProductImage + '" alt="" />'
          );
          setTimeout(function() { // needed for safari 2.0  
          new Effect.MoveRight($(lightbox.id+'_full_image'), -260, {
            initialRight: 260,
            queue: Shop.queue,
            transition: Gucci.cubic,
            duration: 1.3
          });
          },10);  
        }
      }
    });
    return;
  }
  if (!lightboxObject.zoomer) {
    Loader.cacheOrLoad(fullurl, {
      onComplete: function(){
        var htmlStr = '<div class="full_image_wrapper" style="left:-260px;position:absolute;overflow:hidden;width:260px;height:504px">'
          + '<img style="right:0px" id="' + lightbox.id + '_full_image" src="' + fullurl + '" alt="" /></div>';
        productImage.update(htmlStr);
        
        Shop.pollImage(productImage, function () {Shop.renderUpdateZoomer(productImage, lightbox, zoomurl, images, lightboxObject,activeStyle, availstatus);},
          function () {Shop.updateZoomer(lightbox, fullurl, zoomurl, images);}, 50); 
      }
    });
  } else {
    Loader.cacheOrLoad(fullurl, {
      onComplete: function() {		
		
		// We'll use a separate Rotator class for rotation
		lightboxObject.rotator = new Gucci.Rotator({
			wrapperElement: productImage,
			imagesObj: images
		});

		//set Zoomer
		lightboxObject.zoomer = new Gucci.Zoomer(
			productImage,
			productImage.down('img'),
			new Date().getTime(),
			images.zoom, 
			{
				rotator: lightboxObject.rotator
			}
		);
		
        setTimeout(function () { // needed for safari 2.0
          new Effect.MoveRight($(lightbox.id+'_full_image'), -260, {
            initialRight:260,
            queue:Shop.queue,
            transition:Gucci.cubic,
            duration: 1.3 
          });
        },10);
      }
    });
  }
};

Shop.pollImage = function (productImage, callback, errorcallback, timeout) {
  if ((!productImage.innerHTML) || (productImage.innerHTML.length=0)) {
    if (timeout>400) {
      setTimeout(function () {errorcallback();}, 100);
    }
    else {
      setTimeout(function () { Shop.pollImage(productImage, callback, errorcallback, timeout*2);},  timeout);
    }
  } else {
    callback();
  }
};

Shop.renderUpdateZoomer = function (productImage, lightbox, zoomurl, images, lightboxObject, activeStyle, availstatus) {
	// We'll use a separate Rotator class for rotation
	lightboxObject.rotator = new Gucci.Rotator({
		wrapperElement: productImage,
		imagesObj: images
	});

	//set Zoomer
	lightboxObject.zoomer = new Gucci.Zoomer(
		productImage,
		productImage.down('img'),
		new Date().getTime(),
		zoomurl, 
		{
			rotator: lightboxObject.rotator
		}
	);

	setTimeout(function () { // needed for safari 2.0
		new Effect.Move(productImage.down(), {
			x:260,
			queue:Shop.queue,
			transition:Gucci.cubic,
			duration: 1.3,
			afterFinish: function(effect){
				effect.element.setStyle({overflow: '', width: 'auto'});
			} 
		});
	}, 50);
};

Shop.currentProduct = function(lightbox){
  return Shop._lightboxes[lightbox.id].activeProduct;
};

Shop.deactivateProduct = function(product){
  if (!Shop.isActive(product)) {
    return;
  }
  var lightbox = $(product).up('div.lightbox');
  var lightboxObject = Shop._lightboxes[lightbox.id];
  var thumb = lightbox.activeThumbnail;
  var displayGroupInfo = Shop.DomIdToDisplayGroup.get(thumb.id);
  var displayGroup = Shop.getDisplayGroupFromThumbId(thumb.id);
  
  lightboxObject.activeProduct = null;
	
  if (lightboxObject.zoomer && lightboxObject.zoomer._zoomed) {
	lightboxObject.zoomer.zoomOutAndDestroy();
	delay = Gucci.Zoomer.ZOOM_OUT_SPEED + 0.01;
  } else if (lightboxObject.zoomer) {
	lightboxObject.zoomer.destroy();
  }
  if (lightboxObject.rotator) lightboxObject.rotator.destroy();
	
  lightboxObject.rotator = null;
  lightboxObject.zoomer = null;
  
  Shop._lightboxes[$(lightbox).id].variationPanel.closeVariations();
  Shop.showDetails(lightbox);
  
  var wrapper = lightbox.down('div.full_image_wrapper');
  var productImage = $(lightbox.id+'_product_image');
  
  if (wrapper) {
    wrapper.setStyle({
      position:'absolute',
      top:0,
      left:0,
      overflow:'hidden',
      width:'260px',
      height:'504px'
    });
    new Effect.Move(wrapper, {
      x: -260, 
      queue:Shop.queue,
      transition:Gucci.cubic,
      duration: 0.7
    });
  } else {
    new Effect.MoveRight(productImage.down('img'), 260, {
      queue:Shop.queue,
      transition:Gucci.cubic,
      duration: 0.7
    });
    var productImageUnavailable = productImage.down('div.product-image-unavailable');
    if(productImageUnavailable) {
      productImageUnavailable.hide();
    }
  }
  
  product.morph('left: 0px', {
    queue:Shop.queueLast,
    transition:Gucci.cubic,
    duration: 0.7,
    afterFinish: function() {
      Shop.activateVariationSlider(product.up('div.thumbnail'));
    }
  });
};

Shop.getDisplayGroupFromThumbId = function(thumbId) {
  return gucci.DataHelper.getPanelDisplayGroup(Shop.DomIdToDisplayGroup.get(thumbId).displayGroup_id);
};

Shop.getThumbIdFromDisplayGroupId = function(displayGroup_id) {
  var thumbId;
  Shop.DomIdToDisplayGroup.each(function(pair) {
    if (pair.value.displayGroup_id == displayGroup_id) {
      thumbId = pair.key;
    }
  });
  return thumbId;
};

Shop.getThumbIdFromLinkId = function(link_id) {
  var thumbId;
  Shop.DomIdToDisplayGroup.each(function(pair) {
    if (pair.value.link_id == link_id) {
      thumbId = pair.key;
    }
  });
  return thumbId;
};

Shop.showProduct = function(thumbImg) {
  var thumbId = thumbImg.up('div.thumbnail').id;
  var displayGroup = Shop.getDisplayGroupFromThumbId(thumbId);
  var displayGroupInfo = Shop.DomIdToDisplayGroup.get(thumbId);
  var lightbox = thumbImg.up('div.lightbox');
  var details = lightbox.down('div.details');
  var lightboxObject = Shop._lightboxes[lightbox.id];
  //HACK: klemens: to know whats currently 'active' in the lightbox.
  lightbox.activeThumbnail = thumbImg.up();
  
  // prevent further scrolling with variation slider
  Shop.deactivateVariationSlider(thumbImg.up('div.thumbnail'));
  Shop.hideTooltip(thumbImg.up('div.thumbnail').down('.tooltip'));
  
  if (Shop.isActive(thumbImg)) {
    return;
  }
  // TODO: check for Shop's states, e.g. "idle", "active", "busy", ...    
  if (Shop.isBusy(lightbox)) {
    return;
  }
  // not needed any longer => Data.js
  // if(!Shop.getProductInfo(product.up())) return;
  
  Shop.deactivateProduct(Shop.currentProduct(lightbox));
  Shop.hideSizeGuideByLightbox(lightbox);

  Shop.openLightbox(lightbox, thumbId);
  lightbox.down('div.product-image').addClassName('loading');
  details.hide();

  Shop.setBusy(lightbox);

  new Effect.Event({afterFinish:function() {
    
    var displayGroup = gucci.DataHelper.getPanelDisplayGroup(Shop.DomIdToDisplayGroup.get(thumbId).displayGroup_id);
    
    var onDataUpdated = function(displayGroup) {
      if (displayGroup.templates.displaygroup_template) {
        detailsTemplate = new Template(gucci.Partials.renderTemplate(displayGroup.templates.displaygroup_template, displayGroup));
        details.update(detailsTemplate.evaluate({lightbox: lightbox.id}));
      }
      if (displayGroup.templates.personalshopper_template) {
        $(lightbox.id+'_shopper').update(gucci.Partials.renderTemplate(displayGroup.templates.personalshopper_template, displayGroup)).show();
      }

      lightboxObject.variationPanel.prepareAndOpenVariations(thumbId);
      
      Shop.activateProduct(thumbImg);
      Shop.selectStyle(thumbImg, displayGroupInfo.currentStyle, { lightbox: lightbox, thumbId: thumbId });
      Shop.setIdle(lightbox);
    };
    
    displayGroup.getDetails(onDataUpdated);
  }, queue:Shop.queue });
};

Shop.showProductByStyle = function(style) {
  var idx = null;
  style = style.substr(style.length-17).gsub('_', '');
  
  for (var i = 0; i < Shop.thumbs.length; i++) {
    if (Shop.thumbs[i].id == style) {
      idx = i;
      break;
    }
  }
  if (!idx) {
    return;
  }
  Shop.showProduct($(['thumbnail_', idx].join('')).down('img'));
};

Shop.showProductFromDeeplink_depricated = function(deepLink) {
  var displayGroup = gucci.DataHelper.getPanelDisplayGroupByStyleNumber(deepLink.gsub("_",""));
  if (!displayGroup) {
    return;
  }
  var thumb = $(Shop.getThumbIdFromDisplayGroupId(displayGroup.displayGroup_id));
  var displayGroupInfo = Shop.DomIdToDisplayGroup.get(thumb.id);
  displayGroupInfo.currentStyle = displayGroup.leadStyle.style_number;
  displayGroupInfo.currentThumbIndex = displayGroup.getThumbIndexForVariation(displayGroup.leadStyle.style_number);
  
  if (Shop.isActive(thumb.down('img'))) {
	Shop._lightboxes[thumb.up('div.lightbox').id].variationPanel.selectVariation(null, thumb.id, displayGroup.leadStyle.variation_index);
    Shop.moveIntoView(thumb.up('div.lightbox'));
  } else {
    Shop.showProduct(thumb.down('img'));
  }
};

Shop.showProductFromDeeplink = function(fragment) {
  if (Shop.isRTW()) {
    RTW.gotoDeepLink(fragment);
    return;
  }
  // Shop.showProductFromDeeplink('panelId-16418-141415FFKAG9678-801612243');
  var productData = {};
  var fragments = fragment.split('-');
  
  $w('panelId displayGroup styleNumber sku').each(function(identifier, i) {
    if (fragments[i]) {
      productData[identifier] = fragments[i];
    }
  });
  
  if (productData.displayGroup) { //seems to be a fine new deepLink
    var thumb = $(Shop.getThumbIdFromDisplayGroupId(productData.displayGroup));
    if (!thumb) {
      return;
    }
    var displayGroupInfo = Shop.DomIdToDisplayGroup.get(thumb.id);
    var displayGroup = gucci.DataHelper.getPanelDisplayGroup(displayGroupInfo.displayGroup_id);

    if (productData.styleNumber) {
      displayGroupInfo.currentStyle = productData.styleNumber;
      displayGroupInfo.currentThumbIndex = displayGroup.getThumbIndexForVariation(productData.styleNumber);
      if (productData.sku) {
        displayGroupInfo.initialSku = productData.sku;
      }
    }
    if (Shop.isActive(thumb.down('img'))) {
      var product = displayGroup.getProduct(productData.styleNumber);
      Shop._lightboxes[thumb.up('div.lightbox').id].variationPanel.selectVariation(null, thumb.id, product.variation_index);
      Shop.moveIntoView(thumb.up('div.lightbox'));
    } else {
      Shop.showProduct(thumb.down('img'));
    }
  } else { //maybe it works with the old deepLink aka. link_id aka. productLink
    Shop.showProductFromDeeplink_depricated(fragment);
  }
};

Shop.showStyles = function(lightbox) {
  if (Shop.isBusy(lightbox)) {
    return;
  }
  Shop.setBusy(lightbox);
  
  var lightboxObject = this._lightboxes[lightbox.id];
  if (lightboxObject.stylesActive) {
    return;
  }
  
  if (Engine.isMSIE6 && lightbox.down('select.size-select')) {
    lightbox.down('select.size-select').setStyle({visibility:'hidden'});
  }
  var initialRight = 0;
  var sizeGuide = lightbox.down('div.size-guide');
  if (sizeGuide) {
    sizeGuide.hide();
  }
  
  new Effect.Parallel([
    new Effect.MoveRight(lightbox.down('div.details-wrapper'), 260, {
      sync: true,
      initialRight: initialRight
    })
  ], { 
    duration:0.7,
    transition:Gucci.cubic,
    afterFinish: function() {
      Shop.setIdle(lightbox);
    }
  });
  lightboxObject.stylesActive = true;
};

Shop.previewStyle = function(style) {
  if (style.hasClassName('active-style')) {
    return;
  }
  var previous = style.up().down('div.active-style');
  if (previous) {
    previous.removeClassName('active-style');
  }
  style.addClassName('active-style');
};

Shop.cancelStyle = function(back) {
  var lightbox = $(back).up('div.lightbox');
  if (this.isBusy(lightbox)) {
    return;
  }
  this.setBusy(lightbox);
  this.showDetails(lightbox);
};

Shop.showSizeGuide = function(link) {
  var lightbox = $(link).up('div.lightbox');
  if (this.isBusy(lightbox)) {
    return;
  }
  this.setBusy(lightbox);
  
  if (Engine.isMSIE6) {
    var selects = $$('select');
    for (var i = 0; i < selects.length; i++) {
      selects[i].setStyle({visibility:'hidden'});
    }
  }
  lightbox.down('div.shopper-wrapper').hide();
  
  new Effect.MoveRight( lightbox.down('div.details-wrapper'), 260,{
    initialRight: 0,
    duration:0.7,
    transition:Gucci.cubic,
    afterFinish: function() {
      Shop.setIdle(lightbox);
    }
  });
  var activeStyle = Shop.lightboxToActiveStyle.get(lightbox.id);
  Shop._sizeGuideOpen = true;
};

Shop.hideSizeGuide = function(link){
  var lightbox = $(link).up('div.lightbox');
  if (this.isBusy(lightbox)) {
    return;
  }
  this.setBusy(lightbox);
  
  var detailsWrapper = lightbox.down('div.details-wrapper');
  
  if (detailsWrapper.style.right != '260px') {
    return;
  }
  new Effect.MoveRight(detailsWrapper, -260, {
    initialRight: 260,
    duration: 0.7,
    transition: Gucci.cubic,
    afterFinish: function() {
      Shop.setIdle(lightbox);
      if(Engine.isMSIE6) {
        var selects = $$('select');
        for (var i = 0; i < selects.length; i++) {
          selects[i].setStyle({visibility:'visible'});
        }
      }
      lightbox.down('div.shopper-wrapper').show();
    }
  });
  Shop._sizeGuideOpen = false;
};

Shop.hideSizeGuideByLightbox = function(lightbox){
  var detailsWrapper = lightbox.down('div.details-wrapper');
  if (detailsWrapper.style.right != '260px') {
    return;
  }
  detailsWrapper.setStyle({right:'0px'});
};

Shop.showDetails = function(lightbox){
  var sizeSelect = lightbox.down('select.size-select');
  var lightboxObject = this._lightboxes[lightbox.id];
  if (!lightboxObject.stylesActive) {
    if (Engine.isMSIE6 && sizeSelect) {
      sizeSelect.setStyle({visibility:'visible'});
    }
    Shop.setIdle(lightbox);
    return;
  }
  
  var initialRight = 260;
  
  new Effect.Parallel([
    new Effect.MoveRight(lightbox.down('div.details-wrapper'), -260, {
      sync: true,
      initialRight: initialRight
    })
  ], {
    duration: 0.7,
    transition: Gucci.cubic,
    afterFinish: function() {
      Shop.setIdle(lightbox);
      if (Engine.isMSIE6 && sizeSelect) {
        sizeSelect.setStyle({visibility:'visible'});
      }
      if (lightbox.down('div.size-guide')) {
        lightbox.down('div.size-guide').show();
      }
    }
  });
  lightboxObject.stylesActive = false;
};

Shop.showShopper = function(link) {
  var lightbox = $(link).up('div.lightbox');
  var currentDetailsContainer = lightbox.down('div#details_'+ lightbox.id + '_' +Shop.lightboxToActiveStyle.get(lightbox.id));
  var lightboxObject = Shop._lightboxes[lightbox.id];
  var details = lightbox.down('div.details');
  var productImage = lightbox.down('div.product-image');
  var detailsWrapper = lightbox.down('div.details-wrapper');
  var shopper = lightbox.down('div.shopper');
  var shopperWrapper = lightbox.down('div.shopper-wrapper');
  var productBorder = lightbox.down('div.product-details-border');
  
  // if(this.isBusy(lightbox)) return;
  // this.setBusy(lightbox);
  if (!Object.isUndefined(lightbox.down('div.variants')))
  	new Effect.Parallel(Gucci.scaleLayout(-lightbox.down('div.variants').offsetWidth), {
	    transition: Gucci.cubic,
	    duration: 1.7,
	    queue: Shop.queueLast
	  });
  else
 	new Effect.Parallel(Gucci.scaleLayout(0), {
	    transition: Gucci.cubic,
	    duration: 1.7,
	    queue: Shop.queueLast
	  });
  Shop._lightboxes[$(lightbox).id].variationPanel.closeVariations();
  
  if(Engine.isMSIE6 && currentDetailsContainer.down('select.size-select')) {
    currentDetailsContainer.down('select.size-select').setStyle({visibility:'hidden'});
  }
  productImage.style.zIndex = 3;
  
  var delay = 0;
  if (lightboxObject.zoomer) {
    // set Shop.queue to a different value to zoomOut doensn't put the effect in the same queue
    // as the Effect.Parallel above. So the zoomOut is timed properly
    var oldShopQueue = Shop.queue;
    Shop.queue = '';
    lightboxObject.zoomer.zoomOutAndPause();
    Shop.queue = oldShopQueue;
    delay = Gucci.Zoomer.ZOOM_OUT_SPEED + 0.1;
  }
  
  if (lightbox.down('div.size-guide')) {
    lightbox.down('div.size-guide').hide();
  }
  
  if (currentDetailsContainer.down('div.bottom-links')) {
    currentDetailsContainer.down('div.bottom-links').hide();
  }
  
  var effects = [];
  if(this.isCatalog){
    var panel3Background = lightbox.down('div.panel3-background');
    panel3Background.setStyle({
      left:'520px',
      opacity: 0
    });
    detailsWrapper.setStyle({
      left:'520px',
      right:'auto',
      width:'260px',
      overflow:'hidden'
    });
    effects.push(new Effect.Scale(detailsWrapper, 0, {
      sync:true,
      scaleMode: {
        originalWidth:260,
        originalHeight:504
      },
      scaleFrom:100,
      scaleY:false,
      scaleContent:false
    }));
    effects.push(new Effect.Opacity(panel3Background, {
      from:0,
      to:1,
      sync:true
    }));
  } else {
    shopper.setStyle({
      visibility:'hidden',
      opacity: 0
    });
    new Effect.Opacity(details, {
      from:1,
      to:0,
      transition:Gucci.cubic,
      duration:0.7
    });
    effects.push(new Effect.MoveRight( productImage,   260, {
      sync: true,
      initialRight: 260
    }));
    effects.push(new Effect.MoveRight( detailsWrapper, 260, { sync: true, initialRight: 0 }));
    effects.push(new Effect.MoveRight( shopperWrapper, 260, { sync: true, initialRight: (Engine.isMSIE6 ? -258 : -260)}));
  }
  
  new Effect.Parallel(effects, {
    queue: Shop.queueLast,
    duration:1.3,
    delay:delay,
    transition:Gucci.cubic,
    afterUpdate: function(){
      if (productBorder && productBorder.visible()) {
        productBorder.hide();
      }
    },
    afterFinish: function(){
      // TODO is this still needed?
      //    if(details.down('div.more-styles')) details.down('div.more-styles').hide();
      currentDetailsContainer.down('div.configuration-info').setStyle({
        height:'2px',
        overflow:'hidden'
      });
      if(currentDetailsContainer.down('div.size')) {
        currentDetailsContainer.down('select.size-select').hide();
        if(currentDetailsContainer.down('a.size-guide-link')) {
          currentDetailsContainer.down('a.size-guide-link').hide();
        }
        var size = currentDetailsContainer.down('select.size-select');
        lightbox.down('span.size-info').update(size.options[size.selectedIndex].text).show();
      }
      currentDetailsContainer.down('ul.functions').hide();
      currentDetailsContainer.down('ul.personal-shopper-headline').update(Gucci.getTerm('consult a personal shopper')).show();
      
      if (Shop.isCatalog) {
        lightbox.down('div.container').setStyle({overflow:'visible'});
        lightbox.down('div.shopper-wrapper').setStyle({left:'780px',right:'auto',width:'0px',overflow:'hidden'});
        new Effect.Parallel([
          new Effect.Scale(detailsWrapper, 100, {
            sync: true,
            scaleMode: {
              originalWidth:260,
              originalHeight:504
            },
            scaleFrom: 0,
            scaleY: false,
            scaleContent: false
          }),
          new Effect.Scale(shopperWrapper, 100, {
            sync: true,
            scaleMode: {
              originalWidth: 260,
              originalHeight: 504
            },
            scaleFrom: 0,
            scaleY: false,
            scaleContent: false
          })
        ], {
          duration:0.7
        });
      } else {
        shopper.setStyle({visibility:'visible'});
        new Effect.Parallel([
          new Effect.Opacity(details, {
            from: 0,
            to: (Engine.isKHTML ? 0.99 : 1),
            sync: true
          }), //fix rendering bug in Safari 2.0
          new Effect.Opacity(shopper, {
            from:0,
            to:1.0,
            sync:true
          })
        ], {
          duration: 0.7
        });
      }
      Shop.setIdle(lightbox);
    }
  });
  
  var availstatus;
  var activeStyle = Shop.lightboxToActiveStyle.get(lightbox.id);
  var thumb = lightbox.activeThumbnail;
  var displayGroup = Shop.getDisplayGroupFromThumbId(thumb.id);
  
  var producttemp = displayGroup.getProduct(activeStyle);
  var pricetemp = producttemp.price;
  var skutemp = (producttemp.skus.length > 1) ? producttemp.getSku(Shop.getSkuFromSelectedSize(lightbox, activeStyle).get('sku')) : producttemp.skus[0];

  if (!skutemp) {
    availstatus = '';
  } else {
    availstatus = skutemp.status.replace(/\s/g,'_');
  }
};

Shop.closeShopper = function(link) {
  if (Shop.isRTW()) {
    RTW.closePersonalShopper(link);
    return;
  }
  var lightbox = $(link).up('div.lightbox');
  var thumbnail = lightbox.activeThumbnail;
  var currentDetailsContainer = lightbox.down('div#details_'+ lightbox.id + '_' + Shop.lightboxToActiveStyle.get(lightbox.id));
  var panel3Background = lightbox.down('div.panel3-background');
  var lightboxObject = Shop._lightboxes[$(lightbox).id];
  var details = lightbox.down('div.details');
  var productBorder = lightbox.down('div.product-details-border');
  var detailsWrapper = lightbox.down('div.details-wrapper');
  var shopperWrapper = lightbox.down('div.shopper-wrapper');
  var productImage = lightbox.down('div.product-image');
  
  //HACK to get to the current selected thumbnail
  var current_style = Shop.lightboxToActiveStyle.get(lightbox.id);
  var effects = [];
  //if(this.isBusy(lightbox)) return;
  //this.setBusy(lightbox);
  
  if (this.isCatalog && panel3Background.getStyle('left') != '520px') {
    Catalog.closeShopper(link);
    return;
  }
  if (lightboxObject.zoomer) {
    lightboxObject.zoomer.unpause();
  }
  if (this.isCatalog){
    effects.push(new Effect.Scale(detailsWrapper, 0, {
      sync:true,
      scaleMode: {
        originalWidth: 260,
        originalHeight: 504
      },
      scaleFrom: 100,
      scaleY: false,
      scaleContent: false
    }));
    effects.push(new Effect.Scale(shopperWrapper, 0, {
      sync: true,
      scaleMode: {
        originalWidth: 260,
        originalHeight: 504
      },
      scaleFrom: 100,
      scaleY: false,
      scaleContent: false
    }));
  } else {
    effects.push(new Effect.MoveRight( productImage,   -260, { sync: true, initialRight: 520 }));
    effects.push(new Effect.MoveRight( detailsWrapper, -260, { sync: true, initialRight: 260 }));
    effects.push(new Effect.MoveRight( shopperWrapper, -260, { sync: true, initialRight: 0 }));
  }

  new Effect.Parallel(effects, {
    duration: 1.3,
    transition: Gucci.cubic,
    afterFinish:function() {
      var bottomLinks = currentDetailsContainer.down('div.bottom-links');
      var sizeGuideLink = currentDetailsContainer.down('a.size-guide-link');
      var sizeSelect = currentDetailsContainer.down('select.size-select');
      var sizeGuide = currentDetailsContainer.down('div.size-guide');
      
      productBorder.show();
      lightboxObject.variationPanel.prepareAndOpenVariations(thumbnail.id);
      
      currentDetailsContainer.down('div.configuration-info').setStyle({height:'auto',overflow:'visible'});
      currentDetailsContainer.down('ul.functions').show();
      currentDetailsContainer.down('ul.personal-shopper-headline').hide();
      if (bottomLinks) {
        bottomLinks.show();
      }
      if(currentDetailsContainer.down('div.size')) {
        sizeSelect.setOpacity(1).show();
        if(sizeGuideLink) {
          sizeGuideLink.show();
        }
        currentDetailsContainer.down('span.size-info').hide();
      }
      
      Shop.setIdle(lightbox);
      productImage.style.zIndex = 2;
      if (Engine.isMSIE6 && sizeSelect) {
        sizeSelect.setStyle({visibility:'visible'}); 
      }
      if (sizeGuide) {
        sizeGuide.show();
      }
      if (Engine.isKHTML) {
        details.setOpacity(1);
      }
      if(Shop.isCatalog) {
        new Effect.Opacity(panel3Background, {
          from: 1,
          to: 0,
          duration: 0.7,
          afterFinish: function() {
            panel3Background.setStyle({left:'-260px'});
            lightbox.down('div.container').setStyle({overflow:'hidden'});
            new Effect.Scale(detailsWrapper, 100, {
              scaleMode: {
                originalWidth: 260,
                originalHeight: 504
              },
              scaleFrom: 0,
              scaleY: false,
              duration: 0.7,
              scaleContent: false,
              afterFinish:function() {
                detailsWrapper.setStyle({left:'auto',right:'0',overflow:'visible'});
                //alter.down('div.styles-wrapper').show();
              }
            });
          }
        });
      } else {
        //alter.down('div.styles-wrapper').show();
      }
    } 
  });
};

Shop.activateProduct = function(product){
  (function() {
    var lightbox = $(product).up('div.lightbox');
    Shop._lightboxes[lightbox.id].activeProduct = product;
    lightbox.down('div.details').show();
	Shop.checkScrolling(lightbox.down('div.details'));
    product.morph('left:' + product.getWidth() + 'px', {
      queue:Shop.queueLast,
      transition:Gucci.cubic,
      duration: 1.3
    });      
  }).defer();
};

Shop.setBusy = function(lightbox){
  Shop._lightboxes[lightbox.id].busy = true;
};

Shop.setIdle = function(lightbox){
  Shop._lightboxes[lightbox.id].busy = false;
};

Shop.isBusy = function(lightbox){
  return Shop._lightboxes[lightbox.id].busy;
};

Shop.submitShopper = function(form) {
  if (Shop.isRTW()) {
    RTW.submitShopper(form);
    return;
  }
  var lightbox = $(form).up('div.lightbox');
  
  var activeStyle = Shop.lightboxToActiveStyle.get(lightbox.id);
  var displayGroupInfo = Shop.DomIdToDisplayGroup.get(Shop._lightboxes[lightbox.id].activeProduct.up('div.thumbnail').id);
  var displayGroup = gucci.DataHelper.getPanelDisplayGroup(displayGroupInfo.displayGroup_id);
  var product = displayGroup.getProduct(activeStyle);
  var sku = (product.skus.length > 1) ? product.getSku(Shop.getSkuFromSelectedSize(lightbox, activeStyle).get('sku')) : product.skus[0];
  
  var requestParams = {};
  
  if (Shop.isCatalog) {
    var page = lightbox.up('div.catalog-page').id.split('_')[1];
    requestParams = Catalog.serialize(page, Catalog.getOpenStyleForPage(page));
  } else {
    requestParams.status = sku ? sku.status : '';
    requestParams.sku = sku ? sku.sku : '';
    requestParams.size = sku ? sku.sizename : '';
    requestParams.description = product ? product.text.grpdesc : '';
    requestParams.variationDescription = product ? product.text.vardesc : '';
    requestParams.price = product ? product.priceNum : '';
    requestParams.style = product ? product.formatStyleNumber(" ") : '';
    requestParams.sale = product ? product.priceSale : '';
    requestParams.path = displayGroup ? displayGroup.path : '';
    requestParams.collection = product ? product.collection : '';
    requestParams.department = product ? product.department : '';
    requestParams.productLink = product ? product.formatStyleNumber("_") : '';
    requestParams.imageLink = product ? product.images.thumb : '';
    requestParams.miniThumbLink = product ? product.images.miniThumb : '';
    requestParams.shown = product ? (product.images.miniThumb ? 1 : 0) : 0;
  }
  requestParams.formType = 'contact';
  
  new Ajax.Request('/' + Cookie.get('site') + '/contact_item.asp', {
    onSuccess: function(request) {
      $(form).up('div.shopper').update(request.responseText.gsub(/\\"/,'"').gsub(/\\'/,"'"));
    },
    onException: function(transport, exception) {
       Shop.lastException = $H(exception);
    },
    parameters: Form.serialize(form) + '&' + $H(requestParams).toQueryString()
  });
};

Shop.showIconOverlay = function(iconname,target) {
	target = $(target);
	if ($('iconoverlay_container')) return;
	if (Shop._iconText == null) {
		if (typeof gucci.OverlayParser == 'object' && typeof gucci.OverlayParser._iconText == 'object') {
			Shop._iconText = gucci.OverlayParser._iconText;
			Shop.showIconOverlay(iconname,target);
		}
		else {
			new Ajax.Request('/json/icontext.js',{ method: 'get',
				onSuccess: function(transport){
					Shop._iconText = transport.responseText.evalJSON(true);	
					Shop.showIconOverlay(iconname,target);		
				},
				onFailure: function(transport){
					alert('failure:' + transport.status);
				}
			});
		}
		return;
	}
		
	if (Shop._iconText == null) return;
	var iconnamedisplay = iconname;
	iconname = iconname.replace(/ /g,'').toLowerCase();
	var maincontent = Shop._iconText[decodeURI(Cookie.get('language'))];
	if (typeof maincontent == 'undefined' || !maincontent.close || !maincontent.linktext || !maincontent[iconname] || !maincontent[iconname + 'img'] || !maincontent[iconname + 'link']) return;
	if (maincontent[iconname + 'header'])
		iconnamedisplay = maincontent[iconname + 'header'];
	// create elements
	var iconoverlaycontainer = new Element('div',{'id':'iconoverlay_container'});
	var iconoverlaybg = new Element('div');
	iconoverlaybg.addClassName('bg');
	
	if (Engine.isMSIE)
		iconoverlaybg.setStyle({'background':'none'});
	var iconoverlaycontent = new Element('div',{'id':'iconoverlay_content'});
	var closecontainer = new Element('div');
	closecontainer.addClassName('close_container');
	var headertext = new Element('h1');
	var maintext = new Element('p');
	var header = new Element('div');
	header.addClassName('header');
	var imgswatch = new Element('img');
	var iconlinkcontainer = new Element('div');
	iconlinkcontainer.addClassName('link_container');
	
	// update content
	closecontainer.update('<a href=\'#\' onclick=\'Shop.hideIconOverlay(); return false;\'>' + maincontent.close + '</a>');
	headertext.update(iconnamedisplay);
	maintext.update(maincontent[iconname]);
	imgswatch.writeAttribute('src',maincontent[iconname+'img']);
	var fulllink = maincontent[iconname + 'link'].replace('<site>',decodeURI(Cookie.get('site')));
	if (typeof salenav!="undefined" && salenav)		
		iconlinkcontainer.update();
	else
		iconlinkcontainer.update('<a href=\'#\' onclick=\'window.open("' + fulllink + '"); Shop.hideIconOverlay(); return false;\'>' + maincontent.linktext + '</a>');
	var mouseX = Shop._currentMousePosX + Position.scrollX();
	if (!mouseX)
		mouseX = 0;
	var mouseY = 60;
	iconoverlaycontainer.setStyle({
		top: mouseY + 'px',
		left: (mouseX-365) +'px',
		opacity:1,
		zIndex: '10010',
		display:'none'
	});
	if ($('send_to_a_friend') && $('send_to_a_friend').visible())
		iconoverlaycontainer.setStyle({zIndex:'10020'});
	header.appendChild(closecontainer);
	header.appendChild(headertext);
	iconoverlaycontent.appendChild(header);
	iconoverlaycontent.appendChild(maintext);
	iconoverlaycontent.appendChild(imgswatch);
	iconoverlaycontent.appendChild(iconlinkcontainer);
	iconoverlaybg.appendChild(iconoverlaycontent);
	iconoverlaycontainer.appendChild(iconoverlaybg);
	var content = $('content');
	var finalleft = 0;
	if (target.up('div.container') && (target.up('div.container').down('div.products') || target.up('div.container').down('div.alter'))) {
		content = target.up('div.container');
		if ($('send_to_a_friend') && $('send_to_a_friend').visible() && target.up('div.lightbox'))
			content = target.up('div.lightbox');
		content.appendChild(iconoverlaycontainer);
		if ((content.getHeight() - iconoverlaycontainer.getHeight()) < 14) {
			iconoverlaycontainer.setStyle({height:'480px'});
			iconoverlaycontainer.setStyle({width:'350px'});
		}
		
		if (content.down('div.products'))
			finalleft = (parseInt(content.down('div.products').getStyle('width'),10)/2)-((parseInt(iconoverlaycontainer.getStyle('width'),10)-310)/2);
		else
			finalleft = (parseInt(content.down('div.alter').getStyle('width'),10)/2)-((parseInt(iconoverlaycontainer.getStyle('width'),10)-310)/2);
		
		iconoverlaycontainer.setStyle({
			top: (content.getHeight()-iconoverlaycontainer.getHeight())/2 + 'px',
			left: content.getWidth()-iconoverlaycontainer.getWidth() + 'px'
		});
		
		// hitbox call
		if (content.down('div.style-number')) {
			var stylenum = content.down('div.style-number').innerHTML.replace(/ /g,'');
		}
	}
	else {
		content.appendChild(iconoverlaycontainer);
	}
	new Effect.Parallel([
		new Effect.Move(iconoverlaycontainer,{x: finalleft, y: (content.getHeight()-iconoverlaycontainer.getHeight())/2, mode: 'absolute', sync: true}),
		new Effect.Appear(iconoverlaycontainer,{sync: true})
	], {duration: 1});
	
};

Shop.hideIconOverlay = function() {
	if ($('iconoverlay_container')) {
		var iconoverlaycontainer = $('iconoverlay_container');
		var content = iconoverlaycontainer.up('div.container');
		
		if (typeof content == 'undefined') {
			$('iconoverlay_container').fade({duration:0.5,afterFinish:function(){$('iconoverlay_container').remove();}});
		}
		else {	
			new Effect.Parallel([
				new Effect.Move(iconoverlaycontainer,{x: content.getWidth()-iconoverlaycontainer.getWidth(), y: (content.getHeight()-iconoverlaycontainer.getHeight())/2, mode: 'absolute', sync: true}),
				new Effect.Fade(iconoverlaycontainer,{sync: true})
			], {duration: 1,afterFinish:function(){$('iconoverlay_container').remove();}});
		}
	}
	//if $('iconoverlay_container')
		//$('iconoverlay_container').fade({duration:0.5,afterFinish:function(){$('iconoverlay_container').remove();}});
};

Shop.addCardPrice = function(link, lo, hi) {
  var amount = link.value;
  amount = amount.replace(/[^0-9.-]/,'');
  amount = amount.length > 0 ? parseInt(amount, 10) : lo;
  if (amount<lo) {
    amount = lo;
  }
  if (amount>hi) {
    amount = hi;
  }
  var lightbox = $(link).up('div.lightbox');
  var activeStyle = Shop.lightboxToActiveStyle.get(lightbox.id);
  var displayGroupInfo = Shop.DomIdToDisplayGroup.get(Shop._lightboxes[lightbox.id].activeProduct.up('div.thumbnail').id);
  var displayGroup = gucci.DataHelper.getPanelDisplayGroup(displayGroupInfo.displayGroup_id);
  var product = displayGroup.getProduct(activeStyle);
  product.priceNum = amount;
};

Shop.redrawMinibag = function() {
  var minibagProducts = $$('div#minibag-products div.product');
  var waitlistProducts = $$('div#waitlist-products div.product');
  var products = minibagProducts.concat(waitlistProducts);
  var waitlistProducts2 = $('waitlist-products');
  var minibagContainer = $('minibag-container');
  
  if (waitlistProducts2 && minibagProducts.length == 0) {
    waitlistProducts2.setStyle({ marginRight: '0px' });
  } else {
    if (waitlistProducts2) {
      waitlistProducts2.setStyle({ marginRight: '7px' });
    }
  }  
  if (products.length == 0) {
    $('minibag-container').down('ul.shopping-bag').hide();
	if (salenav!="undefined" && salenav)
		$("searchlink").hide();
	else {
		if ($("searchlink"))
			$("searchlink").show();
	}
  } else {
    minibagContainer.down('span.count').update('(' + products.length  + ')');
    minibagContainer.down('ul.shopping-bag').show();
	if (salenav!="undefined" && salenav) { 
		if (minibagContainer.down('ul.shopping-bag').down('.searchlink-bag')) {
			minibagContainer.down('ul.shopping-bag').down('.searchlink-bag').hide();
			$('minibag-container').select('ul.shopping-bag')[0].setStyle({'paddingTop':'36px'});
		}
	}
	if ($("searchlink")){
	  $("searchlink").hide();
	};
	  if(!$('searchlink')){
	   $('minibag-container').select('ul.shopping-bag')[0].setStyle({'paddingTop':'36px'});		
	 }; 
  }
};

Shop.initializeMinibag = function() {
  gucci.Minibag.initialize({
    onInitialized: function() {
      Shop.createProductsFromCookies();
    }.bind(this)
  });
  gucci.Minibag.startSync({
    onSyncComplete: function() {
      Shop.createProductsFromCookies();
    }
  });
};

Shop.createProductsFromCookies = function() {
  var products = gucci.Minibag.getProducts();
  var minibagProducts = $('minibag-products');
  var waitlistProducts = $('waitlist-products');

  if (minibagProducts) {
    minibagProducts.update('');
  }
  if (waitlistProducts) {
    waitlistProducts.update('');
  }
  
  for (var i = 0; i < products.length; i++) {
    var product = products[i];
    var target = product.cookie.substring(0, 2);
          
    if(target == 'wl')
      target = waitlistProducts;
    else
      target = minibagProducts;
    Shop.createProductForMinibag(product, target);
  }
  Shop.redrawMinibag();
};

Shop.createProductForMinibag = function(product, target) {
  var url = product.href + '#' + (product.panel_id || 0) + '-' + product.displayGroupId + '-' + product.stylenumber + '-' + product.sku;
  
  var minibagProduct = new Template(
    '<div class="product" onmouseover="this.firstChild.style.visibility = \'visible\';" onmouseout="this.firstChild.style.visibility = \'hidden\';">' +
      '<a href="#" onclick="Shop.deleteFromMinibag(this); return false" class="remove" style="visibility:hidden">Remove</a>'+
      '<a href="#" onclick="Shop.goToAndOpen(\'' + url  + '\'); return false;">'+
        '<img src="#{miniThumb}"/>'+
      '</a>'+
    '</div>'
  );
  if (target) {
    target.insert({ top: minibagProduct.evaluate(product) });
    target.down('div.product').sku = product.sku;
  }
};

/*
Property: addToBag
  adds HTML to Minibag
*/
Shop.addToBagEffect = function(lightbox, sku) {
  var delay = 0;
  var product = sku._parent;
  var miniThumbURL = product.images.miniThumb;
  var container = $((sku.status == 'backorder' ? 'waitlist' : 'minibag') + '-products');
  var lightboxObject = Shop._lightboxes[lightbox.id];
  
  if (!miniThumbURL) {
    miniThumbURL = Shop.MINI_THUMB_PHOTO_UNAVAILABLE_URL;
  }
  if (lightboxObject.zoomer) {
    lightboxObject.zoomer.zoomOut();
    delay = Gucci.Zoomer.ZOOM_OUT_SPEED*1000 + 10;
  }
  
  setTimeout(function() {
    var minibagProduct = (
      '<div class="product" onmouseover="this.firstChild.style.visibility = \'visible\';" onmouseout="this.firstChild.style.visibility = \'hidden\';" style="display: none;">'+
        '<a href="#" onclick="Shop.deleteFromMinibag(this); return false" class="remove" style="visibility:hidden">Remove</a>'+
        '<a href="#" onclick="Shop.goToAndOpen(\'/' + Cookie.get('site') + '/' + Cookie.get('language') + '/' + Cookie.get('site') +  product._parent.path + '#' + sku.deep_link + '\'); return false;">'+
          '<img src="' + miniThumbURL + '"/>'+
        '</a>'+
      '</div>'
    );
    container.insert({top: minibagProduct});
    
    var productDiv = container.down('div.product');
    productDiv.setStyle({ 
      position: 'relative',
      opacity: 0,
      width: '1px',
      top: '64px' 
    }).show();
    
    lightbox.down('div.product-image').removeClassName('loading');
    
    var moveProductInView = function() {
      new Effect.Parallel([
        new Effect.Move(productDiv, { y: -64,  sync: true }),
        new Effect.Opacity(productDiv, { from: 0.1, to: 1.0 })
      ], { 
        transition: Gucci.cubic, 
        duration: 1.8,
        beforeSetup: function() {
          productDiv.setOpacity(1);
        },
        afterFinish: function() {
          productDiv.setStyle({ 
            position: 'static', 
            top: 'auto' 
          });
        }
      });
    };
    productDiv.sku = sku.sku;
    productDiv.morph({
      width: '45px'
    }, {
      duration: 0.5,
      afterFinish: moveProductInView
    });
    
    Shop.redrawMinibag();
  }, delay);
};

Shop.deleteFromMinibag = function(removeLink) {
  var productDiv = $(removeLink).up('div.product');
  
  gucci.Minibag.removeProduct(productDiv.sku, {
    onRemoved: function() {
      new Effect.Parallel([
        new Effect.Move(productDiv, { y: 64,  sync: true }),
        new Effect.Opacity(productDiv, { from: 1.0, to: 0.1 })
      ], { 
        duration: 1.6,
        transition: Gucci.cubic,
        afterFinish: function() {
          productDiv.setOpacity(0).morph('width: 1px', { //Safari needs at least 1px to prevent flickering
            duration: 0.5,
            afterFinish: function() {
              productDiv.remove();
              Shop.redrawMinibag();
            }
          });
        }
      });
    }
  });
};

Shop.goToAndOpen = function(href) {
  if (Shop.isRTW()) {
    RTW.gotoAndOpen(href);
    return;
  }
  var reference = href.split('#');
  if (reference[0].charAt(reference[0].length-1) != '/') {
    reference[0] += '/';
  }
  if (location.pathname.indexOf(reference[0]) != -1 || (location.pathname + '/').indexOf(reference[0]) != -1) {
    Shop.showProductFromDeeplink(reference[1]);
  //NOTE: there is maybe a weird encoded url-snipped in the location.pathname
  // so try to match it anyway.
  } else if(location.pathname.replace(/%2D/g, "-").indexOf(reference[0].replace(/%2D/g, "-")) != -1) {
      Shop.showProductFromDeeplink(reference[1]);
  } else {
    location.href = href;
  }
};

Shop.moveIntoView = function(lightbox) {
  var windowWidth   = Position.getPageSize().window.width;
  var windowLeft    = Position.scrollX();
  var windowRight   = windowLeft + windowWidth;
  var lightboxLeft  = Position.page(lightbox)[0] - 32 + windowLeft;
  var lightboxRight = lightboxLeft + 780 + 65 + 180;

  if (lightboxRight > windowRight) {
    if (lightboxRight > Position.getPageSize().page.width) {
      setTimeout(function() {
        new Effect.HScrollTo(lightboxRight - windowWidth, { duration: 0.5, transition:Gucci.cubic });
      }, 1000);
    } else {
      new Effect.HScrollTo(lightboxRight - windowWidth, { queue:Shop.queue, duration: 0.5, transition:Gucci.cubic });
    }
  } else if (lightboxLeft  < windowLeft) {
    new Effect.HScrollTo(lightboxLeft, { queue:Shop.queue, duration: 0.5, transition:Gucci.cubic });
  }
};

Shop.openLightbox = function(lightbox, thumbId) {
  if(!Shop.isOpen(lightbox)) {
    this.moveIntoView(lightbox);
    lightbox.down('div.shadow-right').setStyle({visibility:'hidden'});
    
    lightbox.down('div.product-image').update();
    lightbox.down('div.product-image').setStyle({right:'260px'});
    lightbox.down('div.details-wrapper').setStyle({right:'0px'});
    lightbox.down('div.shopper-wrapper').setStyle({right:'-260px'});
    lightbox.down('div.details').update();
    
    new Effect.Parallel([
      new Effect.Morph(lightbox, {
        style: { width: '780px' },
        sync: true
      }),
      new Effect.Morph(lightbox.down('div.container'), {
        style: { width: '780px' },
        sync: true
      })
    ].concat(Gucci.scaleLayout(520)), {
      transition: Gucci.cubic,
      duration: 1.7,
      queue: Shop.queueLast,
      afterUpdate: function() {
        //lightbox.down().setStyle({width:lightbox.offsetWidth+'px'});
      },
      afterFinish: function() {
        lightbox.down('div.shadow-right').setStyle({visibility:'visible'});
        Shop.adjustLayoutWidth();
      }
    });
    
    Shop._lightboxes[lightbox.id].open = true;
  }
};

Shop.closeLightbox = function(lightbox) {
	//Close SendToAFriend if it is below this lightbox
	if (lightbox.down('#send_to_a_friend')) Shop.hideSendToAFriend(true);

  if (this.isCatalog) {
    Catalog.closeLightbox(lightbox);
    return;
  }
  if (!Shop.isOpen(lightbox)) {
    return;
  }
  if ($('iconoverlay_container'))
	Shop.hideIconOverlay();
  var lightboxObject = Shop._lightboxes[lightbox.id];
    
  Shop.deactivateProduct(Shop.currentProduct(lightbox));
  
  if (Engine.isMSIE6) { //HACK ie6
    var selects = $$('select');
    for (var i = 0; i < selects.length; i++) {
      selects[i].setStyle({visibility:'hidden'});
    }
  }
  lightbox.down('div.shadow-right').setStyle({visibility:'hidden'});
  
  var layoutDelta = 520; // without variants the get closed before... + lightbox.down('div.variants').offsetWidth;
  setTimeout(function() {
    new Effect.Parallel([
      new Effect.Morph(lightbox, {
        style: { width: '260px' },
        sync: true
      }),
      new Effect.Morph(lightbox.down('div.container'), {
        style: { width: '260px' },
        sync: true
      })
      ].concat(Gucci.scaleLayout(-layoutDelta)), {
      transition: Gucci.cubic,
      duration: 1.3,
      queue: Shop.queueLast,
      afterFinish: function() {
        lightbox.down('div.shadow-right').setStyle({visibility:'visible'});
        if(Engine.isMSIE6) {
          lightbox.setStyle('width: 260px');
          lightbox.down('div.container').setStyle('width: 260px');
        }
        Shop.adjustLayoutWidth();
      }
    });
  }, 500);
  
  Shop.lightboxToActiveStyle.set(lightbox.id, null);
  lightboxObject.open = false;
};

Shop.closeAllLightboxes = function(afterFinish, sort) {
  var lightboxes = [];
  var effects = [];
  var layoutDeltaSum = 0;
  var lightboxKeys = $H(Shop._lightboxes).keys();
  
  for (var i = 0; i < lightboxKeys.length; i++) {
    if(Shop._lightboxes[lightboxKeys[i]].open) {
      lightboxes.push($(lightboxKeys[i]));
    }
  }
  
  if (lightboxes.length == 0) {
    if (Object.isFunction(afterFinish)) {
      afterFinish(sort);
    }
    return;
  }
  
  for (i = 0; i < lightboxes.length; i++) {
    var lightboxObject = Shop._lightboxes[lightboxes[i].id];

    Shop.deactivateProduct(Shop.currentProduct(lightboxes[i]));
    layoutDeltaSum += (520 + lightboxes[i].down('div.variants') ? lightboxes[i].down('div.variants').offsetWidth : 0);
    
    effects.push(new Effect.Morph(lightboxes[i], {
      style: { width: '260px' },
      sync: true
    }));
    effects.push(new Effect.Morph(lightboxes[i].down('div.container'), {
        style: { width: '260px' },
        sync: true
    }));
    Shop._lightboxes[lightboxes[i].id].open = false;
    
    lightboxes[i].down('div.shadow-right').setStyle({visibility:'visible'});
  }
  
  if (Engine.isMSIE6) { //HACK ie6: Attempt to hide all <select>s in IE6 (or else the are drawn on top of _closed_ lightboxes)
    var selects = $$('select');
    for (i = 0; i < selects.length; i++) {
      selects[i].setStyle({visibility: 'hidden'});
    }
  }
  
  new Effect.Parallel(effects.concat(Gucci.scaleLayout(-layoutDeltaSum)), {
    transition: Gucci.cubic,
    duration: 1.3,
    queue: Shop.queueLast,
    afterFinish: function() {
      Shop.adjustLayoutWidth();
      if (Object.isFunction(afterFinish)) {
        afterFinish(sort);
      }
    }
  });
};

Shop.loadVisibleThumbs = function(){
  if (this._loaderPause) {
    return;
  }
  if (this._loaderTimeout) {
    clearTimeout(this._loaderTimeout);
  }
  this._loaderTimeout = setTimeout(function(){
    var visibles = Shop.getVisiblePanels();
    for (var i = 0; i < visibles.length; i++) {
      Shop.loadVisibleThumbsFromLightbox(visibles[i], i);
    }
  },100);
};

Shop.loadVisibleThumbsFromLightbox = function(lightbox, index) {
  var thumbs = lightbox.select('div.products img');
  for (var i = 0; i < thumbs.length; i++) {
    Shop.loadVisibleThumb(thumbs[i], index, i);
  }
};

Shop.loadVisibleThumb = function(thumb, index, index2) { 
 var product = Shop.thumbs[thumb.parentNode.id.split('_')[1]]; 
 var darkener = thumb.next(); 
 if (!product || !darkener) {
   return; 
 } 
 //thumb.parentNode.hasClassName('highlight') ? darkener.setOpacity(0.001) : darkener.setOpacity(0.3);

 var imageurl=""; 
 var hasImage=false; 
 if (product.thumburl!="") { 
  imageurl=product.thumburl; 
  hasImage=true; 
 }
 else 
 { 
  imageurl=this.photoUnavailableThumbUrlForLightbox($(thumb.parentNode).up("div.lightbox")); 
 } 
 if ((thumb.src==imageurl) || !(/empty.gif$/.test(thumb.src))) { 
  return; 
 } 
 thumb.setStyle({ position: 'relative',left: '-260px' });

 if (hasImage) { 
  Loader.load(imageurl, { onComplete: function(img){ thumb.setStyle({ position: 'relative', left:'0px'}).setOpacity(0); 
  thumb.src = img; 
  new Effect.Opacity(thumb, { from:0, to:1, delay: (index + index2)/25,
   transition:Gucci.cubic, duration: 1.3 }); 
   } 
  }); 
 } else { 
  var thumbContainer=thumb.parentNode;
  Shop.changeThumbnail(thumbContainer).setStyle({left: "0px"});
 } 
};

Shop.initializeThumbsLoader = function(){
  if (Shop.isRTW()) {
    return;
  }
  Event.observe(window,'scroll',this.loadVisibleThumbs.bindAsEventListener(this));
  Event.observe(window,'scroll',this.createVariationSlidersForVisiblePanels.bindAsEventListener(this));
  Event.observe(window,'resize',this.loadVisibleThumbs.bindAsEventListener(this));
  Event.observe(window,'beforeunload',this.unloadThumbs.bindAsEventListener(this));
  this.createVariationSlidersForVisiblePanels();
};

Shop.createVariationSlidersForVisiblePanels = function() {
  if (Shop.createVariationSlidersTimeout) {
    clearTimeout(Shop.createVariationSlidersTimeout);
  }
  Shop.createVariationSlidersTimeout = setTimeout(function() {
    var visiblePanels = Shop.getVisiblePanels();
    
    for (var i = 0; i < visiblePanels.length; i++) {
      var lightbox = visiblePanels[i];
      Shop.insertVariationSliderForPanel(lightbox);
      Shop.updateVariationSlidersForPanel(lightbox);
    }
  }, 500);
};

Shop.unloadThumbs = function() {
  var thumbs = $$('div.products img');
  for (var i = 0; i < thumbs.length; i++) {
    thumbs[i].src = Shop.THUMB_EMPTY;
  }
};

Shop.initializeThumbsFromProductList = function(list, highlight) {
  if (Shop.isRTW()) {
    return;
  }
  list = list || $H(gucci.DataHelper.getPanelsDisplayGroups());
  var thumbs = $$('div.lightbox div.container div.products img');
  Shop.thumbs = [];
  
  // care about the emtpy slots
  if(highlight) {
    for (var index = list.size(); index < thumbs.length; index++) {        
      var container = $(thumbs[index].parentNode);
      var darkener = $(thumbs[index].next());
      container.setOpacity(0);
      container.removeClassName('highlight');
      new Effect.Opacity(container,{from:0,to:1.0});
      new Effect.Opacity(darkener, {from:0,to:0.7});
    }
  } else {
    for(var index = list.size(); index < thumbs.length; index++) {   
      var container = $(thumbs[index].parentNode);     
      new Effect.Opacity(container,{from: 1,to: 0,
        afterFinish: function(effect) {
          effect.element.setOpacity(1);
          effect.element.addClassName('highlight');
		  if (!Engine.isMSIE8)	
          	effect.element.down('div.darkening').setOpacity(0.001);
        }
      });
    }
    highlight = list.clone();
  }
  
  // care about the filled slots
  list = list.toArray();
  for (var index = 0; index < list.length; index++){
    var listitem = list[index];
    var displayGroup = listitem[1];
    var link_id = displayGroup.link_id;
    var container = $(thumbs[index].parentNode);
    var darkener = $(thumbs[index].next());
    
    var shouldHighlight = highlight.get(listitem[0]) != null;

    if (!container.hasClassName('highlight') && shouldHighlight) {
      new Effect.Opacity(container,{from: 1,to: 0,
        afterFinish: function(effect) {
          effect.element.setOpacity(1);
          effect.element.addClassName('highlight');
		  if (!Engine.isMSIE8)
          	effect.element.down('div.darkening').setOpacity(0.001);
        }
      });
    } else {
      if (container.hasClassName('highlight') && !shouldHighlight) {
        container.setOpacity(0);
        container.removeClassName('highlight');
        new Effect.Opacity(container,{from:0,to:1.0});
        new Effect.Opacity(darkener, {from:0,to:0.7});
      }
    }
    if (displayGroup != null) {
      Shop.DomIdToDisplayGroup.set(container.id, {
        link_id: link_id,
        displayGroup_id: displayGroup.displayGroup_id,
        currentStyle: displayGroup.leadStyle.style_number,
        currentThumbIndex: 0
      });
      Shop.thumbs.push({
        id:         displayGroup.leadStyle.style_number,
        stylegroup: displayGroup.link_id,
        thumburl:   displayGroup.leadStyle.images.panel_thumb
      });
    }
    // clean up
    darkener = null;
	container = null;
  }
  
  Loader.reset();
  
  setTimeout(function(){
    this._loaderPause = false;
    this.loadVisibleThumbs();
  }.bind(this),1050);
};

Shop.reorderToSort = function(sort) {
  this._loaderPause = true;
  this.closeAllLightboxes(Shop.removeUnavailableThumbs, sort);
};

Shop.removeUnavailableThumbs = function(sort) {
  // remove thumbnail unavailable -> because otherwise there would be no image for further processing
  var allunavailable = $$('div.panel-thumb-unavailable'); 
  var newThumb = null; 
  var oldLeft  = 0;
  var thumbContainer = null;
  for (var i = 0; i < allunavailable.length; i++) {
      thumbContainer = allunavailable[i].up('div.thumbnail');
      oldLeft = allunavailable[i].getStyle('left');
	  newThumb = new Element('img', {
	      src: Shop.THUMB_EMPTY
	    }).setStyle({
	      position: 'relative',
	      left: oldLeft
	    });
	  thumbContainer.insert({top: newThumb});
	  allunavailable[i].remove();
  }     
  Shop.reorderSort2(sort);
};

Shop.reorderSort2 = function(sort) {
  var products = sort == 'all' ? null : gucci.DataHelper.getOrderedDisplayGroups(sort);
  var allPanels = $$('div.lightbox'); 
  
  for (var i = 0; i < allPanels.length; i++) {
    var thumbs = allPanels[i].select('div.products img');
    for (var k = 0; k < thumbs.length; k++) {
      Shop.reorderToSortForThumb(thumbs[k], ((k + 1) == thumbs.length) && ((i + 1) == allPanels.length), Shop.reorderSort3, products, sort);
    }
  }
};

Shop.reorderSort3 = function(products, sort) {
  if (sort == 'all') {
    Shop.initializeThumbsFromProductList();
  } else {
    Shop.initializeThumbsFromProductList(products.allProducts, products.withCategory);
  }
  Shop.updateVariationSliders();
};

Shop.reorderToSortForThumb = function(thumb, last, afterLastFinish, products, sort) {
  new Effect.Move(thumb, {
    x: Shop.options.thumbnailWidth,
    delay: Math.random()/4,
    transition:Gucci.cubic,
    duration: 0.5,
    afterFinish: function(){
      thumb.src = Shop.THUMB_EMPTY;
      if (last) {
        afterLastFinish(products, sort);
      }
    }
  });
};

Shop.getVisiblePanels = function() {
  var visibles = [];
  var w = Position.getPageSize().window.width;
  var lightboxes = $$('div.lightbox');
  //.each(function(lightbox){
  for (var i = 0; i < lightboxes.length; i++) {
    var lightbox = lightboxes[i];
    var x = Position.page(lightbox)[0];
    if (x >= 0 && x < w) {
      visibles.push(lightbox);
    } else {
      if ( (x + 780) >= 0 && (x + 780) < w ) {
        visibles.push(lightbox);
      }
    }
  }
  return visibles;
};

Shop.selectSort = function(element) {
  //handle "category_XXXX" and "end_category_"
  var sort = element.id.split('_');
  sort = sort[sort.length-1];
  if (sort == "")
	  sort = "all";  
  if(Shop.currentSort == sort) return;
  Shop.currentSort = sort;

  $$('ul.filters-full a').invoke('removeClassName', 'active');
  $$('ul.filters-full a#category_' + sort).invoke('addClassName', 'active');
  $$('ul.filters-full a#end_category_' + sort).invoke('addClassName', 'active');
  if(Position.scrollX()>0) {
    new Effect.HScrollTo(0, { afterFinish: function () {Shop.reorderToSort(sort);} });
  } else {
    Shop.reorderToSort(sort);
  }
};

/*
Property: addToBag
  Called by onclick event to add stuff to minibag or waitlist.

Note:
  The "Bag" the wrapper for 

Parameters:
  link - DOMElement
  target - String - "minibag" or "waitlist"
*/
Shop.addToBag = function(link) {
  var lightbox = $(link).up('div.lightbox');
  if (Shop.isBusy(lightbox)) {
    return;
  }
  Shop.setBusy(lightbox);
  $(link).addClassName('busy');
  $(link).setStyle('height: 13px;');
  
  var activeStyle = Shop.lightboxToActiveStyle.get(lightbox.id);
  var displayGroupInfo = Shop.DomIdToDisplayGroup.get(Shop._lightboxes[lightbox.id].activeProduct.up('div.thumbnail').id);
  var displayGroup = gucci.DataHelper.getPanelDisplayGroup(displayGroupInfo.displayGroup_id);
  var product = displayGroup.getProduct(activeStyle);
  var sku = (product.skus.length > 1) ? product.getSku(Shop.getSkuFromSelectedSize(lightbox, activeStyle).get('sku')) : product.skus[0];
    
  var availability = sku || Shop.getDefaultAvailability();
  var availstatus = availability.status.replace(/\s/g,'_');
  
  
  var callbacks = {
    onSuccess: Shop.addToBagSuccessful,
    onFailure: Shop.addToBagFailure,
    args: lightbox
  };
  
  gucci.Minibag.addProduct(sku, callbacks);
  
  Shop._goingToBag = false;
};

Shop.addToBagSuccessful = function(lightbox, sku) {
  Shop.addToBagEffect(lightbox, sku);
  
  var activeStyle = Shop.lightboxToActiveStyle.get(lightbox.id);
  var c = lightbox.down('div#details_' + lightbox.id + '_' + activeStyle +' div.configuration-info');
  
  var term = sku.status == "backorder" ? Gucci.getTerm('waitlistitem added') : Gucci.getTerm('item added');
  c.down('p.availability').update(term);
  c.down('div.addtobag').hide();
  c.down('div.backorder').hide();
  c.down('div.checkout').show().down('div.content').update(Gucci.getTerm('checkout'));
  c.down('p.info').hide();
  
  Shop.setIdle(lightbox);
  
  gucci.Minibag.initialize();
};

Shop.addToBagFailure = function(lightbox, sku) {
  var buttons = $$('div.button');
  for (var i = 0; i < buttons.length; i++) {
    buttons[i].setStyle('height: 24px;');
  }
  
  var activeStyle = Shop.lightboxToActiveStyle.get(lightbox.id);
  var c = lightbox.down('div#details_' + lightbox.id + '_' + activeStyle +' div.configuration-info');
  
  if (sku.status == "backorder") {
    c.down('div.backorder').removeClassName('busy');
    c.down('div.addtobag').hide();
  } else {
    c.down('div.addtobag').removeClassName('busy');
    c.down('div.backorder').hide();
  }
  
  var errorContainer = c.down('div.form-error');
  if (!errorContainer) {
    c.insert('<div class="form-error" style="margin-left: 19px; margin-right: 20px;">' + Gucci.getTerm('add bag failure') + '</div>');
    errorContainer = c.down('div.form-error');
    new Effect.Opacity(errorContainer, {
      from: 1,
      to: 0,
      delay: 4,
      transition: Gucci.cubic,
      duration: 1,
      afterFinish: function() {
        errorContainer.remove();
      }
    });
  }
  Shop.setIdle(lightbox);
};

Shop.disableOption = function(theSelect, j) {
  theSelect.options[j].disabled = true;
  theSelect.options[j].style.color = "Gainsboro";
};

Shop.enableOption = function(theSelect, j) {
  theSelect.options[j].disabled = false;
  theSelect.options[j].style.color = "#000000";
};

Shop.gotoShoppingBag = function(link) {
  Shop._goingToBag = true;
  location.href = getSecureBaseURL() + '/checkout/shopping_bag.asp';
};

//NOTE: deprecated
Shop.submitBackorder = function(identifier) {
  Shop.addToBag(identifier);
};

/************ DEPRECATION LAYER ************/
Shop.initializeMiniBagFromCookies = Shop.initializeMinibag;

if (document.location.toString().indexOf('/checkout/') && typeof salenav!="undefined" && salenav)
	document.write('<style type="text/css" media="screen"/> #personal_information.form p.information { color: #b90202; }</style>');

