$( function() {

  function init () {
    url = window.location.href;
    if (url.split('/').length < 5 && url.indexOf('#') == -1)
    {
      //$('#submenudiv, #wall, #auth, #textcontent, #video').hide();
    }
    current_url = document.location.hash;

    //if (!$.browser.msie)
    checkHistory();
    
    if (current_url != "") {
      handleLoad(getHash(current_url).substr(1));
    }
  }

  
  $('.js_show').show();
  
  $('.colorchartlink').bind('click', function() {
    $('.close_colorchart').show();
    $('.colorchart').fadeIn('slow');
    return false;
  });
  $('a.close_colorchart').bind('click', function() {
    $('.colorchart').fadeOut('slow');
    return false;
  });
  $('#text_content').jScrollPane();

  if ($('#'+active_container).children().length*238 > 952) {
    $('#scroll_right,#scroll_left').show();
  };
  
  $('#scroll_right').bind('click', function() {
    var left = pxToNumber($('#'+active_container).css('left'));
    var offset = String((-952+left)*actualSize())+"em";
    var image_bar_width = $('#'+active_container).children().length*238;
    
    if ((left-952)*actualSize() > -(image_bar_width*actualSize()))
    {
      jQuery.easing.def = "easeInOutQuad";
      $('#'+active_container+':not(:animated)').animate({left: offset }, 2000);
    }

  });

  $('#scroll_left').bind('click', function() {
    var left = pxToNumber($('#'+active_container).css('left'));
    if (left < 0)
    {
      var offset = (952+left)*actualSize();
      offset = (offset == 0)? 0 : String( offset ) + "em";
      jQuery.easing.def = "easeInOutQuad";
      $('#'+active_container+':not(:animated)').animate({left: offset }, 2000, function() {
        if (offset == 1)
          $('#'+active_container).css({left: '0em'});
      });
    }
  });
  
  $('.tslink').live('click', function() {

    var href = $(this).attr('href');

    if (href != getHash(window.location.hash).substr(1))
    {
      writeHistory();
      $('.tslink').removeClass('active');
      $('#text_content').fadeTo(200,0);
      $('#sidebar').fadeTo(200,0, function () {
        window.location = getHash(href);
      });

      //$('#image_container').fadeTo(200,0, function() {
      //});
    }
        
    return false;
  });

  init();

});

function imageLoader(src, alt, div) {
  var img = new Image();
  
  $(img)
    .load(function () {
      $(this).hide();
      $('.'+div).append(this);
      $(this).fadeIn(300, function() {
        images_loading--;
        if (images_loading == 0)
        {
          $('#'+inactive_container).fadeOut(300, function() {
            $('#'+inactive_container).empty();
            $('#scroll_right,#scroll_left').toggle($('#'+active_container).children().length*238 > 952);
          });
        }
      });
    })

    .error(function () {
      images_loading--;
    })

    .attr('src', src).attr('alt', alt);
}

function handleLoad(href) {
  $.get(href,'', function(json, textStatus) {
    var image_bar = "";
    var sub_menu = "";
    var sidebar = "";
    var obj = "";
    if (json.tomshot.images.length)
    {
      active_container = (active_container == "temp_container")? 'image_container': 'temp_container';
      inactive_container = (active_container == "image_container")? 'temp_container': 'image_container';
      $('#'+active_container).css({'z-index': 2});
      $('#'+inactive_container).css({'z-index': 1});
      $('#'+active_container).empty().show();

      for (var i=0; i<json.tomshot.images.length; i++) {
        obj = json.tomshot.images[i];
        if (!obj.src) 
        {
          $('#'+active_container).append("<div class='"+obj.className+"'>&nbsp;</div>");
        } else {
          $('#'+active_container).append("<div class='"+obj.className+" imagepos"+active_container+String(i)+"'></div>");
          images_loading++;
          imageLoader(obj.src, obj.alt, 'imagepos'+active_container+String(i));
        };
      }
    }
    
    if ($.isArray(json.tomshot.sidebar))
    {
      for (var i=0; i<json.tomshot.sidebar.length; i++) {
        obj = json.tomshot.sidebar[i];
        try {
          if (obj.href)
          {
            sidebar += '<li><a href="'+obj.href+'" class="'+obj.classes+'">'+obj.title+'</a></li>';
          } else {
            sidebar += '<li><span class="active">'+obj.title+'</span></li>';
          }
        } catch (e) {};
      }
      try
      {
        obj = json.tomshot.extra_button;
        sidebar += '<li class="'+obj.classes+'"><a href="'+obj.href+'"><img src="'+obj.image+'" alt="'+obj.alt+'" /></a></li>';
      } catch(e) {};
      sidebar = '<ul>'+sidebar+'</ul>';
    } else {
      sidebar = "<p><span class='active'>"+json.tomshot.sidebar.title+"</span></p>";
    }
    if (json.tomshot.sub_menu.length > 1)
    {
      for (var i=0; i<json.tomshot.sub_menu.length; i++) {
        obj = json.tomshot.sub_menu[i];
        spacer = (i < json.tomshot.sub_menu.length-1)? " /" : "";
        sub_menu += '<li><a href="'+obj.href+'" class="'+obj.classes+'">'+obj.title+'</a>'+spacer+'</li> \n';
      }
      sub_menu = '<ul>'+sub_menu+'</ul>';
    }
    $('#submenu').html(sub_menu);
    $('#sidebar').html(sidebar);
    $('#text_content').html(json.tomshot.content);
    if (!$.browser.msie)
      $('title').html(json.tomshot.title);
    $('#sidebar').fadeTo(300, 1);
    $('#text_content').fadeTo(200, 1, function() {
      if (!$('.jScrollPaneDrag').css('display')) {
        $('#text_content').css({'overflow': 'visible'});
      }
    });
    $('#text_content').jScrollPane();
    
    current_url = getHash(document.location.hash);
    rExp = /\//gi;
    highlights = "."+current_url.substring(2, current_url.length-1).replace(rExp,',.');

    $(highlights).addClass('active');
        
  },'json');
};

function actualSize() {
  var size = pxToNumber($('html').css('font-size'));
  return (size/16)/size;
}

function pxToNumber(val)
{
  if (String(val).indexOf('em') != -1)
  {
    var size = pxToNumber($('html').css('font-size'));
    val = Number(String(val).replace('em', ''))*size;
  } else {
    val = Number(String(val).replace('px', ''));
  }
  return val;
}

var jJSON = {
    getValues: function(obj,num) {
        return jJSON[obj]["values"].slice(0,((num == null) ? jJSON[obj]["values"].length : num));
    },
    getCount: function(obj) {
        return jJSON[obj]["count"];
    }
};

function getHash(url)
{
  if (url === undefined) return "#";

  loc = "http://"+window.location.host+"/";
  url = url.replace(loc, '');
  url = url.replace('#', '');
  if (url.indexOf('/') != 0)
  {
    url = '#/'+url;
  } else {
    url = '#'+url;
  }
  return url;
}

function writeHistory()
{
  $('#history').prepend('<a href="'+window.location+'" />');
}

function checkHistory()
{
  ht = setTimeout("checkHistory()",500);
  hash = window.location;
  if ($('#history a:first-child').attr('href') != undefined)
  {
    if ($('#history a:first-child').attr('href') != hash)
    {
      loc = "http://"+window.location.host+"/";
      url = window.location.hash.replace(loc,'');
      handleLoad(getHash(url).substr(1));
      $('#history').empty();
      writeHistory();
    }
  }
}

var active_container = "image_container";
var inactive_container = "temp_container";

var images_loading = 0;
var do_scroll = false;
