/* Frontend javascript*/

var highest_z_index     = 1500;
var has_position_fixed  = true;

var Frontend = {
  works_line_break: function(){
    $('.works li').removeAttr('style');
    var max_width   = $('.works').width();
    var used_width  = 0;
    var max_height  = 0;
    var last_work   = 0;
    
    $('.works li').each(function(){
      var height = $(this).height();
      used_width += $(this).width() + 20;
      if(used_width > max_width){
        used_width = $(this).width();
        max_height = height;
      }
      
      if((height <= max_height) && (used_width < max_width)){
        $(this).css('height', max_height + 'px');
      }
      else{
        max_height = height;
      }
    });
  },
  
  scroll_distance_to_top: function(){
    return Frontend.filter_results(
      window.pageYOffset ? window.pageYOffset : 0,
      document.documentElement ? document.documentElement.scrollTop : 0,
      document.body ? document.body.scrollTop : 0
    );
  },

  filter_results: function(n_win, n_docel, n_body) {
    var n_result = n_win ? n_win : 0;
    if (n_docel && (!n_result || (n_result > n_docel)))
      n_result = n_docel;
    return n_body && (!n_result || (n_result > n_body)) ? n_body : n_result;
  }
};

var Work = {
  display_detail: function(target){

    $("#detail_background").show();
    $('#detail_images').removeClass('hidden');
    $('#detail_images').addClass('loading');
    $("#detail_images").show();

    $.ajax({
      url: target,
      type: 'GET',
      data: "mode=ajax",
      dataType: 'json',
      async: true,
      error: function(){
        alert('error loading');
        $("#detail_background").hide();
        $("#detail_images").hide();
      },
      success: function(data){

        var works_data = data.works_data;
        var images = new Array();
        
        try{
          $.each(data, function(image_id, image_array){
            if(image_id != 'works_data'){
              images.push(image_array);
            }
          });
          // Some images to display
          if(images.length > 0){
            var images_pending  = images.length;
            var space_width     = $(window).width();
            var space_height    = $(window).height();
            var needed_width    = 0;
          
            var title           = '';
            var description     = '';
            var url             = '';
            
            $(images).each(function(index){
              title       = (($(this)[0] != undefined && $(this)[0] != null) ? $(this)[0] : '');
              url         = (($(this)[1] != undefined && $(this)[1] != null) ? $(this)[1] : '');
              description = (($(this)[2] != undefined && $(this)[2] != null) ? $(this)[2] : '');
              var img     = new Image();
              $(img).load(function(){
                $('#detail_images').append('<div style="z-index:'+(1500-index)+';" class="invisible" id="image_'+index+'"><h4>'+ $(this).attr('alt') + '</h4>' + $(this).attr('title') +'</div>');
                $('#image_' + index).prepend($(this));
                needed_width = $('#image_' + index + ' img').first().width() + 30 + needed_width;
                images_pending = images_pending - 1;
                
                if(images_pending == 0){
                  $('#detail_images').removeClass('loading');
                  Work.show_images(images.length, needed_width, space_width, space_height);
                }
              }).attr('alt', title).attr('title', description).attr('src', url);

            });
          }
          else{
            $("#detail_images").hide();
            $("#detail_background").hide();
          }
        }
        catch(err){
          $("#detail_background").hide();
          $("#detail_images").hide();
        }
      }
    });
  },
  
  show_images: function(number_of_images, needed_width, space_width, space_height){
    var used_space_left = 0;
    var left_space      = 30;
    var fitting         = (needed_width < space_width - 30);
    var rows            = 1;
    
    if(fitting){
      left_space = (space_width - needed_width + 30) / 2;
    }
    
    for(var i=0; i < number_of_images; i++ ){
      var offset  = 0;
      var top     = 0;
      var left    = 0;
      
      if(!has_position_fixed){
        $('#detail_images').css('position', 'absolute');
        $('#detail_images div').css('position', 'absolute');
        offset = Frontend.scroll_distance_to_top();
      }
      
      // only one image to show
      if(number_of_images == 1){
        top   = (space_height - $('#image_' + i).height()) / 2;
        if(top < 0){
          top = 30;
        }
        left  = left_space;
        if(left < 0){
          left = 20;
        }
        $('#image_' + i).css('top', (top + offset) + 'px').css('left', left + 'px').css('width', $('#image_' + i + ' img').first().width() +'px').removeClass('invisible');
      }
      // all fitting beside each other
      else if(fitting || (!fitting && number_of_images != 3)){
        
        top   = (space_height - $('#image_' + i).height()) / 2;
        if(top < 0){
          top = 30;
        }
        left  = ((i == 0) ? left_space : (used_space_left + 30) );
        if(left + $('#image_' + i + ' img').first().width() > space_width){
          left  = left_space;
          rows  += 1;
        }
        if(number_of_images == 2 && !fitting && i == 1){
          left  = space_width - 30 - $('#image_' + i + ' img').first().width();
        }
        
        $('#image_' + i).addClass('rows' + rows).css('top', (top + offset) + 'px').css('left', left + 'px').css('width', $('#image_' + i + ' img').first().width() +'px').removeClass('invisible');

        used_space_left = $('#image_' + i + ' img').first().width() + left;
      }
      // three images not fitting
      else{
        top   = (space_height - $('#image_' + i).height()) / 2;
        if(top < 0){
          top = 30;
        }
        left  = ((i == 0) ? left_space : (used_space_left + 30) );
        
        if(i == 1){
         left = space_width - $('#image_' + i + ' img').first().width() - 30;
         top  = space_height - $('#image_' + i).height() - 20;
        }
        
        else if(i == 2){
         left = (space_width - $('#image_' + i + ' img').first().width()) / 2;
        }
        else{
          top = 10;
        }
        
        $('#image_' + i).css('top', (top + offset) + 'px').css('left', left + 'px').css('width', $('#image_' + i + ' img').first().width() +'px').removeClass('invisible');

        used_space_left = $('#image_' + i + ' img').first().width() + left;
      }
    }
    $("#detail_images div").click(function(){
      var current_index = highest_z_index;
      highest_z_index   += current_index + 100;
      $(this).css("z-index", (current_index + 100));
    });
  }
};

$(document).ready(function(){
  if(navigator.platform == 'iPad' || navigator.platform == 'iPhone' || navigator.platform == 'Android' || navigator.platform == 'iPod'){
    has_position_fixed = false;
  }
  
  $("#detail_background").css("height", $(document).height());
  Frontend.works_line_break();
  
  $(window).bind("resize", function(){  
    $("#detail_background").css("height", $(document).height());
    Frontend.works_line_break();
  });
  
  // register clicks on all thumbnails
  $(".works li a").click(function(){
    $("#detail_background").show();
    Work.display_detail($(this).attr('href'));
    return false;
  });  
  
  $("#detail_background").click(function(){
    $("#detail_images").hide();
    $("#detail_background").hide();
    
    $("#detail_images").addClass('hidden');
    $("#detail_images").empty();
    return false;
  });
  
});

// document ready issue in webkit
if($.browser.webkit){
  $(window).load(function(){
    $("#detail_background").css("height", $(document).height());
  });
}

// IE extension for image load handling
if($.browser.msie){
  (function ($) {
  $.event.special.load = {
    add: function (hollaback) {
      if ( this.nodeType === 1 && this.tagName.toLowerCase() === 'img' && this.src !== '' ) {
        // Image is already complete, fire the hollaback (fixes browser issues were cached
        // images isn't triggering the load event)
        if ( this.complete || this.readyState === 4 ) {
          hollaback.handler.apply(this);
        }

        // Check if data URI images is supported, fire 'error' event if not
        else if ( this.readyState === 'uninitialized' && this.src.indexOf('data:') === 0 ) {
          $(this).trigger('error');
        }
        
        else {
          $(this).bind('load', hollaback.handler);
        }
      }
    }
  };
}(jQuery));
}
