// creative scrape
// the following code is not open-source software and private
// contact us at amy@slash7.com or thomas@fesch.at for licensing
// information

(function(){
  var zoomStyle = null, data = {}, aboutClosed = false, automaticClose,
    autoInterval, waitForAnimation, link = $('zoom').down('a'), suspendAutomatic = false;

  function layout(){
    var dims = document.viewport.getDimensions(),
      q = ((Math.min(dims.width, dims.height) - 110) / 4).floor() * 4;
    
    $('logo').setStyle({ top: (dims.height-q-30)/2+'px' });
    $('images').setStyle({
      width:q+30+'px', height:q+30+'px', top:(dims.height-q-30)/2+'px', left:60+'px'
    });
    $('images').select('li').each(function(image,index){
      image.setStyle({
        width: q/4+'px', height: q/4+'px',
        marginRight: index%4 == 3 ? '0' : '10px',
        marginBottom: index>11 ? '0' : '10px'
      });
    });
  }
  
  function loadImage(src, method){
    var image = new Image();
    image.src = src;
    if(image.complete)
      method();
    else
      image.onload = method;
    return image;
  }

  function setImage(li, src){
    li.setStyle({opacity:0,backgroundImage:'url('+src+')'});
    li.morph('opacity:1',{});
  }
  
  function zoomImage(element, event, suspend){
    closeAbout();
    suspendAutomatic = suspend || false;
      
    var 
      data = element._data,
      zoom = $('zoom'), o = element.cumulativeOffset();
    zoom.setStyle({backgroundImage:'url('+data[0]+')'});
    
    zoomStyle = {
      left:o[0]+'px',top:o[1]+'px',
      width:element.offsetWidth+'px',height:element.offsetHeight+'px'
    };
    var link = zoom.down('a');
    link.hide().writeAttribute('href', data[1]).update(data[1]);
    zoom.setStyle(zoomStyle);
    
    var dims = document.viewport.getDimensions(),
        w = parseInt(data[2]), h = parseInt(data[3]), l = o[0], t = o[1];
    
    if(l+w>dims.width-10) l = dims.width-w-10;
    if(t+h>dims.height-10) t = dims.height-h-10;
    if(l<10) { w=dims.width-20; l=10; }
    if(t<10) { h=dims.height-20; t=10; }
    
    zoom.show().morph(
      'left:'+l+'px;top:'+t+'px;'+
      'width:'+w+'px;height:'+h+'px', {
      duration: .4,
      after: function(){ link.show(); }
    });
    
    if(event) event.stop();
  }

  function showImages(images){
    $('images').update();
    images.each(function(image){
      var li = new Element('li',{opened:'false'});
      li._data = image;

      loadImage(image[0], function(){
        setImage.delay(Math.random()*3, li, image[0]);
      });

      $('images').insert(li);
      li.observe('click', function(event){
        zoomImage(li, event, true);
      });
    });
  }
  
  function getScrapes(){
    new Ajax.Request('creativescrape.json?'+((new Date().getTime())/60000).floor(),{
      method: 'GET',
      onSuccess: function(transport){
        data = transport.responseText.evalJSON();
        showImages(data.sortBy(Math.random).slice(0,16));
        layout();
      }
    });
  }
  
  function openAbout(event){
    if(!aboutClosed) return;
    if(automaticClose){
      clearTimeout(automaticClose);
      automaticClose = null;
    }
    $('about_wrapper').morph('width:400px');
    aboutClosed = false;
    if(event) event.stop();
  }
  
  function closeAbout(event){
    if(aboutClosed) return;
    $('about_wrapper').morph('width:0px');
    aboutClosed = true;
    if(event) event.stop();
  }
  
  function resetTimeout(event){
    if(autoInterval) clearInterval(autoInterval);
    autoInterval = null;
    
    if(waitForAnimation) clearTimeout(waitForAnimation);
    waitForAnimation = setTimeout(function(){
      suspendAutomatic = true;
      
      autoInterval = setInterval(function(){
        var image = $$('#images li[opened=false]').sortBy(Math.random);
        image = image.size() == 0 ? false : image.first();
        unzoom();
        if(!image)
          getScrapes.delay(.6);
        else {
          image.writeAttribute('opened', 'true');
          setTimeout(function(){ zoomImage(image); }, 600);
        }
      }, 3000);
    }, 7500);
  }
  
  function unzoom(){
    if(!suspendAutomatic) resetTimeout();
    if(zoomStyle)
      $('zoom').morph(zoomStyle, { duration: .4, after: function(){ $('zoom').hide() }});
    zoomStyle = null;
  }
  
  $('about_wrapper').observe('click', function(event){
    if(event.element().tagName == "A") return;
    closeAbout(event); 
  });
  $('logo').observe('click', function(event){
    if(event.element().tagName == "A") return;
    if(aboutClosed)
      openAbout(event);
    else
      closeAbout(event);
  });
  
  $('zoom').observe('click',function(event){
    if(event.element() == link) {
      window.open(a.readAttribute('href'));
    }
    link.hide();
    unzoom()
    event.stop();
  }).observe('mouseout', function(){ link.hide(); })
    .observe('mouseover',function(){ link.show(); });
  
  automaticClose = setTimeout(closeAbout, 10000);
  
  Event.observe(document, 'click', function(){
    closeAbout();
    getScrapes();
  });
  Event.observe(document, 'mousemove', function(){
    resetTimeout();
  });
  resetTimeout();
  getScrapes();
  Event.observe(window, 'resize', layout);
  
  layout();
})();