var Miumiu = {};

Miumiu.StageBagBrowser = Class.create({
  initialize: function(data){

    this.images = {};
    this.currentImage = 0;
    this.currentPage = 0;
    this.thumbnailCache = {};
    this.showLookNumber = true;
    this.enlargeImages = false;

    this.options = Object.extend({
      style: 'left: 350px; top: 50px'
    }, arguments[1] || {});
    this.enlargeImages = !!this.options.enlargeImages;
    this.showLookNumber = !this.options.omitThumbs;
    this.miuandyou = !!this.options.miuandyou;
    this.captions = this.options.captions || null;
    this.shopTheLook = this.options.shopTheLook || null;

    // select thumbnail/details depending on viewport height
    var viewportHeight = document.viewport.getDimensions().height;
    [900, 725, 0].each(function(height, index){
      if(viewportHeight >= height){
        this.THUMBS_VARIANT = 'thumbs_' + (3-index);
        this.DETAILS_VARIANT = 'details_' + (3-index);
        throw $break;
      }
    }.bind(this));

    this.data = this.options.order
      ? this.options.order.map(function(index){ return data[index] })
      : data;
      
    if(!$('modal_container')) {
      this.overlayWindow = this.miuandyou 
      ? new Element('div', { id: 'modal_container', className: "miuandyou", style: 'position:absolute;z-index:100;display:;'+this.options.style })
      : new Element('div', { id: 'modal_container', style: 'position:absolute;z-index:100;display:;'+this.options.style }).update(
          new Element('div',{ id: 'modal_container-title-bar', className: 'clearfix' }).insert(
            new Element('img',{ src: '/images/prevlabel.gif', style:'cursor:pointer;float:left'}).observe('click', this.previousImage.bind(this))
          ).insert(
            new Element('img',{ src: '/images/nextlabel.gif', style:'cursor:pointer;float:left;margin-left:3px'}).observe('click', this.nextImage.bind(this))
          ).insert(
            new Element('img',{ src: '/images/close.gif', style:'cursor:pointer;margin-bottom:3px;float:right'}).observe('click', this.closeImage.bind(this))
          )
        );
      
      var imageWrapper = new Element('div', { id: 'image_container_wrapper' }).update(
        new Element('div', { id: 'image_container' })
      );
      if(this.shopTheLook){
        var shopTheLook = new Element('div', { id: 'shop_the_look', style: 'display:hide' }),        
          shopTheLookClose = new Element('div', { className: 'close' });
        shopTheLook.insert(shopTheLookClose);
        shopTheLook.observe('click', this.navigateToCurrentLook.bind(this));
        shopTheLookClose.observe('click', this.closeShopTheLook.bind(this));
        imageWrapper.insert(shopTheLook);
      }
      
      if(this.miuandyou){
        this.overlayWindow.insert({bottom:imageWrapper});
        
        if(this.captions) $$('body').first().insert(
          new Element('div',{ id: 'modal_container-captions', className: 'miuandyou-captions' })
        );
        $$('body').first().insert(
          new Element('div',{ id: 'modal_container-title-bar', className: 'miuandyou-controls' }).insert(
            new Element('img',{ src: '/images/miuandyou/prev.png', style:'cursor:pointer;float:left'}).observe('click', this.previousImage.bind(this))
          ).insert(
            new Element('img',{ src: '/images/miuandyou/next.png', style:'cursor:pointer;float:left'}).observe('click', this.nextImage.bind(this))
          ).insert(
            new Element('img',{ src: '/images/miuandyou/close.png', style:'cursor:pointer;float:left'}).observe('click', this.closeImage.bind(this))
          )
        );
      }
      else
        this.overlayWindow.insert(imageWrapper);
        
      $$('body').first().insert(this.overlayWindow.hide());
    } else {
      this.overlayWindow = $('modal_container');
    }
    
    if(!this.options.omitThumbs){
      this.thumbnails = this.data.map(function(item, index){
        var thumbnail = new Element('div',{ id:'thumb-'+index, className:'image-container' }).setStyle({
          display: 'none',
          zIndex: 50,
          width:(item[this.THUMBS_VARIANT].width+6)+'px', height:(item[this.THUMBS_VARIANT].height+6)+'px',
          cursor: 'pointer'
        });
        thumbnail.observe('click', this.showImage.bind(this, index));
        $('thumb-looks').insert(thumbnail);
        return thumbnail;
      }.bind(this));
      $('sub-nav').insert(
        '<div id="arrow_bar" class="clearfix" style="padding:0;border:0">'+
        '<img id="sub-next-btn" src="/images/nextlabel.gif" style="cursor:pointer;float:right"/>'+
        '<img src="/images/pagelabel.gif" style="float:right"/>'+
        '<img id="sub-prev-btn" src="/images/prevlabel.gif" style="cursor:pointer;float:right"/>'+
        '</div>'
      );

      $('sub-next-btn').observe('click', this.nextPage.bind(this));
      $('sub-prev-btn').observe('click', this.previousPage.bind(this));

      Event.observe(window, 'resize', this.redraw.bind(this, 0));
      Event.observe(window, 'load', this.redraw.bind(this, 0));

      this.redraw(0);
    }
    else {
     this.showImage(0);
    }
  },

  showThumbnail: function(index, delay){
    var thumbnail = this.thumbnails[index];
    if(!this.thumbnailCache[index]){
      var image = new Image();
      image.src = this.options.path + this.data[index][this.THUMBS_VARIANT].src;
      thumbnail.show().setStyle({opacity:0});
      if(image.complete){
        thumbnail.insert(new Element('img', { src: image.src })).hide();
        setTimeout(function(){ thumbnail.appear() }, 1);
      } else
        image.onload = function(){
          thumbnail.insert(new Element('img', { src: image.src })).hide();
          setTimeout(function(){ thumbnail.appear() }, 1);
        }
      this.thumbnailCache[index] = image;
      return;
    }
    if(delay>0)
      thumbnail.appear({duration:0.4,delay:delay/9});
    else
      thumbnail.show();
  },

  redraw: function(dir){
    var displayed = true, startIndex = 0, index, delay = true;
    if(dir==0)
      this.thumbnails.each(function(t,i){ if(t.visible()){ startIndex = i; throw $break } });
    if(dir==-1)
      this.thumbnails.each(function(t,i){ if(t.visible()){ startIndex = i-1; throw $break } });
    if(dir==1)
      this.thumbnails.reverse(false).each(function(t,i){
        if(t.visible()){ startIndex = this.thumbnails.length - i; throw $break }
      }.bind(this));

    if(dir==0) { delay = false; dir = 1 }
    index = startIndex;
    this.thumbnails.each(Element.hide);

    var firstThumbnail = this.thumbnails[index];
    while(displayed && index >= 0 && index < this.thumbnails.length){
      var thumbnail = this.thumbnails[index];
      thumbnail.show();
      displayed = true; //dir==-1
//        ? firstThumbnail.getHeight() + firstThumbnail.viewportOffset().top < document.viewport.getDimensions().height
//        : thumbnail.getHeight() + thumbnail.viewportOffset().top < document.viewport.getDimensions().height;
      if(displayed) index += dir;
    }

    if(startIndex > (index-1)) { var temp = index; index = startIndex+1; startIndex = temp+1 }
    // this.thumbnails.each(Element.hide);

    $R(startIndex, index-1).each(function(i){
      this.showThumbnail(i, delay ? i-startIndex : -1);
    }.bind(this));

    $('sub-prev-btn').setStyle({cursor:this.thumbnails.first().visible() ? 'default' : 'pointer'});
    $('sub-next-btn').setStyle({cursor:this.thumbnails.last().visible() ? 'default' : 'pointer'});
  },
  
  showShopTheLook: function(index){
    if(!this.shopTheLook) return;
    if(!this.shopTheLook[index]) return;
    $('shop_the_look').appear({delay:0.8,duration:0.4});
  },
  
  closeShopTheLook: function(event){
    if(!this.shopTheLook) return;
    if($('shop_the_look').visible())
      $('shop_the_look').fade({duration:0.2});
    event.stop();
  },
  
  hideShopTheLook: function(){
    if(!this.shopTheLook) return;
    $('shop_the_look').hide();
  },
  
  navigateToCurrentLook: function(){
    if(!this.shopTheLook) return;
    $('shop_the_look').pulsate({pulses:2,duration:0.4});
    setTimeout(function(){
      location.href = '/shop/looks/' + this.shopTheLook[this.currentImage];
    }.bind(this), 410);
  },

  previousPage: function(){
    if(this.thumbnails.first().visible()) return;
    this.redraw(-1);
  },

  nextPage: function(){
    if(this.thumbnails.last().visible()) return;
    this.redraw(1);
  },

  previousImage: function(){
    if(this.transition) return;
    if((this.currentImage--)==0) this.currentImage = this.data.length-1;
    this.showImage(this.currentImage);
  },

  nextImage: function(){
    if(this.transition) return;
    if((this.currentImage++)==this.data.length-1) this.currentImage = 0;
    this.showImage(this.currentImage);
  },

  revealImage: function(src, width, height){
    var image = new Element('img',{ src: src, width: width, height: height }).setStyle({opacity:0,display:'none'});
    $('image_container').insert(image);
    image.show();
    image.morph('opacity:1',{ duration: 0.5, afterFinish:function(){
      this.transition = false;
      if(Prototype.Browser.IE){
        image._src = image.src;
        image.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + image.src + "', sizingMethod='scale')";
        image.src = '/images/blank.gif';
      }
    }.bind(this) });
  },

  showImage: function(index){
    this.transition = true;
    var animate = true;
    this.currentImage = index;
    
    this.hideShopTheLook();
    
    if(this.captions)
      $('modal_container-captions').update(this.captions[index]);

    if(!this.overlayWindow.visible()){
      animate = false;
      this.overlayWindow.show();
      if(this.miuandyou)
        $('modal_container-title-bar').show();
      if(this.captions)
        $('modal_container-captions').show();
    }

    if($('image_container').down()) {
      var oldImage = $('image_container').down();
      oldImage.morph('opacity:0',{ duration: 0.5,
        afterFinish: function(effect){
          oldImage.remove();
        }
      });
    }

    var data = this.data[index], imageData = data[this.DETAILS_VARIANT];
    var imgWidth = imageData.width;
    var imgHeight = imageData.height;
    var ratio = imgWidth/imgHeight;

    var dims = document.viewport.getDimensions();
    if(this.enlargeImages) {
      if(this.miuandyou){
        imgHeight = dims.height - 50;
        imgWidth = (imgHeight * ratio).round();
        if (imgWidth>(dims.width - 50)) {
          imgWidth = dims.width - 50;
          imgHeight = (imgWidth / ratio).round();
        }
      } else {
        imgHeight = dims.height - ($('modal_container').offsetTop+40);
        imgWidth = (imgHeight * ratio).round();
        if (imgWidth>(dims.width - ($('modal_container').offsetLeft+20))) {
          imgWidth = dims.width - ($('modal_container').offsetLeft+20);
          imgHeight = (imgWidth / ratio).round();
        }
      }
    }

    if(animate){
      $('image_container').morph(
        {width: imgWidth+'px',height: imgHeight+'px'},
        {duration:0.5}
      );
      if(this.miuandyou)
        $('modal_container').morph({
          width: imgWidth+2+'px', left: ((dims.width-imgWidth)/2).round()+'px',
          height: imgHeight+2+'px', top: ((dims.height-imgHeight)/2).round()+'px' 
        },{duration:0.5});
      else
        $('modal_container').morph({width: imgWidth+'px'},{duration:0.5});
    } else {
      $('image_container').setStyle({width: imgWidth+'px',height: imgHeight+'px'});
      if(this.miuandyou)
        $('modal_container').setStyle({
          width: imgWidth+2+'px', left: ((dims.width-imgWidth)/2).round()+'px',
          height: imgHeight+2+'px', top: ((dims.height-imgHeight)/2).round()+'px' 
        });
      else
        $('modal_container').setStyle({width: imgWidth+'px'});
    }

    if(!this.images[index]) {
      var image = new Image();
      image.src = this.options.path + imageData.src;
      if(image.complete){
        this.revealImage(image.src, imgWidth, imgHeight);
        this.showShopTheLook(index);
      }
      else
        image.onload = function(){
          this.revealImage(image.src, imgWidth, imgHeight);
          this.showShopTheLook(index);
        }.bind(this);
      this.images[index] = image;
    } else {
      this.revealImage(this.images[index].src, imgWidth, imgHeight);
      this.showShopTheLook(index);
    }
    if(this.showLookNumber) {
      if(!$('sub-nav').down('.lookNumber'))
        $('sub-nav').insert('<span class="lookNumber"></span>');
      $('sub-nav').down('.lookNumber').update('#'+(index+1));
    }
  },

  closeImage: function(){
    this.overlayWindow.hide();
    if(this.miuandyou)
      $('modal_container-title-bar').hide();
    if(this.captions)
      $('modal_container-captions').hide();
    $('image_container').update();
    if(this.showLookNumber)
      $('sub-nav').down('.lookNumber').remove();
    if(this.options.onClose) this.options.onClose();
  }
});