$(function() {
  var main      = $('#images .main');
  var secondary = $('#images .secondary');
  loaded_preview_ids = [];
  
  secondary.load(function() {
    $this = $(this);
    $('#images img.spinner').hide();
    $this.fadeIn(250, function() {
      main.attr('src', $this.attr('src')).show();
      $this.hide();
    });
  });
  
  var main_fade_out = function() {
    var map = $('#map');
    
    if(map.hasClass('selected')) {
      main.hide();
      $('#images .label img').hide().fadeIn(300);
      map.fadeOut(250);
      
    } else {
      main.fadeOut(250);
    }
  };
  
  $('#images img.preview').click(function() {
    var new_id       = parseInt($(this).attr('data-id'));
    var new_filename = $(this).parent().attr('href');
    
    if(main.attr('data-id') != new_id) {
      main.attr('data-id', new_id);
      
      if($.inArray(new_id, loaded_preview_ids) == -1)
        $('#images img.spinner').show();
      
      main_fade_out();
      // webkit will not trigger the laod event if the new and old src value are the same
      secondary.attr('src', '').attr('src', new_filename);
      $('#map').removeClass('selected');
    }
    
    return false;
  });
  
  $('.map_preview').click(function() {
    var map = $('#map');
    if(map.hasClass('selected'))
      return false;
    
    main.attr('data-id', 'map');
    map.hide().css('opacity', 1).css('filter', null).fadeIn(250);
    map.addClass('selected');
  });
});

$(window).load(function() {
  $('#images img.preview').each(function() {
    var $this = $(this);
    
    $('<img>')
      .load(function() {loaded_preview_ids.push(parseInt($this.attr('data-id')))})
      .attr('src', $this.parent().attr('href'));
  });
});



$(function() {
  $('#content .back_to_top').click(function() {
    $('html, body').animate({scrollTop: 0}, 'slow');
    return false;
  });
});
