$(function(ready){
  previousHtml = $('#left').html();
  //previousTitle = document.title;
	
	$(window).hashchange(function(){
		var $id = location.hash.substr(9);
		if ($id) {
			project($id);
		} else
			$('#left').html(previousHtml);
	});
	
	$(window).hashchange();
  
  $('#global-ajax-loader').show();
  $.get('theme/widgets/portfolio/ajax/portfolio.php', function(d){
    $('#portfolio-content').html(d);
    $('#global-ajax-loader').hide();
    
    $('.projects a').live('click', function(e){
      e.preventDefault();
			var $id = $(this).attr('rel');
			window.location = '#project/'+$id;
      //project($id);
    });
  });
  
  function project($id) {
    $('#global-ajax-loader').show();
    $.get('theme/widgets/portfolio/ajax/project.php', { id: $id }, function(d){
      var $json = $.parseJSON(d);
      //document.title = $json.title;
      $('#left').html($json.page);
			$('#left #image-list img').load(function(){
				$.scrollTo('#left', 300);
				$('#global-ajax-loader').hide();
			});
      $('#return-index').click(function(){
        $('#left').html(previousHtml);
        //document.title = previousTitle;
        $.scrollTo('#portfolio-content', 300);
      });
    });
  }
  
  $('#thumb-list img').live('click', function(){
		if ($(this).hasClass('youtube')) {
			$.fancybox({
				href: $(this).parent().attr('href').replace(new RegExp("watch\\?v=", "i"), 'v/'),
				type: 'swf'
			})
			return false;
		}
    $.scrollTo('#left', 300);
    var $id = $(this).attr('rel');
    $(this).addClass('selected')
    $('#image-list li').hide();
    $('#image-list li.image_'+$id).show();
		return true;
  });
  
  $('#image-list a').live('click', function(e){
    e.preventDefault();
    $.fancybox({
      href: $(this).attr('href')
    });
  });
  
  $('#portfolio-toggle a').click(function(){
    $(this).toggleClass('less');
    $('#portfolio-content > ul').removeClass('off-index');
    if ($(this).hasClass('less'))
      $('#portfolio-content > ul').slideDown(200);
    else
      $('#portfolio-content > ul').slideUp(200);
  });
});
