window.scrollTo(0,1); // Hides address bar on iPhone
$('a.lightbox').fancybox(); // Enable fancybox

// Book now - GA tracking
$('a[data-track]').live('click', function() { _gaq.push(['_trackEvent', 'Downloads', $(this).data('track'), $(this).attr('href')]); });

// Smooth scroll
$('a[href^=#]').live('click', function(e) {
  e.preventDefault();
  var $this = $(this), $page = $('html, body'), $target = $(this.hash), target = this.hash;
  if (!$target.length) return;
  targetOffset = $target.offset().top;
  $page.animate({ scrollTop: targetOffset }, 400, function() { location.hash = target; });
});

// Shortlist
$('.category').each(function() {
  var $this = $(this), $handle = $this.find('h1'), $content = $this.find('.wrap').hide();
  $handle.click(function() {
    $handle.toggleClass('active');
    ($handle.hasClass('active')) ? $content.show() : $content.hide();
  });
});

// Gallery
var $gallery = $('#intro'), $images = $gallery.find('img'), $cont = $images.parent();

var loop = 0, loaded = 0, start_from = $images.length, loaded_images = [], $loaded_images;

$.each(gallery_images, function(i, img) {
  var $img = $(new Image());
  $img.load(function() {
    loaded++;
    loaded_images[i] = $img;
    if (gallery_images.length - loaded === 0) { $loaded_images = $(loaded_images); refresh_gallery(); }
  }).prop('src', img.url + (loop === 0 ? '/crop:500x600:' : '/crop:600x400:') + img.crop_weight);
  loop = (loop === 0) ? 1 : 0;
});

var refresh_gallery = function() {
  setTimeout(function() { 
    var next_left = $loaded_images[start_from] || false
    var next_right = $loaded_images[start_from+1] || false
    if (next_left) start_from++;
    if (next_right) start_from++;
    if (!next_left || !next_right) { start_from = 0; refresh_gallery(); return; }
    
    $images.addClass('inactive');
    setTimeout(function() {
      if (next_left) $images.first().prop('src', next_left.prop('src'));
      if (next_right) $images.last().prop('src', next_right.prop('src'));
      $images.removeClass('inactive');
      setTimeout(refresh_gallery, 1000);
    }, 1000);
  
  }, 3000);
};

// Testimonials
// var articles = $('#testimonials article').hide(), current_testimonial = articles.first().show();
// setInterval(function() {
//   next = current_testimonial.next('article');
//   if (!next.length) next = articles.first();
//   current_testimonial.fadeOut(function() { next.fadeIn(); });
//   current_testimonial = next;
// }, 5000);
