/*
 * Girlfriend presents:
 * Hugo & Marie
 */

var HM = {};

/*
 * Header Functions
 */
HM._header = {};

(function($) {

  // Definitions
  HM._header.lockNavigation = function() {
    
    var $hm = $('#hm');
    var $header = $hm.find('.header.global');
    var $nav = $header.find('nav');
    
    if( !$hm.length ) { return false; }
    
    var top = $nav.offset().top;
    
    $(window).scroll(function() {
      
      var end_transition = top + $nav.height();
      
      if( top <= $(window).scrollTop() ) {
        $hm.addClass('fixedHeader');
        $header.find('.bottom-gradient').css({'opacity': 1 });
      } else {
        $header.find('h1 a').css({'opacity': 1 - ($(window).scrollTop()/top) });
        $header.find('.bottom-gradient').css({'opacity': ($(window).scrollTop()/top) });
        $hm.removeClass('fixedHeader');
      }
                         
    });
    
  };
  
  HM._header.blipUpdate = function( selector ) {

    var $hm = $('#hm');
    var $header = $hm.find('.header.global');
    var $nav = $header.find('nav');
    
    if( HM.documentReady ) {
      $nav.find( selector ).trigger('updateBlip');
    } else {
      $nav.find( selector ).addClass('active');
    }

  };
  
  HM._header.navigationBlip = function() {
    
    var $hm = $('#hm');
    var $header = $hm.find('.header.global');
    var $nav = $header.find('nav');
    
    var $active = $nav.find('ul li a.active');
    
    // Setup blip
    $nav.append('<div class="blip"></div>');
    var $blip = $nav.find('.blip');
    
    if( $active.length ) {
      $blip.css({
        'width': $active.width(),
        'left': $active.offset().left - $nav.offset().left
      });
    }
    
    // Bind the click
    $nav.find('ul li a').bind('updateBlip', function(e) {
      
      // e.preventDefault();

      var $this = $(this);
      
      // Don't do anything if its already active
      /*
      if( $this.hasClass('active') ) {
        return false;
      }
      */
      
      // Change active elements
      $nav.find('ul li a.active').removeClass('active');
      $this.addClass('active');
      
      // Do some animating
      $blip.stop(true,true).animate({
        'width': $this.width(),
        'left': $this.offset().left - $nav.offset().left
      }, {
        easing: 'easeOutQuint',
        duration: 400,
        complete: function() {
          
          // window.location.href = $this.attr('href');
          
        }
      });
      
    })
    
  };
  
  HM._header.bindEvents = function() {
    var $hm = $('#hm');
    var $header = $hm.find('.header.global');
    var $nav = $header.find('nav');
    
    $nav.find('ul li a[href^="/"]').bind('click', function(e) {
      e.preventDefault();
      
      HM.controller.navigate($(this).attr('href'), true);
    });
    
    $header.find('h1 a').bind('click', function(e) {
    	e.preventDefault();
    	HM.controller.navigate($(this).attr('href'), true);
    });
    
  }
  
  HM._header.title = function(title) {
  	document.title = 'Hugo & Marie - ' + (title || 'Creative Direction & Artist Management');
  };
  
  HM._header.updateWidth = function() {
    var $hm = $('#hm');
    var $header = $hm.find('.header.global');
    var $nav = $header.find('nav');
    
    $nav.css('width', '100%');
    $nav.width($nav.find('ul').width());
  }
  
  // Triggers
  $(document).ready(function() {
    HM._header.lockNavigation();
    HM._header.bindEvents();
  });
  
  $(window).load(function() {
    HM._header.navigationBlip();
    HM._header.updateWidth();
  });
  

})(jQuery);

/*
 * Creatives Page
 */
HM.creatives = {};

(function($) {

  // Definitions
  HM.creatives.centerAlignInfo = function() {
    var $articles = $('.creative-single .items .item,#body .page .images .image:has(.info)');
    
    $articles.each(function() {

      var $article = $(this);
      var $info = $article.find('.info .inside');
      
      var article_height = $article.height();
      var info_height = $info.height();
      
      var difference = article_height - info_height;
      
      $info.css({
        'marginTop': difference / 2
      })
      
    });
  };
  
  HM.creatives.articleRollover = function() {
    
    $articles = $('.creative-single .items .item,#body .page .images .image:has(.info)');
    
    $articles
      .each(function() {
        
        var $article = $(this);
        var $info = $article.find('.info');
        
        var timeout;
        
        $(this).bind('mouseenter', function() {
          
          timeout = setTimeout(function() {
            $info.stop(true).fadeTo( 300, 1 );
          }, 200);
          
        })
        .bind('mouseleave', function() {
          
          clearTimeout( timeout );
          
          $info.stop(true).fadeTo( 200, 0 );
        });
        
        $info.fadeTo(0,0);
        
        
      })
    
  };
  
  HM.creatives.masonry = function() {
  
    $('.creatives-index').masonry({
      columnWidth: 278+33,
      singleMode: true,
      isResizable: false
    });
  
  };
  
  // Triggers
  $(document).ready(function() {
    
    // HM.creatives.centerAlignInfo();
    // HM.creatives.articleRollover();
    
  });
  

})(jQuery);

(function($) {

  // Definitions
  HM.creatives.background = {};
  
  HM.creatives.background.ready = function() {
    
    var $background = $('#background');
    $background.hide();
    
  };
  
  HM.creatives.background.load = function() {
    
    HM.creatives.background.draw();
    
    var $background = $('#background');
    $background.fadeTo(300,1);
    
    $(window).unbind('resize.creativesBackground').bind('resize.creativesBackground', function() {
      HM.creatives.background.draw();
    });
    
  };
  
  HM.creatives.background.draw = function() {
    
    var n = 0.05;
    
    var $background = $('#background');
    var $img = $background.find('img');
    
    var wHeight = $(window).height();
    var newHeight = wHeight*(1+n);
    
    $background.height( newHeight )
    $img.height( newHeight );
    
    var full = $(document).height() - wHeight;
    var magicNumber = -1 * (wHeight*n);
    
    if( $.browser.safari ) {
      $(window).unbind('scroll.creatives-background').bind('scroll.creativesBackground', function() {
        $img.css({
          'marginTop': magicNumber * ($(window).scrollTop()/full)
        });
      });
    } else {
      
      if( Modernizr.backgroundsize && $img.length ) {
        $background.css({
          'background-image': 'url(' + $img.attr('src') + ')',
          'background-size': 'cover',
          'background-position': '50% 50%'
        });
        
        $img.remove();
      }
      
    }
    
  };
  
  $(document).ready(function() {
    
    // Check if chrome
    $.browser.chrome = /chrome/.test(navigator.userAgent.toLowerCase());
    if( $.browser.chrome ){ $.browser.safari = false; }
    
    // 
    
    // And now we'll do the creatives background
    // HM.creatives.background.ready();
  });
  
  $(document).ready(function() {
    
    setTimeout(function() {
      // HM.creatives.background.load();
    }, 1000);
    
  });
  
  

})(jQuery);

HM._zoom = {};

/*
 * Lightbox Defintiion
 */
(function($) {

  HM._zoom.lightboxSetup = function() {
  
    $(window).bind('resize.zoomLightbox', function() {
      
      var $img = $('#zoom .inside img.main');
      var iWidth = parseInt($img.attr('data-width'), 10);
      var iHeight = parseInt($img.attr('data-height'), 10);
      
      // Check if image has width or height
      if( _.isNaN(iWidth) || _.isNaN(iHeight) ) {
        if( !$img.get(0).complete ) {
          $img.bind('load', function() {
            $(window).trigger('resize.zoomLightbox');
          });
          
          return;
        } else {
          $img.removeAttr('width').removeAttr('height');
          iWidth = $img.outerWidth();
          iHeight = $img.outerHeight();
        }
      }
      
      var ratio = iWidth / iHeight;
      
      var padding = 100;
      
      var wWidth = $(window).width() - (padding*2);
      var wHeight = $(window).height() - (padding*2);
      var wRatio = wWidth / wHeight;
   
      if( ratio < wRatio ) {
        
        var height = wHeight;
        $img.height( height );
        $img.width( HM.getWidthForHeight(iWidth, iHeight, height) );
        
        var height = wHeight;
        $('#zoom .inside').height( height );
        $('#zoom .inside img').css({
          'marginTop': 0
        });
        
      } else {
        
        var width = wWidth;
        
        var newWidth = width;
        var newHeight = HM.getHeightForWidth(iWidth, iHeight, width);
        
        $img.width( newWidth );
        $img.height( newHeight );
   
        var height = wHeight;
        $('#zoom .inside').height( height );
   
        $('#zoom .inside img').css({
          'marginTop': (height-newHeight)/2
        })
        
      }
   
    });
    
    $(window).trigger('resize.zoomLightbox');
  
  };

})(jQuery);


/*
 * Zoom Page
 */
(function($) {

  HM._zoom.hide = function() {
    
    HM.refreshImages( $('#body') );
    
    HM._zoom.visible = false;
  
    $('#zoom').hide();
    $('body').removeClass('scroll-less fullscreen fullscreen-zoom');
    
    // hack: just remove the /zoom
    var url = Backbone.history.getFragment().replace('/zoom','');
    HM.controller.navigate(url, false);
  };
  
  HM._zoom.progress = function(direction) {
    
    // calculate currentIndex
    var creativeId = $('#creative .creative-single').attr('data-creative-id');
    var creativeWorks = HM.data.creatives.get('individuals').get(creativeId).get('works');    
    var currentWorkId = $('#zoom img.main').attr('data-work-id');
    var currentWorkIndex = creativeWorks.indexOf( creativeWorks.get(currentWorkId) );
    
    // appear id
    var appearIndex = currentWorkIndex + direction;
    appearIndex = ( appearIndex < 0 ? creativeWorks.length - 1 : appearIndex % creativeWorks.length );
    
    HM._zoom.newImage( creativeWorks.at( appearIndex ).get('id') );
    
  };

  HM._zoom.newImage = function( workId ) {
  
    // Stop the window from loading
  	HM.windowStop();
  
    // Make it appear
    $('#zoom').show().removeClass();
    $('#zoom .content,#zoom .content .inside').attr('style', '');
    
    HM._zoom.visible = true;
    
    $('body').addClass('scroll-less fullscreen fullscreen-zoom');
    
    // figure out the creative ID
    var creativeId = $('#creative .creative-single').attr('data-creative-id');
    var work = HM.data.creatives.get('individuals').get(creativeId).get('works').get(workId);
    
    $('#zoom img.main').remove();
    $('#zoom .content .inside').append('<img data-work-id="' + workId + '" data-creative-id="' + creativeId + '" src="' + work.get('zoomImage') + '" width="' + work.get('zoomImageWidth') + '" height="' + work.get('zoomImageHeight') + '" data-width="' + work.get('zoomImageWidth') + '" data-height="' + work.get('zoomImageHeight') + '" class="main" />');
    
    
    // Figure out the display mode
    // if( work.get('pan_mode') == 1 ) {
    if( true ) {
      $('#zoom').addClass('zoom');
      HM._zoom.renderImage();
      HM._zoom.bindEvents();
    } else {
      $('#zoom').addClass('lightbox');
      HM._zoom.lightboxSetup();
    }
    
    HM.controller.navigate( '/creatives/' + creativeId + '/zoom' );
    
    HM.controls.render(['.up','.down','.back','.share']);
    
  };

  // Definitions
  HM._zoom.renderImage = function() {
    
    var $image = $('#zoom img.main');
    var $content = $('#zoom .content');

    var width = $image.attr('width');
    var height = $image.attr('height');

    $content.width( width );
    $content.height( height );
    
    width = $content.outerWidth();
    height = $content.outerHeight();
    
    var wWidth = $(window).width();
    var wHeight = $(window).height();
    
    var attrs = {
      position: 'static',
      top: 0,
      left: 0,
      marginTop: 0,
      marginLeft: 0
    };
    
    if( wWidth > width ) {
      attrs.position = 'absolute';
      attrs.left = '50%';
      attrs.marginLeft = width/-2;
      HM._zoom.overflowX = false;
    } else {
      HM._zoom.overflowX = true;
    }
    
    if( wHeight > height ) {
      attrs.position = 'absolute';
      attrs.top = '50%';
      attrs.marginTop = height/-2;
      HM._zoom.overflowY = false;
    } else {
      HM._zoom.overflowY = true;
    }
    
    $content.css( attrs );
    
  };
  
  HM._zoom.bindEvents = function() {
    
    $('#zoom img').bind('mousedown', function(e) {
      
      var oldX, oldY;
      var evX, evY;
      var deltaX, deltaY;
      var updateCounter = 0;
      var timeout;
      
      $('#zoom').bind('mousemove', function(e) {
        
        clearTimeout( timeout );
        
        updateEventCoordinates(e);
        
        var currLeft = $('#zoom').scrollLeft();
        var currTop = $('#zoom').scrollTop();
        
        var newLeft = currLeft - deltaX;
        var newTop = currTop - deltaY;
        
        $('#zoom').scrollTop( newTop ).scrollLeft( newLeft );
        
        timeout = setTimeout(function() { updateEventCoordinates(e); }, 100);
        
      }); // end bind mousemove
      
      $(this).bind('mouseup', function() {
        
        if( updateCounter > 2 ) {
          
          var n = 8;
          var distance = n * Math.sqrt(
            ( (oldX-evX)*(oldX-evX) ) + ( (oldY-evY)*(oldY-evY) )
          );
          
          var currLeft = $('#zoom').scrollLeft();
          var currTop = $('#zoom').scrollTop();
          
          newLeft = currLeft - (deltaX*n);
          newTop = currTop - (deltaY*n);
          
          $('#zoom').animate({
            'scrollTop': newTop,
            'scrollLeft': newLeft
          }, {
            duration: Math.round(distance*0.8),
            easing: 'easeOutQuad'
          });
          
        }
        
        $('#zoom').unbind('mousemove');
        $(this).unbind('mousemove mouseup');
        
      });
      
      $(this).bind('mouseout', function() {
        $(this).trigger('mouseup');
      }); // end mouseout
      
      // Functions
      function updateEventCoordinates(e) {
        oldX = typeof evX == 'number' ? evX : 0;
        oldY = typeof evY == 'number' ? evY : 0;
        
        if( e.pageX ) {
          evX = e.pageX;
          evY = e.pageY;
        } else {
          evX = oldX;
          evY = oldY;
        }
        
        deltaX = evX - oldX;
        deltaY = evY - oldY;
        
        updateCounter++;
      }
      
      updateEventCoordinates(e);
      
      e.preventDefault();
      return false;
    }).bind('mouseup', function(e) {
      $('#zoom').unbind('mousemove mouseup');
    });
    
  };
  
  // Triggers
  $(document).ready(function() {

    HM._zoom.renderImage();
    HM._zoom.bindEvents();
    
  });
    
  $(window).bind('resize', function() {
    HM._zoom.renderImage();
  });
  

})(jQuery);

/*
 * Showcase
 */
HM.showcase = {};

(function($) {

  HM.showcase.setup = function() {
  
    $('.showcase').masonry({
      columnWidth: 278+33,
      singleMode: true,
      isResizable: false
    });

  };

  $(document).ready(function() {
    // HM.showcase.setup();
  });
  

})(jQuery);


/*
 * Bind social
 */
(function($) {

  HM.bindSocial = function(el) {
  
    $(el).find('li.facebook a,a.facebook').bind('click', function(e) {
      e.preventDefault();
      HM.share('facebook', $(this).attr('data-url') );
    });

    $(el).find('li.twitter a,a.twitter').bind('click', function(e) {
      e.preventDefault();
      HM.share('twitter', $(this).attr('data-url') );
    });
    
  }
  
  HM.share = function( service, url ) {
    var params = {
      pubId: 'nhassan',
      url: ( !_.isUndefined(url) ? url : window.location.href ),
      template: '{{url}} @hugoandmarie'
    };
    
    window.open('http://api.addthis.com/oexchange/0.8/forward/' + service + '/offer?' + $.param(params), 'share-window', 'menubar=1,resizable=1,width=350,height=250');
  };

})(jQuery);

HM.controls = {};
/*
 * Controls
 */
(function($) {

  /*
   * Definitions
   */
  HM.controls = {};
  HM.controls.visible = ['.up', '.down', '.share'];

  HM.controls.animateProperties = function( element, to, opts ) {
    if( $('body').hasClass('fullscreen-zoom') ) {
      return element.css('left', 'auto').stop(true,true).animate({'right': to}, opts);
    } else {
      return element.css('right','auto').stop(true,true).animate({'left': to}, opts);
    }
  };
  
  HM.controls.bind = function() {
    
    /*
     * Handle the share
     */
    $('#controls ul li.share a').bind('click', function(e) {
    
      e.preventDefault();
      
      if( HM.controls.visible.indexOf('.facebook') < 0 || HM.controls.visible.indexOf('.twitter') < 0 ) {
        HM.controls.add('.facebook');
        HM.controls.add('.twitter');
        
        HM.controls.render();
      } else {
        HM.controls.remove( '.facebook' );
        HM.controls.remove( '.twitter' );
        
        HM.controls.render();
      }

    });
    
    /*
     * Handle each share item
     */
    HM.bindSocial('#controls ul');
    
    /*
     * Handle the back button
     */
    $('#controls ul li.back a').bind('click', function(e) {
      e.preventDefault();

      if( $('body').hasClass('fullscreen') ) {
        HM._zoom.hide();
        return;
      }

      var backURLs = {
        // '#zoom': '/creatives/' + $('#creative .creative-single').attr('data-creative-id'),

        '#creative .creative-single .items.multiple': '/creatives',
        '#creative .creative-single .items:not(.multiple)': $('#creative .creative-single .header h1 a').attr('href'),
        '#showcase-single': '/showcase',
        '#interactive-single': '/interactive'
      };
      
      for( selector in backURLs ) {
        
        if( $(selector).length ) {
          HM.controller.navigate( backURLs[selector], true);
        }
      }
      
    });
    
    /*
     * Handle the fullscreen button
     */
    $('#controls ul li.fullscreen a').bind('click', function(e) {
      e.preventDefault();
      
      if( $('body').hasClass('fullscreen') ) {
        HM._zoom.hide();
      } else {
        HM._zoom.newImage( HM.controls.horizontalScroll('#creative .item').currentElement.attr('data-work-id') );
      }
      
    });
    
    $(document).bind('keydown', 'esc', function(e) {
      
      if( $('body').hasClass('fullscreen') ) {
        $('#controls ul li.fullscreen a').trigger('click');
      }
      
      if( !HM.windowLoaded ) {
        e.preventDefault();
      }
      
    });
    
    /*
     * Handle the mouseover
     */
    $('#controls ul li a').bind('mouseenter', function() {

      // HM.controls.animate( $(this).parent().stop(true,true), -1, {duration:0} );
      HM.controls.animateProperties( $(this).parent().stop(true,true), -1, {duration:2} );

    }).bind('mouseleave', function() {

      // HM.controls.animate( $(this).parent().stop(true,true), 0, {duration:0} );
      HM.controls.animateProperties( $(this).parent().stop(true,true), 0, {duration:2} );

    });
    
    /*
     * Handle the .left + .right
     */
    $('#controls ul li.left a').bind('click', function(e) {
      e.preventDefault();
      
      HM.interactive.progress(-1)
    });
    
    $('#controls ul li.right a').bind('click', function(e) {
      e.preventDefault();
      
      HM.interactive.progress(1)
    });
    
    $(document).bind('keydown', 'left', function() {
      $('#controls ul li.left a').trigger('click');
    });
    
    $(document).bind('keydown', 'right', function() {
      $('#controls ul li.right a').trigger('click');
    });
    
    /*
     * Handle the .up + .down
     */
    $('#controls ul li.down a').bind('click', function(e) {
      e.preventDefault();
      
      if( $('body').hasClass('fullscreen') ) {
        HM._zoom.progress(1);
      } else if( $('#creative .items .item').length == 1 ) {
        HM.controls.progressCreativeWork(1);
        return false;
      } else {
        animateWindowTo( 'next' );
      }

    });
    
    $('#controls ul li.up a').bind('click', function(e) {
      e.preventDefault();

      if( $('body').hasClass('fullscreen') ) {
        HM._zoom.progress(-1);
      } else if( $('#creative .items .item').length == 1 ) {
        HM.controls.progressCreativeWork(-1);
        return false;
      } else {
        animateWindowTo( 'previous' );
      }
    });

    $(document).bind('keydown', 'up', function(e) {
      if( $('#creative .items .item').length == 1 ) { e.preventDefault(); }
      
      $('#controls ul li.up a').trigger('click');
    });
    
    $(document).bind('keydown', 'down', function(e) {
      if( $('#creative .items .item').length == 1 ) { e.preventDefault(); }
      
      $('#controls ul li.down a').trigger('click');
    });
    
    function animateWindowTo( keyword ) {

      $('html,body').stop(false, true);

      // figure out what selector were going to use
      var selectors = {
        // '#homepage': '#homepage .posts .news-item',
        '#creatives': '#creatives .creatives-index .creatives-index-single',
        '#creative': '#creative .header.creative-single-header, #creative .item:not(:first-child)',
        // '#showcase': '#showcase .showcase-single',
        '#interactive': '#interactive-single .paragraph, #interactive-single .images .image',
        '#showcase-single': '#showcase-single .paragraph, #showcase-single .images .image'
      };

      var use_selector = '';
      for( selector in selectors ) {
        if( $(selectors[selector]).length ) {
          use_selector = selectors[selector];
        }
      }
      
      var scrollTop = HM.controls.horizontalScroll( use_selector )[ keyword ];
      
      if( typeof(scrollTop) == 'undefined' ) {
        scrollTop = $(window).scrollTop() + 450;
      }
      
      if( $(window).scrollTop() == 0 && keyword == 'previous' ) {
        return;
      }
      
      $('html,body').stop(false, true).animate({'scrollTop': scrollTop}, {duration: 400, easing: 'easeOutQuint'});
    };
    
    
  };
  
  HM.controls.horizontalScroll = function( selectors ) {
    
    var $selector = $(selectors);
    var header_offset = $('.header.global').outerHeight() + 5;
    
    var offset = 15;
    var offsets = {
      '#showcase-single': 10
    };

      for( selector in offsets ) {
        if( $(offsets[selector]).length ) {
          offset = offsets[selector];
        }
      }
    
    var header_offset = 65 + offset;
    
    // evaluate break points.
    var points = [];
    var elements = {};
    
    points.push(0);
    
    $selector.each(function() {
      var point = $(this).offset().top - header_offset;
      
      elements[ point ] = $(this);
      points.push( point );
    });
    
    points = _(points).uniq();
    
    var currentTop = $(window).scrollTop();
    var maxIndex = 0;
    
    $(points).each(function(i) {
      
      if( points[i] > currentTop ) {
        return false;
      }
      
      maxIndex = i + 0.5;
      
    });
    
    var nextElement = elements[ ( Math.ceil(maxIndex) == 1 ? points[Math.ceil(maxIndex)+1] : points[Math.ceil(maxIndex)] ) ];
    var currentElement = _(elements).toArray()[ Math.max( Math.floor(maxIndex) - 1, 0 ) ];
    
    if( $(window).scrollTop() < points[1] ) { 
      // var currentElement = _(elements).toArray()[ Math.floor(maxIndex) ];
    }
    
    return {
      next: points[Math.ceil(maxIndex)],
      previous: ( points[Math.floor(maxIndex)] == currentTop ? points[ Math.floor(maxIndex)-1 ] : points[ Math.floor(maxIndex) ] ),
      nextElement: nextElement,
      currentElement: currentElement
    };
    
  };
  
  HM.controls.add = function( item ) {
    var item = item.split(',');
    for (var i=0; i < item.length; i++) {
      HM.controls.visible.push( item[i] );
    };
  };
  
  HM.controls.remove = function( item ) {
    var item = item.split(',');
    for (var i=0; i < item.length; i++) {
      HM.controls.visible.remove( HM.controls.visible.indexOf(item[i]) );
    };
  };
  
  HM.controls.render = function( list ) {

    if( !list ) { var list = HM.controls.visible };

    var show_selector = list.join(',');
    var hide_selector = ':not(' + show_selector + ')';
    
    HM.controls.visible = list;
    
    for (var i=0; i < HM.controls.visible.length; i++) {
      if( i == 0 ) {
        $('#controls ul li').filter(HM.controls.visible[i]).prependTo( $('#controls ul') );
      } else {
        $('#controls ul li').filter(HM.controls.visible[i]).insertAfter( $('#controls ul li').eq(i-1) );
      }
    };
    
    var $show = $('#controls ul li').filter( show_selector );
    var $hide = $('#controls ul li').filter( hide_selector );
    
    var animOpts = {
      duration: 500,
      easing: 'easeOutQuint',
      delay: 30
    };
    
    $('#controls ul').removeClass();
    for (var i=0; i < list.length; i++) { $('#controls ul').addClass( 'show-' + list[i].substr(1) ); };
    
    $show.each(function(i) {

      HM.controls.animateProperties( $(this).show().delay(i*animOpts.delay), 0, animOpts );
      
    });
    
    var $animate_list = [];
    $hide.each(function() {
      
      var $li = $(this);
      
      if( parseInt($li.css('left').replace('px')) < 0 ) {
        $li.hide();
      } else {
        $animate_list.push( $li );
      }
      
    });
    
    $( $animate_list ).each(function(i) {
    
      HM.controls.animateProperties( $animate_list[i].delay(i*animOpts.delay), -35, animOpts );
      
    });

  };
  
  
  /*
   * Trigger
   */
  $(document).ready(function() {
    
    HM.controls.bind();
    HM.controls.render();
    
  });
  
  /*
   * Some prototype extensions
   */
  Array.prototype.remove = function(from, to) {
    var rest = this.slice((to || from) + 1 || this.length);
    this.length = from < 0 ? this.length + from : from;
    return this.push.apply(this, rest);
  };
  
  

})(jQuery);


/*
 * Handle next and previous on the "creative single work page"
 */
(function($) {

  HM.controls.progressCreativeWork = function( direction ) {
  
    // calculate currentIndex
    var creativeId = $('#creative .creative-single').attr('data-creative-id');
    var creativeWorks = HM.data.creatives.get('individuals').get(creativeId).get('works');    
    var currentWorkId = $('#creative .items .item').first().attr('data-work-id');
    var currentWorkIndex = creativeWorks.indexOf( creativeWorks.get(currentWorkId) );
    
    // appear id
    var appearIndex = currentWorkIndex + direction;
    appearIndex = ( appearIndex < 0 ? creativeWorks.length - 1 : appearIndex % creativeWorks.length );
    
    HM.controller.navigate( creativeWorks.at(appearIndex).url(), true );
    
  };

})(jQuery);


/*
 * Handle the fading in of elements
 */

(function($) {

  var elems = [
    '#homepage .items .item.large',
    '#homepage .items .item.small img',
    
    '#creatives .items .item',
    '#creatives-single .items .image a img',
    
    '#showcase .items .item p.image img'
  ];
  
  /*
  var time_between = 100;
  // var animation_time = ( Math.random() > 0.5 ? 700 : 1000 );
  var animation_time = 700;
  */
  
  var time_between = 100;
  var animation_time = 1000;

  $(document).ready(function() {
    
    for (var i=0; i < elems.length; i++) {
      $( elems[i] ).each(function(n) {
        
        $(this)
          .css({
            'opacity': 0
          })
          .bind('reveal', function() {

            $(this)
              .delay( time_between*n )
              .animate({
                'opacity': 1
              }, {
                duration: animation_time
              });
              
          });
        
      });
    };
    
  });
  
  $(window).bind('load', function() {
    
    for (var i=0; i < elems.length; i++) {
      $( elems[i] ).trigger('reveal');
    };
    
  });

})(jQuery);

/*
 * Handles the Interactive pages
 */
HM.interactive = {};
(function($) {

  HM.interactive.lineUp = function() {
    
    var itemWidth = 750;
    
    var $itemsContainer = $('#interactive .items');
    var $inside = $itemsContainer.find('.inside');
    var $items = $inside.find('.interactive-slide');
    
    if( !$itemsContainer.length ) { return false; }
    
    $inside.width( itemWidth * $items.length );
    $items.each(function(n) {
      $items.height( $(this).outerHeight() );
    });
    
  };
  
  HM.interactive.bindEvents = function() {
    
    var itemWidth = 750;
    
    var $itemsContainer = $('#interactive .items');
    var $inside = $itemsContainer.find('.inside');
    var $items = $inside.find('.interactive-slide');
    
    var center = function( $this, time ) {
      
      $items.delay(time/3).animate({'opacity':0.6});
      
      var eq = $items.index( $this );
      
      HM.interactive.currentIndex = eq;
      
      $this.delay(time/3).stop(true,true).animate({'opacity':1});
      
      $itemsContainer.stop(true,false).animate({
        'scrollLeft': (eq*itemWidth)
      }, {
        easing: 'easeInOutQuint',
        duration: time
      });
      
    };
    
    HM.interactive._center = center;
    
    $items.bind('center', function() {
      
      center( $(this), 900 );
      
    });
    
    $items.bind('mouseenter', function() {

      if( !$(this).find('a.active').length ) {
        $(this).stop(true).animate({'opacity':0.8});
      }

    }).bind('mouseleave', function() {
    
      if( !$(this).find('a.active').length ) {
        $(this).stop(true).animate({'opacity':0.6});
      }

    });
    
    $items.find('a').bind('click', function(e) {
      if( $(this).hasClass('active') ) {
        HM.controller.navigate($(this).attr('href'), true);
        e.preventDefault();
        return;
      }
      
      e.preventDefault();
      
      $items.find('a.active').removeClass('active');
      $(this).addClass('active');
      
      $(this).parents('.interactive-slide').eq(0).trigger('center');
    });
    
    // now we center the middle one
    // var $center = $items.eq( Math.floor($items.length/2) );
    var $center = $items.eq(0);
    $center.find('a').addClass('active');
    center( $center, 0 );
    
    $items.bind('mouseenter', function() {
    
      if( $(this).find('a.active').length && !$.browser.msie ) {

        $(this).find('.overlay').stop(true).css({'opacity':0}).show().animate({
          'opacity': 1
        });

      }
    
    }).bind('mouseleave', function() {

      if( $(this).find('a.active').length && !$.browser.msie ) {

        $(this).find('.overlay').stop(true).animate({
          'opacity': 0
        }, {
          complete: function() {
            $(this).css({'opacity':0}).hide();
          }
        });

      }

    });
    
  };
  
  HM.interactive.progress = function( direction ) {
  
    var $itemsContainer = $('#interactive .items');
    var $inside = $itemsContainer.find('.inside');
    var $items = $inside.find('.interactive-slide');
    
    $items.eq( (HM.interactive.currentIndex + direction) % $items.length ).find('a').trigger('click');
  };
  
  $(document).ready(function() {
    HM.interactive.lineUp();
    HM.interactive.bindEvents();
  });

})(jQuery);


/*
 * Handle the locking of the footer
 */
HM._footer = {};

(function($) {

  HM._footer.mailingList = function() {
    
    var $mailing_list = $('footer.global .mailing-list');
    var $mailing_list_toggle = $('footer.global #mailing-list-toggle');
    
    if( !$mailing_list.length ) { return; }
    
    // Overlabel
    $mailing_list.find('p.text label').overlabel();
    
    // Display
    $mailing_list_toggle.bind('click', function(e) {
      
      e.preventDefault();
      
      var open = {
        'opacity': 1,
        'marginBottom': 0
      };
      
      var close = {
        'opacity': 0,
        'marginBottom': -5
      }
      
      if( $(this).hasClass('active') ) {
        var css = open;
        var animate = close;
        var after = function() {
          $mailing_list.hide();
        }
      } else {
        var css = close;
        var animate = open;

        $mailing_list.show();
      }
      
      $mailing_list
        .css( css )
        .stop(true,true)
        .animate(
          animate,
          {
            duration: 500,
            easing: 'easeOutQuint',
            after: ( after ? after : function() {} )
          });
      
      $(this).toggleClass('active');
      
    });
  };
  
  // Trigger
  $(document).ready(function() {
    
    HM._footer.mailingList();
    
  });
  

})(jQuery);

(function($) {

  HM._footer.lockFooter = function() {
    
    // Helper functions
    var draw = function() {
      
      // Meat & Bones
      var $footer;
      var max_height;

      $footer = $('footer.global');
      $hm = $('#hm');
      $header = $hm.find('.header.global');
      $body = $hm.find('#body');

      max_height = $header.outerHeight(true) + $body.outerHeight(true);

      if( $(window).height() > (max_height+$footer.outerHeight(true)) ) {
        $footer.addClass('lock');
      } else {
        $footer.removeClass('lock');
      }

    };
    
    draw();
    
    $(window).unbind('resize.lockFooter');
    $(window).bind('resize.lockFooter', function() {
      draw();
    });
    
  }


  $(document).ready(function() {

    HM._footer.lockFooter();

  });

})(jQuery);

(function($) {

	// Keep track of when the page loads
	$(window).bind('load', function() {
		HM.windowLoaded = true;
	});
	
	// And the dom is ready.
	$(document).ready(function() {
	 HM.documentReady = true;
	});

})(jQuery);

(function() {


  HM.getWidthForHeight = function( oWidth, oHeight, height ) {
    return height * (oWidth/oHeight);
  },
  
  HM.getHeightForWidth = function( oWidth, oHeight, width ) {
    return width * (oHeight/oWidth);
  }

})(jQuery);

(function($) {

  HM.generateLink = function( link ) {

    // external or internal
    if( link.search('#') < 0 && link.substr(0,1) != '/' ) {
      return 'target="_blank" href="' + link + '"';
    } else {
    
      if( link.substr(0,1) == '/' ) link = '#' + link;
    
      return 'href="' + link + '"';
    }
    

  };

})(jQuery);

(function($) {

  HM.lessToCss = function( input_less ) {

    var css = '';

    var compiler = new less.Parser();
    compiler.parse( input_less, function(_a,_ruleSet){
      css += _ruleSet.toCSS();
    });
    
    return css;
  
  };

})(jQuery);


(function($) {

  HM._externalLinks = function( input ) {

    $(input).find("a[href^=http]").each(
      function(){
        if(this.href.indexOf(location.hostname) == -1) {
          $(this).attr('target', '_blank');
        }
      }
    );

  }

})(jQuery);

(function() {

  return;

  $(window).one('load', function() {
  
    var backgroundColor = HM.data.misc.get('website_backdrop_color');
    var backgroundImage = HM.data.misc.get('backdropImage');
  
    // Background color
    if( backgroundColor ) {
      
      $('body').stop(true,true).animate({
        'background-color': backgroundColor
      }, {
        duration: 300
      });
      
    }
    
    // Render background image
    if( backgroundImage ) {
      
      var image = new Image();
      image.onload = function() {
        $('body').css({
          'background-image': 'url("' + image.src + '")'
        });
      }
      image.src = backgroundImage;
      
    }
  
  });

})(jQuery);

(function() {

  $(document).ready(function() {
    $('#zoom').hide();
  });
  
})(jQuery);

(function() {

  $(document).ready(function() {
    
    if( $.browser.chrome ) {
      $('html').addClass('isChrome');
    }
    
  });

})(jQuery);

(function() {

  HM.refreshImages = function( element ) {
  
    $(element).find('img').each(function() {
    
      $(this).bind('load', function() {
        $(this).removeClass('loading').addClass('loaded');
      });
      
      // cached images don't fire load sometimes, so we reset src.
      if ( this.complete || this.complete === undefined || $(this).hasClass('loading') ){
      
        var blank = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";
        var src = this.src;
        // webkit hack from http://groups.google.com/group/jquery-dev/browse_thread/thread/eee6ab7b2da50e1f
        // data uri bypasses webkit log warning (thx doug jones)
        this.src = blank;
        this.src = src;

      }
      
      $(this).addClass('loading');
    
    });
  
  };

})(jQuery);

(function() {
  
  HM.windowStop = function() {
    if( window.stop ) {
      window.stop();
    }
  };
  
})(jQuery);

/*
 * Window Location On Hash Change
 */
(function($) {

	$(window).bind('hashchange', function() {
		HM.trackPageView();
	});
	
	HM.trackPageView = function(url) {
		url = (url || '/' + Backbone.history.getFragment())
		
		if (!!_gaq && !!_gaq.push) {
			_gaq.push(['_trackPageview', url]);
		}
		
		if (typeof(pSUPERFLY) != 'undefined') {
			pSUPERFLY.virtualPage(url, document.title);
		}
	}

})(jQuery);
