var Shop = {
  _duration: 0.5,
  _lightboxes: {},
  _avails: {},
  _defaultAvail: 'unavailable',
  currentSort: 'all',
  thumbs: [],
  queue: { position:'end', scope:'shop' },
  queueLast: { position:'with-last', scope:'shop' },

  getS7Base: function() {
  return('http://www.sideration.org/');
   
 },

  initialize: function(){
    var s7Base = Shop.getS7Base();
    Shop.options =  Object.extend({
      thumbTemplate: s7Base + '#{style}?$thumbnail$&crop=56,300,1038,1334&op_sharpen=1',
      lowlightTemplate: s7Base + '#{style}?$thumbnail$&crop=56,300,1038,1334&op_sharpen=1&layer=1&src=Gallery/msk20&sizeN=3,2',
      thumbStyleFormat: /^[^_]+_[^_]+_(.*)$/,
      thumbnailWidth: 130
    }, arguments[0] || {});

    $$('div.lightbox').each( function(lightbox, i) {
      lightbox.setAttribute('id', 'lightbox_' + i);
      new Insertion.Bottom(lightbox.down('div.container'),
        '<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
      }
    });

    $$('div.lightbox div.products img').each( function(img,idx){
      img.parentNode.addClassName('highlight');
      img.parentNode.setAttribute('id','thumbnail_' + idx);
      Event.observe(img, 'click', function(){
        Shop.showProduct(this);
      }.bindAsEventListener(img));
    });

    var lastLightbox = $$('div.lightbox').last();
    var numberOfProducts = 0;
    ['format-2x3','format-2x2','format-1x3'].each(function(style,idx){
      if(lastLightbox.hasClassName(style)) numberOfProducts = [6,4,3][idx];
    });
    (numberOfProducts - lastLightbox.getElementsBySelector('div.thumbnail').length).times(function(){
      new Insertion.Bottom(lastLightbox.down('div.products'), '<div class="thumbnail"><img src="/images/empty.gif" alt="" /></div>');
    });
  },

  initializeCatalog: function(){
    var s7Base = Shop.getS7Base();

    this.isCatalog = true;

    Gallery.Zoomer.expand = false;

    Shop.options =  Object.extend({
      thumbTemplate: s7Base + '#{style}?$thumbnail$&crop=56,300,1038,1334&op_sharpen=1',
      lowlightTemplate: s7Base + '#{style}?$thumbnail$&crop=56,300,1038,1334&op_sharpen=1&layer=1&src=Gallery/msk20&sizeN=3,2',
      thumbStyleFormat: /^[^_]+_[^_]+_(.*)$/,
      thumbnailWidth: 130
    }, arguments[0] || {});

    $$('div.lightbox').each( function(lightbox, i) {
      lightbox.setAttribute('id', 'lightbox_' + i);
      new Insertion.Bottom(lightbox.down('div.container'),
        '<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
      }
    });
  },

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

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

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

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

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

  printStyle: function(lightbox, style) {
    this.printItems = this.getStyles(lightbox, style);
    var url = "/" + getCookie('site') + "/templates/print.html";
    this.printWindow = window.open(url,'printStyle', 'height=520,width=540,resizable=yes');
  },

  printCallback: function() {
    var w = this.printWindow;
    var d = w.document.getElementById("mainDescription");
    d.innerHTML = this.printItems.first().data.description;
    var d = w.document.getElementById("productShot");
    d.src = this.printItems.first().images.front.full;
    for(var i = 0; i < this.printItems.length && i < 9 ; i++) {
      d = w.document.getElementById("variationDescription"+i);
      d.innerHTML = this.printItems[i].data.variationDescription;
      d = w.document.getElementById("style"+i);
      d.innerHTML = this.printItems[i].data.style;
      d = w.document.getElementById("price"+i);
      var p = this.printItems[i].data.price;
      if(p) {
        d.innerHTML = new Template(Gallery.getTerm('price-template')).evaluate({price:p});
      }
      else {
        d.innerHTML = "";
      }
      d = w.document.getElementById("group"+i);
      d.style["display"] = "block";
    }
  },

  getAvailabilityBySku: function(sku){
    var ret = null;
    for(style in Shop._avails){
      Shop._avails[style].each(function(s){
        if(s.sku==sku) ret = s;
      });
    }
    return ret;
  },

  getAvailabilityBySize: function(styleData, size){
    var sku = null;

    styleData.sku.each(function(s){
      if(s.size==size) sku = s.sku;
    });

    return sku ? Shop.getAvailabilityBySku(sku) : null;
  },

  selectStyle: function(link, style){
  
    lightbox = $(link).up('div.lightbox');

    //if(this.isBusy(lightbox)) return;
    //this.setBusy(lightbox);

    var data = this.getStyle(lightbox, style);
    Shop._lightboxes[lightbox.id].activeStyleData = data;

    var html = $(link).innerHTML;
    lightbox.down('div.active-style').update(html);

    if(data.sku){
      if(data.sku.length > 1) {
        lightbox.down('select.size-select').selectedIndex = 0;
        this.hideAvailabilityInformation(lightbox);
      } else {
        var s = data.sku.first();
        if(s) {
          this.updateAvailabilityInformationBySku(lightbox, s.sku);
        }
      }
    }
    this.updateZoomerWithImages(lightbox, data.images);
    this.showDetails(lightbox);

    lightbox.down('div.style-list').getElementsBySelector('div.style').each(function(s){
      s.removeClassName('current-style');
    });
    $(link).addClassName('current-style');
    if(hbx && hbxProductView) {
      var styleGroupStyle = Shop._lightboxes[lightbox.id].styles[0].style;
      var hbxx=new Object();
      hbxx.pr=style;
      hbxx.bd='Gallery';
      hbxx.ca=hbx.ca;
      hbxx.pn='style view';
      hbxx.mlc=hbx.mlc + '/' + styleGroupStyle + '/' + style;
      hbxProductView(hbxx);
    }
  },

  selectSize: function(element){
    if($(element.selectedIndex)==0) {
      element.selectedIndex = element.oldSelectedIndex;
      return;
    }
    lightbox = $(element).up('div.lightbox');
    element.oldSelectedIndex = element.selectedIndex;
    this.updateAvailabilityInformationBySize(lightbox, $F(element));
  },

  getSize: function(lightbox){
    var select = lightbox.down('select.size-select');
    if(!select) return null;
    return $H({
      sku: $F(select),
      size: select.options[select.selectedIndex].text
    });
  },

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

  updateAvailabilityInformationBySize: function(lightbox, size){
    var styleData = Shop._lightboxes[lightbox.id].activeStyleData;
    var avail = this.getAvailabilityBySize(styleData, size);
    if(!avail) {
      avail = {};
      avail.status = Shop._defaultAvail;
      avail.info   = Gallery.getTerm(Shop._defaultAvail);
    }
    Shop.updateAvailabilityInformation(lightbox, avail);
  },

  updateAvailabilityInformationBySku: function(lightbox, sku){
    var avail = this.getAvailabilityBySku(sku);
    if(!avail) {
      avail = {};
      avail.status = Shop._defaultAvail;
      avail.info   = Gallery.getTerm(Shop._defaultAvail);
    }
    Shop.updateAvailabilityInformation(lightbox, avail);
  },

  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':
        break;

      case 'possibly available':
        break;

      case 'jewelry possibly available':
        break;

      case 'unavailable':
        shopper = false;
        break;
      case 'no threshold':
        shopper = false;
        break;
      case 'unknown sku':
        shopper = false;
    };

    var c = lightbox.down('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(Gallery.getTerm('add to bag'));
    c.down('div.backorder')[ backorder ? 'show' : 'hide']().removeClassName('busy').down('div.content').update(Gallery.getTerm('register for wait list'));
    c.down('p.info')[ shopper ? 'show' : 'hide']().update(Gallery.getTerm('personal shopper link'));
  },

  hideAvailabilityInformation: function(lightbox){
    var c = lightbox.down('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();
  },

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

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

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

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

    lightbox.down('div.product-image').addClassName('loading');

    if(!Shop._lightboxes[lightbox.id].zoomer){
      this.updateZoomer(lightbox, fullUrl, zoomUrl, images);
      return;
    }

    if(Shop._lightboxes[lightbox.id].zoomer && Shop._lightboxes[lightbox.id].zoomer._zoomed) {
      Shop._lightboxes[lightbox.id].zoomer.zoomOutAndDestroy();
      delay = Gallery.Zoomer.ZOOM_OUT_SPEED + 0.01;
    } else if(Shop._lightboxes[lightbox.id].zoomer) {
      Shop._lightboxes[lightbox.id].zoomer.destroy();
    }

    new Effect.Opacity(lightbox.id+'_full_image',{
      delay:delay, from:1, to:0, transition:Gallery.cubic, afterFinish:function(){
      lightbox.down('div.product-image').update();
      if(!zoomUrl){
        Loader.cacheOrLoad(fullUrl,{ onComplete:function(){
          lightbox.down('div.product-image').update(
            '<img id="'+lightbox.id+'_full_image" src="'+fullUrl+'" alt="" style="opacity:0;filter:alpha(opacity=0)" />' +
            (images.front.unavailable ? ('<div class="product-image-unavailable">' + Gallery.getTerm('photo unavailable') + '</div>') : '')
          );
          new Effect.Opacity(lightbox.id+'_full_image',{from:0,to:1,transition:Gallery.cubic});
        }});
        return;
      }

      Loader.cacheOrLoad(fullUrl,{ onComplete:function(){
        var productImage = lightbox.down('div.product-image');
        productImage.update(
          '<div class="full_image_wrapper"><img id="'+lightbox.id+'_full_image" src="'+fullUrl+'" alt="" style="opacity:0;filter:alpha(opacity=0)" /></div>' +
          (images.front.unavailable ? ('<div class="product-image-unavailable">' + Gallery.getTerm('photo unavailable') + '</div>') : '')
        );
        new Effect.Opacity(lightbox.id+'_full_image',{from:0,to:1,transition:Gallery.cubic,afterFinish:function(){
          Shop._lightboxes[lightbox.id].zoomer = new Gallery.Zoomer(
            productImage,
            productImage.down('img'),
            new Date().getTime(),
            zoomUrl);
          Shop._lightboxes[lightbox.id].zoomer.setViews(images);
        }});
      }});
    }});
  },

  updateZoomer: function(lightbox, fullurl, zoomurl, images){
    lightbox = $(lightbox);
    if(!zoomurl){
      if(Shop._lightboxes[lightbox.id].zoomer) Shop._lightboxes[lightbox.id].zoomer.zoomOutAndDestroy();
      Shop._lightboxes[lightbox.id].zoomer = null;
      Loader.cacheOrLoad(fullurl,{ onComplete:function(){
        $(lightbox).down('div.product-image').update(
          '<img style="right:260px" id="'+$(lightbox).id+'_full_image" src="'+fullurl+'" alt="" />');
        new Effect.MoveRight(lightbox.id+'_full_image', -260, { initialRight:260, queue:Shop.queue, transition:Gallery.cubic, duration: 1.3 });
      }});
      return;
    }
    if(!Shop._lightboxes[lightbox.id].zoomer) {
      Loader.cacheOrLoad(fullurl,{ onComplete:function(){
        $(lightbox).down('div.product-image').update(
          '<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>');
        Shop._lightboxes[lightbox.id].zoomer = new Gallery.Zoomer(
          $(lightbox).down('div.product-image'),
          $(lightbox).down('div.product-image').down('img'),
          new Date().getTime(),
          zoomurl);
        if(images) Shop._lightboxes[lightbox.id].zoomer.setViews(images);
        new Effect.Move($(lightbox).down('div.product-image').down(), {
          x:260, queue:Shop.queue,
          transition:Gallery.cubic,
          duration: 1.3,
          afterFinish: function(effect){
            effect.element.setStyle({overflow:'',width:'auto'});
          }
        });
      }});
    } else {
      Loader.cacheOrLoad(fullurl,{ onComplete:function(){
        Shop._lightboxes[lightbox.id].zoomer.swap(
          new Date().getTime(),
          fullurl,
          zoomurl);
        if(images) Shop._lightboxes[lightbox.id].zoomer.setViews(images);
        new Effect.MoveRight(lightbox.id+'_full_image', -260, { initialRight:260, queue:Shop.queue, transition:Gallery.cubic, duration: 1.3 });
      }});
    }
  },

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

  deactivateProduct: function(product){
    if(!Shop.isActive(product)) return;

    var lightbox = $(product).up('div.lightbox');
    Shop._lightboxes[lightbox.id].activeProduct = null;
    Shop._lightboxes[$(lightbox).id].zoomer = null;

    Shop.showDetails(lightbox);
    var wrapper = lightbox.down('div.full_image_wrapper');
    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:Gallery.cubic, duration: 0.7 });
    }
    else
      new Effect.MoveRight($(lightbox.id+'_product_image').down('img'), 260, { queue:Shop.queue, transition:Gallery.cubic, duration: 0.7 });

    new Effect.Move(product, { queue:Shop.queueLast, x: -Shop.options.thumbnailWidth, transition:Gallery.cubic, duration: 0.7 });
  },

  showProduct: function(product){
    product = $(product);
    var lightbox = product.up('div.lightbox');

    if(Shop.isActive(product)) return;

    if(Shop.isBusy(lightbox)) return;

    Gallery.setPageFragmentIdentifier(Shop.getProductInfo(product.up()).id);

    Shop.deactivateProduct(Shop.currentProduct(lightbox));
    Shop.hideSizeGuideByLightbox(lightbox);

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

    Shop.setBusy(lightbox);

    new Effect.Event({ afterFinish:function(){
      new Ajax.Request(
        '/'+getCookie('site')+'/product-shots/'+getCookie('language')+'/'+
		         getCookie('site')+'/'+Shop.getProductInfo(product.up()).stylegroup+'.asp', {
         parameters: 'lightbox=' + lightbox.id + '&style=' + Shop.getProductInfo(product.up()).id,
         onComplete: function(){
           Shop.setIdle(lightbox);
           Shop.activateProduct(product);
         },
         onException: function(transport, exception){
           Shop.lastException = $H(exception);
         }
      });
    }, queue:Shop.queue });
  },

  showProductByStyle: function(style){
    var idx = null;
    style = style.substr(style.length-17);
    Shop.thumbs.each(function(k,i){ if(k.id==style) idx = i });
    if(!idx) return;
    Shop.showProduct($('thumbnail_'+idx).down('img'));
  },

  showStyles: function(lightbox){
    if(this._lightboxes[lightbox.id].stylesActive) return;
    if(this.isBusy(lightbox)) return;
    this.setBusy(lightbox);

    if(Engine.isMSIE6 && lightbox.down('select.size-select'))
      lightbox.down('select.size-select').setStyle({visibility:'hidden'});

    var initialRight = 0;
    if(lightbox.down('div.size-guide')) lightbox.down('div.size-guide').hide();

    new Effect.Parallel([
      new Effect.MoveRight( lightbox.down('div.details-wrapper'), 260, { sync: true, initialRight: initialRight }),
      new Effect.MoveRight( lightbox.down('div.styles-wrapper'),  260, { sync: true, initialRight: initialRight-260 })
    ], { duration:0.7, transition:Gallery.cubic, afterFinish: function(){
      Shop.setIdle(lightbox)
    } });
    this._lightboxes[lightbox.id].stylesActive = true;
  },

  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');
  },

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

  showSizeGuide: function(link){
    var lightbox = $(link).up('div.lightbox');
    if(this.isBusy(lightbox)) return;

    if(Engine.isMSIE6 && lightbox.down('select.size-select'))
      lightbox.down('select.size-select').setStyle({visibility:'hidden'});

    lightbox.down('div.styles-wrapper').hide();
    lightbox.down('div.shopper-wrapper').hide();

    this.setBusy(lightbox);
    new Effect.MoveRight( lightbox.down('div.details-wrapper'), 260,
      { initialRight: 0, duration:0.7, transition:Gallery.cubic, afterFinish: function(){
        Shop.setIdle(lightbox);
      } });
  },

  hideSizeGuide: function(link){
    var lightbox = $(link).up('div.lightbox');
    if(this.isBusy(lightbox)) return;
    this.setBusy(lightbox);
    if(lightbox.down('div.details-wrapper').style.right != '260px') return;
    new Effect.MoveRight( lightbox.down('div.details-wrapper'), -260,
      { initialRight: 260, duration:0.7, transition:Gallery.cubic, afterFinish: function(){
        Shop.setIdle(lightbox);
         if(Engine.isMSIE6 && lightbox.down('select.size-select'))
            lightbox.down('select.size-select').setStyle({visibility:'visible'});
        lightbox.down('div.styles-wrapper').show();
        lightbox.down('div.shopper-wrapper').show();
      } });
  },

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

  showDetails: function(lightbox){
    if(!this._lightboxes[lightbox.id].stylesActive) {
      if(Engine.isMSIE6 && lightbox.down('select.size-select'))
        lightbox.down('select.size-select').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 }),
      new Effect.MoveRight( lightbox.down('div.styles-wrapper'),  -260, { sync: true, initialRight: initialRight-260 })
    ], { duration:0.7, transition:Gallery.cubic, afterFinish: function(){
      Shop.setIdle(lightbox);
      if(Engine.isMSIE6 && lightbox.down('select.size-select'))
        lightbox.down('select.size-select').setStyle({visibility:'visible'});
      if(lightbox.down('div.size-guide')) lightbox.down('div.size-guide').show();
    } });
    this._lightboxes[lightbox.id].stylesActive = false;
  },

  showShopper: function(link){
    var lightbox = $(link).up('div.lightbox');
    if(this.isBusy(lightbox)) return;
    this.setBusy(lightbox);

    if(Engine.isMSIE6 && lightbox.down('select.size-select'))
      lightbox.down('select.size-select').setStyle({visibility:'hidden'});

    lightbox.down('div.product-image').style.zIndex = 3;

    var delay = 0;
    if(Shop._lightboxes[$(lightbox).id].zoomer) {
      Shop._lightboxes[$(lightbox).id].zoomer.zoomOutAndPause();
      delay = Gallery.Zoomer.ZOOM_OUT_SPEED + 0.1;
    }

    var details = lightbox.down('div.details');

    if(lightbox.down('div.size-guide')) lightbox.down('div.size-guide').hide();
    lightbox.down('div.styles-wrapper').hide();

    var effects = [];
    if(this.isCatalog){
      lightbox.down('div.panel3-background').setOpacity(0).setStyle({left:'520px'});
      lightbox.down('div.details-wrapper').setStyle({left:'520px',right:'auto',width:'260px',overflow:'hidden'});
      effects.push(new Effect.Scale(lightbox.down('div.details-wrapper'),0,{ sync:true,
        scaleMode:{originalWidth:260,originalHeight:504}, scaleFrom:100, scaleY:false, scaleContent:false }));
      effects.push(new Effect.Opacity(lightbox.down('div.panel3-background'),{from:0,to:1,sync:true}));
    } else {
      lightbox.down('div.shopper').setStyle({visibility:'hidden'}).setOpacity(0);
      new Effect.Opacity(lightbox.down('div.details'),{from:1,to:0,transition:Gallery.cubic,duration:0.7});
      effects.push(new Effect.MoveRight( lightbox.down('div.product-image'),   260, { sync: true, initialRight: 260 }));
      effects.push(new Effect.MoveRight( lightbox.down('div.details-wrapper'), 260, { sync: true, initialRight: 0 }));
      effects.push(new Effect.MoveRight( lightbox.down('div.shopper-wrapper'), 260, { sync: true, initialRight: -260 }));
    }

    new Effect.Parallel(effects, { queue:'end', duration:0.7, delay:delay, transition:Gallery.cubic, afterFinish: function(){

      if(details.down('div.more-styles')) details.down('div.more-styles').hide();
      details.down('div.configuration-info').setStyle({height:'2px',overflow:'hidden'});

      if(details.down('div.size')) {
        details.down('select.size-select').hide();
        if(details.down('a.size-guide-link')) details.down('a.size-guide-link').hide();

        var size = lightbox.down('select.size-select');
        details.down('span.size-info').update(size.options[size.selectedIndex].text).show();
      }

      details.down('ul.functions').hide();
      details.down('ul.personal-shopper-headline').update(Gallery.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(lightbox.down('div.details-wrapper'), 100,{ sync:true,
            scaleMode:{originalWidth:260,originalHeight:504}, scaleFrom:0, scaleY:false, scaleContent:false }),
          new Effect.Scale(lightbox.down('div.shopper-wrapper'), 100,{ sync:true,
              scaleMode:{originalWidth:260,originalHeight:504}, scaleFrom:0, scaleY:false, scaleContent:false })
        ],{duration:0.7});
      } else {
        lightbox.down('div.shopper').setStyle({visibility:'visible'});
        new Effect.Parallel([
          new Effect.Opacity( lightbox.down('div.details'),{from:0,to:(Engine.isKHTML ? 0.99 : 1),sync:true}), //fix rendering bug in Safari 2.0
          new Effect.Opacity( lightbox.down('div.shopper'),{from:0,to:1.0,sync:true})
        ],{duration:0.7});
      }
      Shop.setIdle(lightbox)
    } });
  },

  closeShopper: function(link){
    var lightbox = $(link).up('div.lightbox');

    if(this.isCatalog && lightbox.down('div.panel3-background').getStyle('left')!='520px') {
      Catalog.closeShopper(link);
      return;
    }

    if(this.isBusy(lightbox)) return;
    this.setBusy(lightbox);

    if(Shop._lightboxes[$(lightbox).id].zoomer)
      Shop._lightboxes[$(lightbox).id].zoomer.unpause();

    var details = lightbox.down('div.details');

    var effects = [];

    if(this.isCatalog){
      effects.push(new Effect.Scale(lightbox.down('div.details-wrapper'), 0,{ sync:true,
        scaleMode:{originalWidth:260,originalHeight:504}, scaleFrom:100, scaleY:false, scaleContent:false }));
      effects.push(new Effect.Scale(lightbox.down('div.shopper-wrapper'), 0,{ sync:true,
        scaleMode:{originalWidth:260,originalHeight:504}, scaleFrom:100, scaleY:false, scaleContent:false }));
    } else {
      effects.push(new Effect.MoveRight( lightbox.down('div.product-image'),   -260, { sync: true, initialRight: 520 }));
      effects.push(new Effect.MoveRight( lightbox.down('div.details-wrapper'), -260, { sync: true, initialRight: 260 }));
      effects.push(new Effect.MoveRight( lightbox.down('div.shopper-wrapper'), -260, { sync: true, initialRight: 0 }));
    }

    new Effect.Parallel(effects, { duration:0.7, transition:Gallery.cubic, afterFinish:function(){

      if(details.down('div.more-styles')) details.down('div.more-styles').show();
      details.down('div.configuration-info').setStyle({height:'auto',overflow:'visible'});
      details.down('ul.functions').show();
      details.down('ul.personal-shopper-headline').hide();

      if(details.down('div.size')) {
        details.down('select.size-select').show();
        if(details.down('a.size-guide-link')) details.down('a.size-guide-link').show();
        details.down('span.size-info').hide();
      }

      Shop.setIdle(lightbox);
      lightbox.down('div.product-image').style.zIndex = 2;
      if(Engine.isMSIE6 && lightbox.down('select.size-select'))
        lightbox.down('select.size-select').setStyle({visibility:'visible'});
      if(lightbox.down('div.size-guide')) lightbox.down('div.size-guide').show();
      if(Engine.isKHTML) details.setOpacity(1);
      if(Shop.isCatalog) {
        new Effect.Opacity(lightbox.down('div.panel3-background'),{from:1,to:0,duration:0.7,
          afterFinish:function(){
            lightbox.down('div.panel3-background').setStyle({left:'-260px'});
            lightbox.down('div.container').setStyle({overflow:'hidden'});
            new Effect.Scale(lightbox.down('div.details-wrapper'), 100,{
              scaleMode:{originalWidth:260,originalHeight:504}, scaleFrom:0, scaleY:false,
              duration:0.7, scaleContent:false, afterFinish:function(){
                lightbox.down('div.details-wrapper').setStyle({left:'auto',right:'0',overflow:'visible'});
                lightbox.down('div.styles-wrapper').show();
              }
            });
          }
        });
      } else {
        lightbox.down('div.styles-wrapper').show();
      }
    } });
  },

  activateProduct: function(product){
    var lightbox = $(product).up('div.lightbox');
    Shop._lightboxes[lightbox.id].activeProduct = product;
    lightbox.down('div.details').show();
    new Effect.Move(product, {
      x: Shop.options.thumbnailWidth, queue:Shop.queueLast,
      transition:Gallery.cubic, duration: 1.3
    });
  },

  addToBagSuccessful: function(lightbox){
    if(lightbox==null) return;
    var lightbox = $(lightbox);
    if(lightbox==null) return;
    var data = Shop._lightboxes[lightbox.id].activeStyleData;
    this.addToMiniBag(lightbox, data);

    var details = lightbox.down('div.details');

    var c = lightbox.down('div.configuration-info');
    c.down('p.availability').update(Gallery.getTerm('item added'));
    c.down('div.addtobag').hide();
    c.down('div.backorder').hide();
    c.down('div.checkout').show().down('div.content').update(Gallery.getTerm('checkout'));
    c.down('p.info').hide();

    this.setIdle(lightbox);
  },

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

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

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

  submitShopper: function(form){
    var lightbox = $(form).up('div.lightbox');

    var submitData = '';

    if(Shop.isCatalog && !Shop._lightboxes[lightbox.id].activeStyleData){
      var page = lightbox.up('div.catalog-page').id.split('_')[1];
      submitData = Catalog.serialize(page, Catalog.getOpenStyleForPage(page));
    } else {
      var data = Shop._lightboxes[lightbox.id].activeStyleData;
      var sku = data.sku.length > 1 ? null : data.sku.first().sku;
      var size = this.getSize(lightbox);
      var avail = sku ? this.getAvailabilityBySku(sku) : this.getAvailabilityBySize(data, size.size);

      var extraData = $H({
        status: avail.status,
        sku: avail.sku,
        size: size ? size.size : ''
      });

      submitData = $H(data.data).toQueryString() + '&' + extraData.toQueryString();
    }

    new Ajax.Request(
      '/' + getCookie('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) + '&' + submitData + '&' + 'formType=contact'
      });
  },

  addCardPrice: function(link, lo, hi){
    var amount = link.value;
    amount = amount.replace(/[^0-9.-]/,'');

    amount = amount.length > 0 ? parseInt(amount) : lo;
    if(amount<lo) amount = lo;
    if(amount>hi) amount = hi;

    var lightbox = $(link).up('div.lightbox');
    var data = Shop._lightboxes[lightbox.id].activeStyleData;
    data.data.price = amount;
  },

  addToBag: function(link){
    var lightbox = $(link).up('div.lightbox');
    if(this.isBusy(lightbox)) return;
    this.setBusy(lightbox);

    $(link).addClassName('busy');

    var data = Shop._lightboxes[lightbox.id].activeStyleData;
    var sku = data.sku.length > 1 ? null : data.sku.first().sku;
    var size = this.getSize(lightbox);
    var avail = sku ? this.getAvailabilityBySku(sku) : this.getAvailabilityBySize(data, size.size);
    var style = data.style;
    var price = data.data.price;

    var extraData = $H({
      fullImageLink: data.images.front.full.replace("&", "&amp;"),
      status: avail.status,
      sku: avail.sku,
      size: size ? size.size : ''
    });

    this.bagAddHbx(lightbox, style, price);

    new Ajax.Request(
      '/' + getCookie('site') + '/mini_bag.asp', {
      parameters: 'lightbox=' + lightbox.id + '&' +
        $H(data.data).toQueryString() + '&' +
        extraData.toQueryString(),
      onException: function(transport, exception){
        Shop.lastException = $H(exception);
      }
      });
  },

  addToMiniBag: function(lightbox, data){
    var lightbox = $(lightbox);
    var delay    = 0;

    if(Shop._lightboxes[lightbox.id].zoomer) {
      Shop._lightboxes[lightbox.id].zoomer.zoomOut();
      delay = Gallery.Zoomer.ZOOM_OUT_SPEED*1000 + 10;
    }

    setTimeout(function(){
      new Insertion.Top('minibag-products',
        '<div class="product" style="display:none"><a href="#" onclick="' +
        "Shop.goToAndOpen('" + location.pathname + '#' + data.style + "'); return false" +
        '"><img src="' + data.images.front.miniThumb + '"/></a></div>');
      var div = $('minibag-products').down('div.product');
      div.setStyle({ position: 'relative', top: '56px' });
      lightbox.down('div.product-image').removeClassName('loading');
      new Effect.Parallel([
        new Effect.Move(div, { y:-56,  sync:true })
      ], { transition: Gallery.cubic, duration: 1.6,
        beforeSetup: function(){
          div.show();
        },
        afterFinish: function(){
          div.setStyle({ position: 'static', top: 'auto' });
        }
      });
      this.redrawMiniBag();
    }.bind(this), delay);
  },

  redrawMiniBag: function() {
    var products = $$('div#minibag-products div.product');
    if(products.length == 0){
      $('minibag-container').down('ul.shopping-bag').hide();
    } else {
      $('minibag-container').down('span.count').update('(' + products.length  + ')');
      $('minibag-container').down('ul.shopping-bag').show();
    }
  },

  initializeMiniBag: function(products) {
    products.each(function(product){
      new Insertion.Top('minibag-products',
        '<div class="product"><a href="#" onclick="Shop.goToAndOpen(\'' + product.href + '\'); return false"><img src="' + product.miniThumb + '"/></a></div>');
    });
    this.redrawMiniBag();
  },

  initializeMiniBagFromCookies: function() {
    var cookieMap = [], idx = 0, cookieData = null;

    while(++idx && (cookieData = getCookie('mb'+idx)))
      cookieMap.push(cookieData);

    var parsedData = cookieMap.map(function(p){
      var data = p.split('|');
      return({
        href: data[1],
        miniThumb: data[2]
      })
    });

    Shop.initializeMiniBag(parsedData);
  },

  goToAndOpen: function(href) {
    var reference = href.split('#');
    if(location.pathname == reference[0])
      Shop.showProductByStyle(reference[1]);
    else
      location.href = href;
  },

  moveIntoView: function(lightbox){
    lightbox = $(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;

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

  openLightbox: function(lightbox){
    lightbox = $(lightbox);

    if(!Shop.isOpen(lightbox)) {
      this.moveIntoView(lightbox);

      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.Scale(lightbox, 300, { scaleY:false, scaleContent:false, sync:true })
      ].concat(Gallery.scaleLayout(520)), {transition:Gallery.cubic, duration:1.7, queue:Shop.queueLast});

      Shop._lightboxes[lightbox.id].open = true;
    }
  },

  closeLightbox: function(lightbox){
    lightbox = $(lightbox);
    if(this.isCatalog) {
      Catalog.closeLightbox(lightbox);
      return;
    }

    if(!Shop.isOpen(lightbox)) return;

    if(Shop._lightboxes[$(lightbox).id].zoomer)
      Shop._lightboxes[$(lightbox).id].zoomer.zoomOutAndDestroy();

    Shop.deactivateProduct(Shop.currentProduct(lightbox));
    if(Engine.isMSIE6 && lightbox.down('select.size-select'))
      lightbox.down('select.size-select').setStyle({visibility:'hidden'});

    new Effect.Parallel([
      new Effect.Scale(lightbox, 100/3, { scaleY:false, scaleContent:false, sync:true })
    ].concat(Gallery.scaleLayout(-520)), { transition:Gallery.cubic, duration:1.3, queue:Shop.queueLast });
    Shop._lightboxes[lightbox.id].open = false;
  },

  closeAllLightboxes: function(){
    var lightboxes = [], effects = [];
    $H(Shop._lightboxes).keys().each( function(k) {
      if(Shop._lightboxes[k].open) lightboxes.push(k);
    });
    if(lightboxes.length == 0) return;

    lightboxes.each(function(lightbox){
      if(Shop._lightboxes[lightbox].zoomer) Shop._lightboxes[lightbox].zoomer.zoomOutAndDestroy();
      new Effect.Opacity(Shop._lightboxes[lightbox].activeProduct.parentNode,{from:0.0, to:1.0, duration:Shop._duration});
      Shop._lightboxes[lightbox].activeProduct = null;
      Shop._lightboxes[lightbox].open = false;
      if(Engine.isMSIE6 && $(lightbox).down('select.size-select'))
        $(lightbox).down('select.size-select').setStyle({visibility:'hidden'});
      effects.push(new Effect.Scale(lightbox, 100/3, { scaleY:false, scaleContent:false, sync:true }));
    });

    new Effect.Parallel(
      effects.concat(Gallery.scaleLayout(-520 * lightboxes.length)),
      { transition:Gallery.cubic, duration:1.2, queue:Shop.queue }
    );
  },

  loadVisibleThumbs: function(){
    if(this._loaderPause) return;
    if(this._loaderTimeout) clearTimeout(this._loaderTimeout);
    this._loaderTimeout = setTimeout(function(){
      var w = Position.getPageSize().window.width;

      var visibles = [];
      $$('div.lightbox').each(function(lightbox){
        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);
        }
      });

      visibles.each(function(lightbox,idx){
        lightbox.getElementsBySelector('div.products img').each(function(thumb,idx2) {
          var product = Shop.thumbs[thumb.parentNode.id.split('_')[1]];
          if(!product) return;
          var image = thumb.parentNode.hasClassName('highlight') ? product.thumburl : product.thumburl_lowlight;
          if(Loader.isQueued(image)) return;
          $(thumb).setStyle({ position: 'relative', left: '-260px' });
          Loader.load(image, {
            onComplete: function(img){
              $(thumb).setStyle({ position: 'relative', left: '0px'}).setOpacity(0);
              thumb.src = img;
              new Effect.Opacity(thumb, {
                from:0, to:1, delay:(idx+idx2)/25, transition:Gallery.cubic, duration: 1.3
              });
            }});
        });
      });
    },100);
  },

  initializeThumbsLoader: function(){
    Event.observe(window,'scroll',this.loadVisibleThumbs.bindAsEventListener(this));
    Event.observe(window,'resize',this.loadVisibleThumbs.bindAsEventListener(this));
    Event.observe(window,'beforeunload',this.unloadThumbs.bindAsEventListener(this));
    this.loadVisibleThumbs();
  },

  unloadThumbs: function(){
    $$('div.products img').each(function(image){ image.src = '/images/empty.gif' });
  },

  initializeThumbsFromProductList: function(list, highlight){

    var thumbTemplate =
       new Template(Shop.options.thumbTemplate);
    var lowlightTemplate =
       new Template(Shop.options.lowlightTemplate);
    var thumbs = $$('div.lightbox div.container div.products img');

    Shop.thumbs = [];

    highlight = highlight || list.collect(Prototype.K);

    if(highlight.length == list.length) highlight.push(null);

    list.inGroupsOf(thumbs.length).flatten().each( function(product, index) {
      var container = $(thumbs[index].parentNode);

      if(!container.hasClassName('highlight') && highlight.include(product)) {
        new Effect.Opacity(container,{from:1,to:0,duration:1.0,afterFinish:function(){
          container.setOpacity(1);
          container.addClassName('highlight');
        }});
      } else {
        if(container.hasClassName('highlight') && !highlight.include(product)) {
          container.setOpacity(0);
          container.removeClassName('highlight');
          new Effect.Opacity(container,{from:0,to:1,duration:1.0});
        }
      }
      if(product != null) {
        product.style = product.id.match(Shop.options.thumbStyleFormat)[1];

		if(product.thumburl) {
			thumburl = product.thumburl
		} else {
        var thumburl = thumbTemplate.evaluate(product);
        if(product.thumbOptions) thumburl = thumburl.split('?')[0] + '?' + product.thumbOptions;
		}
		if (product.lowlighturl) {
			lowlighturl = product.lowlighturl
		} else {
			var lowlighturl = lowlightTemplate.evaluate(product);
    		if(product.lowlightOptions) lowlighturl = lowlighturl.split('?')[0] + '?' + product.lowlightOptions;
		}

        Shop.thumbs.push({
          id:         product.style,
          stylegroup: product.id,
          thumburl:   thumburl,
          thumburl_lowlight: lowlighturl
        });
      }
    });

    Loader.reset();

    setTimeout(function(){
      this._loaderPause = false;
      this.loadVisibleThumbs();
    }.bind(this),1050);
  },

  reorderToSort: function(sort){
    this._loaderPause = true;
    this.closeAllLightboxes();

    var front = [], back = [], highlight = [];
    products.each( function(product) {
      ((sort == 'all' || (product.sorts && product.sorts.include(sort))) ? front : back).push(product);
    });

    highlight = front.clone();

    var visibles = [], w = Position.getPageSize().window.width, effects = [];
    $$('div.lightbox').each(function(lightbox){
      var x = Position.page(lightbox)[0];
      if(x>=0 && x<(w*1.5)) {
        visibles.push(lightbox)
      } else {
        if((x+780)>=0 && (x+780)<w) visibles.push(lightbox);
      }
    });
    visibles.each(function(lightbox){
      lightbox.getElementsBySelector('div.products img').each(function(thumb) {
        new Effect.Move(thumb, {
          x: Shop.options.thumbnailWidth, delay: Math.random()/4, transition:Gallery.cubic, duration: 0.5,
          afterFinish: function(){
            thumb.src = '/images/empty.gif'
          }
        });
      });
    });
    new Effect.Event({
      queue: 'end',
      afterFinish: function(){
        setTimeout(function(){
          Shop.initializeThumbsFromProductList(front.concat(back), highlight)
        }, 100);
      }
    });
  },

  selectSort: function(element,className){
    var sort = className || $(element).className.gsub(/\sactive/,'');
    if(Shop.currentSort == sort) return;
    Shop.currentSort = sort;
    $$('ul.filters-full a').each(function(a){ a.removeClassName('active') });
    $$('ul.filters-full a.'+sort).each(function(a){ a.addClassName('active') });
    if(Position.scrollX()>0)
      new Effect.HScrollTo(0,{ afterFinish:function(){ Shop.reorderToSort(sort) }});
    else
      Shop.reorderToSort(sort);
  },

  submitBackorder: function(link){
    var lightbox = $(link).up('div.lightbox');

    var data = Shop._lightboxes[lightbox.id].activeStyleData;
    var sku = data.sku.length > 1 ? null : data.sku.first().sku;
    var size = this.getSize(lightbox);
    var avail = sku ? this.getAvailabilityBySku(sku) : this.getAvailabilityBySize(data, size.size);
    var style = data.style;
    var price = data.data.price;

    var extraData = $H({
      fullImageLink: data.images.front.full.replace("&", "&amp;"),
      status: avail.status,
      sku: avail.sku,
      size: size ? size.size : ''
    });

    this.bagAddHbx(lightbox, style, price);

    new Ajax.Request(
      '/' + getCookie('site') + '/mini_bag.asp', {
      onSuccess: function(request){
        location.href = getSecureBaseURL() + '/checkout/shopping_bag.asp';
      },
      onException: function(transport, exception){
        Shop.lastException = $H(exception);
      },
      parameters:
        $H(data.data).toQueryString() + '&' +
        extraData.toQueryString()
      });
  },

  bagAddHbx: function(lightbox, style, price) {
    if(hbx && hbxCartAdd) {
      var t = null;
      if(siteStuff) {
        var site = siteStuff.getSiteFromCookie();
        var t = siteStuff.getSiteData(site);
      }
      if(t == null) {
        t = {};
        t.hbxStoreID = "unknown";
      }
      var styleGroupStyle = Shop._lightboxes[lightbox.id].styles[0].style;
      var hbxx=new Object();
      hbxx.pn  = 'cart add';
      hbxx.mlc = hbx.mlc + '/' + styleGroupStyle + '/' + style + '/add';
      hbxx.pr  = style;
      hbxx.qn  = '1'
      hbxx.bd  ='Gallery';
      hbxx.ca  = hbx.ca;
      hbxx.pc  = price;
      hbxx.sr  = t.hbxStoreID;
      hbxx.pr  = style;
      hbxCartAdd(hbxx);
    }
  },
  
  gotoShoppingBag: function(link){
    location.href = getSecureBaseURL() + '/checkout/shopping_bag.asp';
  }
};

var Catalog = {
    _tfx: null,
    _sfx: null,
    _loaded: false,
    _opened: {},
    _openedStyle: $H({}),
    _animation: { inProgress: false },
    _pos: [],
    _highlighted: 0,
    initialize: function() {
      this.options = Object.extend({
        hasOutlines: true
      }, arguments[0] || {});

      $$('div.catalog-page').each(function(p,idx){
        new Insertion.Bottom(p.down('div.lightbox'),
          '<div class="panel1-background"> </div>'+
          '<div class="panel2-background"> </div>'+
          '<div class="panel3-background"> </div>');
        p.down('div.details-button').hide().down('div.content').update(Gallery.getTerm('show outlines'));
      });

      Catalog.cachePagePositions();
      Event.observe(window,'resize',Catalog.cachePagePositions);

      if(this.options.hasOutlines) Event.observe(document,'mousemove', Catalog.onMouseMove);
    },
    cachePagePositions: function() {
      Catalog._pos = [];
      Position.prepare();
      $$('div.catalog-page').each(function(p,idx){
        var pos = Position.page(p);
        pos.push(pos[0]+780);
        pos.push(pos[1]+504);
        Catalog._pos.push(pos);
      });
    },
    onMouseMove: function(event){
      var pos   = [Event.pointerX(event), Event.pointerY(event)];
      var found = false;
      var old   = Catalog._highlighted;
      Catalog._pos.each(function(p,idx){
        if(p[0] <= pos[0] && p[1] <= pos[1] && p[2] >= pos[0] && p[3] >= pos[1]){
          var page = idx + 1;
          if(Catalog._highlighted != page){
            Catalog._highlighted = page;
            $('shop'+page+'_details').show();
          }
          found = true;
          throw $break;
        }
      });
      if(!found && Catalog._highlighted>0) Catalog._highlighted = 0;
      if(old != Catalog._highlighted && $('shop'+old+'_details'))
        $('shop'+old+'_details').hide();
    },
    turnPage: function(page) {
      if(!Catalog._loaded) return;
      if(Catalog._tfx && Catalog._sfx==page) return;
      var w = Position.getPageSize().window.width;
      var p = 301 + (780+65) * (page-1);
      if(Catalog._tfx) Catalog._tfx.cancel();
      Catalog._sfx = page;
      var d = (p - (w - 780)/2) - Position.scrollX();
      if(d == 0) return false;
      Catalog._tfx = new Effect.HScrollTo((p - (w - 780)/2),{
        duration: (Math.log(Math.abs(d*d))/10),
        transition: Gallery.cubic,
        afterFinish: function(){Catalog._tfx = null}
      });
      return true;
    },
    serialize: function(page,style){
      var price = _catalog_data[style].price == 0 ? '' : new Template(Gallery.getTerm('price-template')).evaluate({price:_catalog_data[style].price});
      return(
        'description=' + encodeURIComponent(_catalog_data[style].description) +
        '&displayStyle=' + encodeURIComponent(style) +
        '&price=' + encodeURIComponent(price) +
        '&catalog=85th-gucci' +
        '&productLink=' + (page+'_'+style.gsub(/\s/,'_')) +
        '&lightbox=lightbox_' + (page-1)
      );
    },

    disableMap: function(element){
      var map = element.up('div.catalog-page').down('img.map');
      if(!map) return;
      map.useMap = '#';
    },

    closePage: function(element){
      var page = element.up('div.catalog-page').id.gsub(/page_/,'');
      Catalog._opened[page] = false;
      var map = element.up('div.catalog-page').down('img.map');
      if(!map) return;
      map.useMap = '#map_page_'+page;
    },

    closeShopper: function(link){
      var lightbox = $(link).up('div.lightbox');

      Catalog.closePage(lightbox);

      new Effect.Parallel([
        new Effect.Scale(lightbox.down('div.details-wrapper'), 0,{ sync:true,
          scaleMode:{originalWidth:260,originalHeight:504}, scaleFrom:100, scaleY:false, scaleContent:false }),
        new Effect.Scale(lightbox.down('div.shopper-wrapper'), 0,{ sync:true,
          scaleMode:{originalWidth:260,originalHeight:504}, scaleFrom:100, scaleY:false, scaleContent:false })
      ],{ duration:0.5, queue:'end' });

      new Effect.Parallel([
        new Effect.Move( lightbox.down('div.panel1-background'),{x:-260,sync:true}),
        new Effect.Move( lightbox.down('div.panel2-background'),{x:-520,sync:true})
      ],{ duration:0.75, transition:Gallery.cubic, queue:'end', afterFinish: function(){
        lightbox.hide();
      } });
    },

    getOpenStyleForPage: function(page){
      for(style in Catalog._openedStyle){
        if(Catalog._openedStyle[style].page == page) return style;
      }
    },

    shop: function(page,style){
      if(Catalog._animation.inProgress) return;
      if(!Catalog._loaded) return;
      Catalog.turnPage(page);

      if(Catalog._opened[page]) return;

      if(Catalog._openedStyle[style]) {
        if(Catalog._openedStyle[style].page != page)
          Catalog.closeShop(Catalog._openedStyle[style].page);
      }

      Catalog._openedStyle[style] = { page: page };

      var lightbox = $('lightbox_'+(page-1));
      Catalog.disableMap(lightbox);

      if(!_catalog_data[style]) {
        alert('page '+page+', style '+style+' not found');
        return;
      }

      Catalog._opened[page] = true;

      Catalog._animation.inProgress = true;
      switch(_catalog_data[style].url){
        case 'shopper':
          var e = [];
          e.push(new Effect.Move(lightbox.down('div.panel1-background'),{x:260,sync:true}));
          e.push(new Effect.Move(lightbox.down('div.panel2-background'),{x:520,sync:true}));
          lightbox.down('div.product-image').hide();
          lightbox.setStyle({display:'block'});
          lightbox.down('div.details-wrapper').setStyle({left:'260px',width:'0px',overflow:'hidden'});
          lightbox.down('div.shopper-wrapper').setStyle({left:'520px',width:'0px',overflow:'hidden'}).show();
          new Effect.Parallel(e,{duration:1.5,transition:Gallery.cubic,
            afterFinish: function(){
              Catalog._animation.inProgress = false;
              new Ajax.Updater(
                'shop'+page+'_panel1',
                '/'+getCookie('site')+'/contact_item.asp', {
                  parameters: Catalog.serialize(page,style) + '&form=shopper',
                  onException: function(transport, exception){
                    Shop.lastException = $H(exception);
                  },
                  onComplete: function(r){
                    new Effect.Parallel([
                      new Effect.Scale(lightbox.down('div.details-wrapper'), 100,{ sync:true,
                        scaleMode:{originalWidth:260,originalHeight:504}, scaleFrom:0, scaleY:false, scaleContent:false }),
                      new Effect.Scale(lightbox.down('div.shopper-wrapper'), 100,{ sync:true,
                        scaleMode:{originalWidth:260,originalHeight:504}, scaleFrom:0, scaleY:false, scaleContent:false })
                    ],{ duration:1.1, transition:Gallery.cubic });
                  }
                }
              );
            }
          });
          break;

        case 'unavailable':
          var e = [];
          e.push(new Effect.Move(lightbox.down('div.panel1-background'),{x:260,sync:true}));
          e.push(new Effect.Move(lightbox.down('div.panel2-background'),{x:520,sync:true}));
          lightbox.down('div.product-image').hide();
          lightbox.setStyle({display:'block'});
          lightbox.down('div.details-wrapper').setStyle({left:'260px',width:'0px',overflow:'hidden'});
          lightbox.down('div.shopper-wrapper').setStyle({left:'520px',width:'0px',overflow:'hidden'}).show();
          new Effect.Parallel(e,{duration:1.5,transition:Gallery.cubic,
            afterFinish: function(){
              Catalog._animation.inProgress = false;
              new Ajax.Updater(
                'shop'+page+'_panel1',
                '/'+getCookie('site')+'/contact_item.asp', {
                  parameters: Catalog.serialize(page,style) + '&form=unavailable',
                  onException: function(transport, exception){
                    Shop.lastException = $H(exception);
                  },
                  onComplete: function(r){
                    new Effect.Parallel([
                      new Effect.Scale(lightbox.down('div.details-wrapper'), 100,{ sync:true,
                        scaleMode:{originalWidth:260,originalHeight:504}, scaleFrom:0, scaleY:false, scaleContent:false }),
                      new Effect.Scale(lightbox.down('div.shopper-wrapper'), 100,{ sync:true,
                        scaleMode:{originalWidth:260,originalHeight:504}, scaleFrom:0, scaleY:false, scaleContent:false })
                    ],{ duration:1.1, transition:Gallery.cubic });
                  }
                }
              );
            }
          });

          break;

        default:
          Catalog.loadShopPanels(page,style);
      }
    },
    loadShopPanels: function(page,style) {
      var lightbox = $('lightbox_'+(page-1));
      var e = [];
      e.push(new Effect.Move(lightbox.down('div.panel1-background'),{x:260,sync:true}));
      e.push(new Effect.Move(lightbox.down('div.panel2-background'),{x:520,sync:true}));

      lightbox.down('div.product-image').update().setStyle({width:'260px',overflow:'hidden'}).setOpacity(0);
      lightbox.setStyle({display:'block'});

      lightbox.down('div.details-wrapper').setStyle({left:'520px',width:'0px',overflow:'hidden'}).show();
      lightbox.down('div.styles-wrapper').setStyle({right:'-260px'}).show();
      lightbox.down('div.shopper-wrapper').setStyle({right:'-260px'}).show();

      new Effect.Parallel(e,{duration:1.5,transition:Gallery.cubic,
        afterFinish: function(){
          Catalog._animation.inProgress = false;
          new Effect.Appear(lightbox.down('div.product-image'));
          new Ajax.Request(
            '/'+getCookie('site')+'/product-shots/'+getCookie('language')+'/'+
             getCookie('site')+'/'+_catalog_data[style].url+'.asp', {
             parameters: 'lightbox=' + lightbox.id + '&style=' + style,
             onException: function(transport, exception){
               Shop.lastException = $H(exception);
             },
             onSuccess: function(){
               new Effect.Scale(lightbox.down('div.details-wrapper'), 100,{
                 scaleMode:{originalWidth:260,originalHeight:504}, scaleFrom:0, scaleY:false,
                 scaleContent:false, duration:1.1, transition:Gallery.cubic, afterFinish:function(){
                   lightbox.down('div.details-wrapper').setStyle({left:'auto',right:'0',overflow:'visible'});
                 }});
               if(lightbox.down('div.size-guide')) lightbox.down('div.size-guide').hide();
             }
          });
        }
      });
    },
    closeLightbox: function(lightbox) {
      var lightbox = $(lightbox);
      var e = [];

      if(Shop._lightboxes[$(lightbox).id].zoomer) {
        Shop._lightboxes[$(lightbox).id].zoomer.zoomOutAndDestroy();
        Shop._lightboxes[$(lightbox).id].zoomer = null;
      }

      lightbox.down('div.product-image').setStyle({left:'260px',overflow:'hidden'});
      lightbox.down('div.details-wrapper').setStyle({left:'520px',overflow:'hidden'});
      if(lightbox.down('div.size-guide')) lightbox.down('div.size-guide').hide();
      lightbox.down('div.styles-wrapper').hide();
      lightbox.down('div.shopper-wrapper').hide();

      e.push(new Effect.Scale(lightbox.down('div.product-image'), 0,{ sync:true,
        scaleMode:{originalWidth:260,originalHeight:504}, scaleFrom:100, scaleY:false, scaleContent:false }));
      e.push(new Effect.Scale(lightbox.down('div.details-wrapper'), 0,{ sync:true,
        scaleMode:{originalWidth:260,originalHeight:504}, scaleFrom:100, scaleY:false, scaleContent:false }));

      new Effect.Parallel(e,{duration: 0.75,transition:Gallery.cubic,afterFinish:function(){
        var e = [];
        e.push(new Effect.Move(lightbox.down('div.panel1-background'),{x:-260,sync:true}));
        e.push(new Effect.Move(lightbox.down('div.panel2-background'),{x:-520,sync:true}));
        e.push(new Effect.Move(lightbox.down('div.panel3-background'),{x:-780,sync:true}));
        new Effect.Parallel(e,{duration: 0.75,transition:Gallery.cubic,afterFinish:function(){
          lightbox.hide();
          Catalog.closePage(lightbox);
        }});
      }});
    },
    info: function(page,style,area){
    },
    clearInfo: function(page,area){
    },
    closeShop: function(page){
    },
    toggleOverlay: function(link){
      var overlay = $(link).previous('img');
      if(overlay.getOpacity()==0){
        link.down('div.content').update(Gallery.getTerm('hide outlines'));
        if(Engine.isMSIE) {
          $(overlay).setOpacity(1);
        } else {
          new Effect.Opacity(overlay,{from:0,to:1});
        }
      } else {
        link.down('div.content').update(Gallery.getTerm('show outlines'));
        if(Engine.isMSIE) {
          $(overlay).setOpacity(0);
        } else {
          new Effect.Opacity(overlay,{from:1,to:0});
        }
      }
    },
    loadVisiblePages: function(){
	//alert('A');
      if(!Catalog._loaded) return;
      //alert('B');
	  if(Catalog._loaderTimeout) clearTimeout(Catalog._loaderTimeout);
      Catalog._loaderTimeout = setTimeout(function(){
        var p = window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft || 0;
        var w = Position.getPageSize().window.width;
		//alert('C');
        var visibles = [];
        $R(1,CATALOG_PAGES).each(function(i){
          var x = 301+(i-1)*(780+65);
          if(p<x && (p+w)>x) visibles.push(i);
          if(p<(x+780) && (p+w)>(x+780)) visibles.push(i);
        });

        visibles.each(function(i){
          if($('page_'+i).hasClassName('loaded')) return;
          $('page_'+i).addClassName('loading');
          Loader.load(CATALOG_URL+i+'.jpg&width=780',{
            onComplete:function(img){
              $('image_'+i).setOpacity(0);
              setTimeout(function(){
                $('image_'+i).src = img;
                if(Engine.isMSIE6) { // alpha(opacity=0)
                  $('image_'+i+'_map').style.filter =
                    "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+OVERLAY_URL + i + ".jpg&width=780',sizingMethod='scale')";
                } else {
                  $('image_'+i+'_map').src = OVERLAY_URL + i + '.jpg&width=780';
                }
                $('image_'+i+'_map').show().setOpacity(0);
                new Effect.Opacity('image_'+i,{from:0.0,to:1.0,afterFinish:function(){ $('page_'+i).addClassName('loaded').removeClassName('loading') }});
              },1);
            }
          });
        });

        if((p+w)>(65+236+CATALOG_PAGES*(780+65))) $R(1,CATALOG_PAGES).each(function(i){
          Loader.load(CATALOG_URL+i+'.jpg&width=250&height=162',{
            onComplete:function(img){
              $('thumb_'+i).setOpacity(0);
              $('thumb_'+i).src = img;
              new Effect.Opacity('thumb_'+i,{from:0.0,to:0.999});
            }
          });
        });
      }, 250);
    }
  };

