/*

All is full of code

*/

$(function(){
  if (! $.browser.msie)
  {
  
  var base_url = $('input[name=base_url]').val();
  var fade_time = 500;
  var title_prefix = 'Michael Frahm — ';
  var img_no;
  var img_total = 0;
  var sidebar_opacity = 0.6;
  var hover_fade = 300;
  var agent = navigator.userAgent.toLowerCase();
  var is_iphone = (agent.indexOf('iphone')!=-1);
  
  // Array Remove - By John Resig (MIT Licensed)
  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);
  };
  
  function fade()
  {
    
    var interval = setInterval(timer, 200);
    var visibility = true;
    var time = 0;
    var mousemove = false;
    var fade_el = $('.fade');
    
    function resetTimer()
    {
      time = 0;
      if ( visibility === false )
      {
        fade_el.stop().fadeTo(fade_time, 1);
      }
      visibility = true;
    }
    
    function timer()
    {
      time++;
      if( time > 10 && visibility)
      {
        visibility = false;
        fade_el.stop().fadeTo(1200, 0);
      }
    }
    
    $('body').mousemove(function(e){
      resetTimer();
    });
    
  }
  
  function image_count()
  {
    
    var image_count_el = $('.image_count');
    var image_count = 0;
    var counter = 0;
    
    image_count = parseInt( image_count_el.html(), 10);
    image_count_el.html('');
    
    
    var count_interval = setInterval(timer, 100);
    
    function timer()
    {
      counter ++;
      if (counter < 10)
      {
        image_count_el.html('0' + counter);
      }
      else
      {
        image_count_el.html(counter);
      }
      
      if ( counter == image_count )
      {
        clearTimeout ( count_interval );
        return false;
      }
      
    }
    
  }
  
  function load_picture()
  {
    
    var url,
        rel,
        direction,
        position_el;
    var rm_img_no = /\d*$/;
    
    
    $('a.next, a.prev').live('click', function(){
      
      show_loader();
      
      position_el = $('.position');
      url = $(this).attr('href');
      rel = $(this).attr('rel');
      img_no = parseInt(url.split('/').pop(), 10);
      
      if ($(this).hasClass('prev'))
      {
       direction = 'prev';
      }
      else
      {
        direction = 'next';
      }
      
      $.ajax({
        
        type    : 'POST',
        url     : url,
        data    : ({
          type  : 'load_image'
        }),
        success : function(data)
        {
          
          $('#image_container').html(data).hide().fadeTo(fade_time, 1);
          
          img_total = parseInt( $('#image_count').val(), 10);
          
          if ( direction == 'next' )
          {
            if ( (parseInt(position_el.html(), 10) + 1) < 10 )
            {
              position_el.html('0'+(parseInt(position_el.html(), 10) + 1) );
            }
            else
            {
              position_el.html( parseInt(position_el.html(), 10) + 1 );
            }
          }
          else
          {
            if ( (parseInt(position_el.html(), 10) - 1) < 10 )
            {
              position_el.html('0'+(parseInt(position_el.html(), 10) - 1) );
            }
            else
            {
              position_el.html( parseInt(position_el.html(), 10) - 1 );
            }
          }
          
          if ( img_no == img_total )
          {
            $('a.next').hide();
          }
          else
          {
            $('a.next').css({'display':'inline'});
          }
          
          if ( img_no == 1 )
          {
            $('a.prev').hide();
          }
          else
          {
            $('a.prev').css({'display':'inline'});
          }
          
          $('a.next').attr('href', url.replace(rm_img_no, (img_no+1))).attr('rel', rel.replace(rm_img_no, (img_no+1)));
          $('a.prev').attr('href', url.replace(rm_img_no, (img_no-1))).attr('rel', rel.replace(rm_img_no, (img_no-1)));   
          
          $.address.value(rel);
        }
        
      });
      
      return false;
      
    });
    
  }
  
  function key_navigation()
  {
    
    function check_key(e)
    {
      switch (e.keyCode)
      {
        case 37: // Left arrow key
          if ( img_no == 1 )
          {
            return false;
          }
          else
          {
            $('a.prev').trigger('click');
          }
        break;
        case 39: // Right arrow key
          if ( img_no == parseInt( $('#image_count').val(), 10) )
          {
            return false;
          }
          else
          {
            $('a.next').trigger('click');
          }
        break;
      }
      
    }

    if ($.browser.mozilla)  { $(document).keypress(check_key); }
    else                    { $(document).keydown(check_key); }
    
  }
  
  function load_page()
  {
    
    $('#sidebar a.load').click(function(){
      
      url = $(this).attr('href');
      
      show_loader();
      
      $.ajax({
        
        url     : url,
        success : function(data)
        {
          $('#content').html(data).hide().fadeTo(fade_time, 1);
          image_count();
          
          fade();
          
        }
      
      });
      
      $('#sidebar li').removeClass('active').children('.comment, span').fadeOut(fade_time);
      
      if ( $(this).parents('ul#work').length > 0 )
      {
        $(this).siblings('.comment, span').fadeIn(fade_time).parent('li').addClass('active');
      }
      else
      {
        $(this).parent('li').addClass('active');
      }
      
      $('#sidebar li:not(.active)').fadeTo(hover_fade, sidebar_opacity);
      
      return false;
      
    });
    
  }
  
  function show_loader()
  {
    $('#image_container').hide().delay(fade_time).html('<img src="' + base_url + 'public/images/general/loader.gif" alt="Loading..." class="loader" />').fadeTo(fade_time, 1);
  }
  
  function css()
  {
    
    $('.js_hide').hide();
    $('a.comment').css({'cursor':'default'});
    
  }
  
  function hover_states()
  {
    
    $('#sidebar li a').hover(function(){
      
      $(this).parent('li').stop().fadeTo(hover_fade, 1);
      
    },function(){
      
      $(this).parent('li:not(.active)').stop().fadeTo(hover_fade, sidebar_opacity);
      
    });
    
  }
  
  function show_comment()
  {
    
    $('a.comment').hover(function(){
      
      $('<div id="comment_wrapper" class="opacity93"><div id="comment"><div class="col1 left">' + $(this).siblings('input[name=desc1]').val() + '</div><div class="col2 right">' + $(this).siblings('input[name=desc2]').val() + '</div></div></div>').appendTo('#content').hide().fadeIn(fade_time);
      
    },function(){
      
      $('#comment_wrapper').fadeOut(fade_time).delay(fade_time).remove();
      
    });
    
    $('a.comment').click(function(){
      return false;
    });
    
  }
  
  function deep_linking()
  {
    var title;
    
    $('#sidebar a:not(.comment)').address(function(){
      
      title = $(this).html();
      
      if ( title == 'Michael Frahm' )
      {
        title = 'Home';
      }
      
      $.address.title( title_prefix + title.replace(/(<([^>]+)>)/ig," ") );
    });
    
  }
  
  function load_deep_linking()
  {
    
    var url;
    var address;
    var title;
    
    img_no = parseInt(window.location.href.split('/').pop(), 10);
    
    if ( isNaN(img_no) )
    {
      img_no = 1;
    }
    
    $.address.externalChange(function(event){
        
      address = $.address.value().substr(1).split('/');
      if ( address != '' )
      {
        
        show_loader();
        
        $('#sidebar li').each(function(){

          if ( $('a:eq(0)', this).attr('rel') == 'address:/' + address[0] )
          {
            
            $(this).addClass('active').removeClass('opacity60').children('.comment, span').show();
            
            if ( address.length == 2 )
            {
              url =  $('a:eq(0)', this).attr('href')+'/'+address[1];
            }
            else
            {
              url =  $('a:eq(0)', this).attr('href');
            }
            
            title = $('a:eq(0)', this).html();
            
            $.ajax({
              url     : url,
              success : function(data)
              {
                $('#content').hide().html(data).fadeTo(fade_time, 1);
                $.address.title( title_prefix + title.replace(/(<([^>]+)>)/ig,' ') );
                image_count();
                fade();
              }

            });

            return false;
          }

        });
        
      }
      
    });
    
  }
  
  function use_arrows()
  {
    
    var first_time = true;
      
    $('a.next').live('mouseover mouseout', function(event) {
      if ( first_time == true )
      {
        if (event.type == 'mouseover')
        {
          $('#img_nav').append('<div id="use_arrows" class="hide"><p>Please use your arrow keys to navigate between the pictures</p></div>');
          $('#use_arrows').fadeTo(hover_fade, 1).delay(5000).fadeOut('fast');
          first_time = false;
        }
      }
    });
    
    
    
    
  }
  
  function a_ext()
  {
    $('a[rel=ext]').live('click', function(){
      window.open(this.href);
      return false;
    });
  }
    if (is_iphone === false) {
      try { fade(); }               catch(e)  { /*console.log(e);*/ }
    }
    try { load_picture(); }       catch(e)  { /*console.log(e);*/ }
    try { key_navigation(); }     catch(e)  { /*console.log(e);*/ }
    try { image_count(); }        catch(e)  { /*console.log(e);*/ }
    try { load_page(); }          catch(e)  { /*console.log(e);*/ }
    try { css(); }                catch(e)  { /*console.log(e);*/ }
    try { show_comment(); }       catch(e)  { /*console.log(e);*/ }
    try { deep_linking(); }       catch(e)  { /*console.log(e);*/ }
    try { load_deep_linking(); }  catch(e)  { /*console.log(e);*/ }
    try { hover_states(); }       catch(e)  { /*console.log(e);*/ }
    try { use_arrows(); }         catch(e)  { /*console.log(e);*/ }
    try { a_ext(); }              catch(e)  { /*console.log(e);*/ }
  }

  
  
});
