$(document).ready(function(){
	
	if ($('#main_content').length == 0) {
		window.location = '/';
	}
  
  var home_content = $('#main_content').html();
  
    // DEFAULT EASE TYPE:
  jQuery.easing.def = "easeOutExpo";
  
    // SCALE FEATURES SLIDER:
  $(window).resize(
    function(){
      $('#features').css('margin-left', ($(window).width() - $('#features').width()) * 0.5);
    }
  ).trigger('resize');

    // SETUP SLIDERS:
  Galleria.loadTheme('js/libs/galleria/themes/sp/galleria.sp.js');
  $('#features').galleria({
    autoplay: true,
    pause_on_interaction: false,
    show_info: true,
    transition_initial: 'fade',
    transition_speed: 1000,
    thumbnails: false
  });
  /*
  $('.views').galleria({
    autoplay: false,
    transition_initial: 'fade',
    thumbnails: false
  });
  */
  var load_home = function(location){
    $('.category').hide();
    $('.controller').hide();
    $('#portfolio').slideUp('slow', function(){
      $('body').attr('id', 'home');
      $('#primary .block').height(0).empty().siblings('.category').empty();
      $('#secondary .block').height(0).empty().siblings('.category').empty();      
      $('#slider').slideDown('slow');
      $('#main_content').slideDown('slow');
      $('#main_nav .selected').removeClass('selected');
      Galleria.get(0).play();
      $('#main_content').html(home_content);
    });
  };
  
  var load_input = function(location){
    var id = location.split('/')[0].replace('.php',''),
        main = $('#main_content');
        
    $('#main_content').empty(); // .slideDown('slow');
        
    $('footer').hide();
    $('.category').hide();
    $('.controller').hide();
    $('#portfolio').slideUp('slow');
    $('#slider').slideUp('slow', function(){
      
      $('#primary .block').height(0).empty().siblings('.category').empty();
      $('#secondary .block').height(0).empty().siblings('.category').empty();      
      $('#main_nav .selected').removeClass('selected');
      $('#nav_'+id).addClass('selected');
      
      Galleria.get(0).pause();
      
      $.ajax({
        url: location,
        type: "GET",
        dataType: 'html',
        success: function(data){
          var content = $(data).find('.content');
          if (content) {
            main.fadeTo('slow', 0, function(){
        	    $('body').attr('id', id);
              $(this).html(content).fadeTo('slow', 1);
        	    if(id == 'about'){
	              $('#about section#main_content .group').masonry({ 
									singleMode: true,
									resizeable: false
								});
							}
        	    if(id == 'contact'){
        	    	setup_contact();
        	    }
        	    
        	    $('footer').delay(500).fadeIn('slow');
							
            })
          }
        }
      });
      
    });    
  };
  
  var load_output = function(location){
    var id = location.split('/')[0].replace('.php',''),
        nav_item = $('#nav_'+id),
        main = $('#main_content'),
        p = $('#primary'),
        s = $('#secondary'),
        storage = {title: null, block: null};
        
    $.ajax({
      url: location,
      type: "GET",
      dataType: 'html',
      success: function(data){
        var pb = $('#primary .block'),
            pc = $('#primary .category'),
            sb = $('#secondary .block'),
            sc = $('#secondary .category'),
            content;            
            
        if (data) {
          try { content = $(data).find('.article') } catch (e) {}
        }
        
        if (content) {
          
          $('#portfolio').show();
          
          $('#main_content').slideUp(function(){
            $(this).empty();
          });
          nav_item.addClass('selected');
          
            // DISABLE SLIDER:
          if ($('#slider').css('opacity') == 1) {
            $('#slider').slideUp('slow', 0, function(){
              Galleria.get(0).pause();
            });
            // $('#main_content').slideUp('slow');
          }
          
            // LOAD INTO APPROPRIATE COLUMN
          if (pb.children().length === 0) {
            
            pc.text(id).show();
            pb.empty().html(content);
            pb.find('.article').removeClass('current');
            pb.find('.article:first').addClass('current');
            
          } else if (sb.children().length === 0) {
            
            sc.text(id).show();
            sb.empty().html(content);
            sb.find('.article').removeClass('current');
            sb.find('.article:first').addClass('current');
            
          } else {
            
            storage.title = sc.text();
            storage.block = sb.clone();
            
            pc.text(storage.title).show();
            pb.empty();
            pb.html($(storage.block).find('.article'));
            pb.find('.article').removeClass('current');
            pb.find('.article:first').addClass('current');
            
            sc.text(id).show();
            sb.empty();
            sb.html(content);
            sb.find('.article').removeClass('current');
            sb.find('.article:first').addClass('current');
            
          }
          
            // HIDE ARTICLE CONTROLLERS:
          if (pb.find('.article').length > 1) {
            p.find('.controller').show();
          } else {
            p.find('.controller').hide();
          }
          if (sb.find('.article').length > 1) {
            s.find('.controller').show();
          } else {
            s.find('.controller').hide();
          }
          
            // RESET POSITIONING:
          pb.scrollTop(0);
          sb.scrollTop(0);
          
          update_nav();
          
            // GALLERIA BEHAVIOUR (OR LACK THERE OF):            
          if ($.browser.msie && $.browser.version === '7.0') {
            $('.block .pages').find('img:not(:first)').css('display', 'none');
          } else {
            $('.block .pages').each(function(i, el){
							/*
              if ($(el).find('img').length > 1) {
                $(el).galleria({autoplay: false, thumbnails: true, transition_initial: 'fade'});
              }
              */
              if ($(el).find('img').length > 1 || $(el).find('iframe').length > 1) {
	            	$('.article_nav').css('visibility', 'visible');
								// Slider stuff
								
								$("#sp_slider").scrollable({
								
									// basic settings
									vertical: true,
								
									// up/down keys will always control this scrollable
									keyboard: 'static',
								
									// assign left/right keys to the actively viewed scrollable
									onSeek: function(event, i) {
										horizontal.eq(i).data("scrollable").focus();
									}
								
								// main navigator (thumbnail images)
								}).navigator("#main_navi");
								
								// horizontal scrollables. each one is circular and has its own navigator instance
								var horizontal = $(".scrollable").scrollable({ circular: true }).navigator(".article_nav");
								
								
								// when page loads setup keyboard focus on the first horzontal scrollable
								horizontal.eq(0).data("scrollable").focus();

              }              
            });
          }
          
            // SETUP ARTICLE HEIGHT:
          if (pb.children().length) {
            pb.height(p.find('.article:first').height());
          }
          
          if (sb.children().length) {
            sb.height(s.find('.article:first').height());
          }
          
            // FIX FOR IE NOT RESIZING:
          $(window).trigger('resize');
          
        } // END if (content)
      }
    });
  };
    
  var update_nav = function(){
    $('#main_nav li.selected').each(function(i, el){
      var current = $(el).attr('id').replace('nav_', '');
      if (current != $('#primary .category').text().toLowerCase() && 
          current != $('#secondary .category').text().toLowerCase()) {
        $(el).removeClass('selected');
      }
    });
  };
  
  var prev_work = function(target){
    if (target.find('.current').prev().length > 0) {
      target.find('.current').removeClass('current').prev().addClass('current');
    } else {
      target.find('.current').removeClass('current');
      target.find('.article').last().addClass('current');
    }
    if (target.find('.current')) {
      target
        .scrollTo('.current', 500)
        .animate({
          height: target.find('.current').height()
          }, 250);
    }
  };
  
  var next_work = function(target){
    if (target.find('.current').next().length > 0) {
      target.find('.current').removeClass('current').next().addClass('current');
    } else {
      target.find('.current').removeClass('current')
      target.find('.article').first().addClass('current');
    }  
    if (target.find('.current')) {
      target
        .scrollTo('.current', 500)
        .animate({
          height: target.find('.current').height()
          }, 250);
    }
  };
  
  $('.select_prev').click(function(evt){
    evt.preventDefault();
    prev_work($(this).parent().parent().find('.block'));
  });
  
  $('.select_next').click(function(evt){
    evt.preventDefault();
    next_work($(this).parent().parent().find('.block'));
  });
  
  $('#logo').click(function(evt){
    evt.preventDefault();
    load_home();
  });
  
  $('#main_nav a').click(function(evt){
    evt.preventDefault();
    var that = this,
        id = $(that).parent().attr('id').replace('nav_', ''),
        location = $(that).attr('href'),
        type = $(that).attr('class'),
        already_loaded = false;
    
    switch (type) {
      case "input" :
        load_input(location);
        break;
      case "output" :
        $('#portfolio .category').each(function(i, el){
          if (id === $(el).text().toLowerCase()) already_loaded = true;
        });        
        if (!already_loaded) load_output(location);
        break;
    }
    
  }).parent().css('visibility', 'visible');
	
	// TWITTER 
	
	$('#twitter ul:last-child').addClass('last');
	
	// Older tweets
	$('#past').click(function(evt){
		evt.preventDefault();
		$('#future').removeClass('disabled');
		if( !$('.active_tweets').hasClass('last') ){
			$('#past').removeClass('disabled');
			$('.active_tweets').fadeOut(400, function(){
				$(this)
					.removeClass('active_tweets')
					.next('ul')
					.fadeIn(400, function(){
						$(this).addClass('active_tweets');
						if($(this).is(':last-child')){
							$('#past').addClass('disabled');
						}
						else {
							$('#past').removeClass('disabled');
						}						
					});
			});
		}
		else {
			$('#past').addClass('disabled');
		}
	});	
	
	// Newer tweets
	$('#future').click(function(evt){
		evt.preventDefault();
		$('#past').removeClass('disabled');
		if( !$('.active_tweets').hasClass('first') ){
			$('#future').removeClass('disabled');
			$('.active_tweets').fadeOut(400, function(){
				$(this)
					.removeClass('active_tweets')
					.prev('ul')
					.fadeIn(400, function(){
						$(this).addClass('active_tweets');
						if($(this).hasClass('first')){
							$('#future').addClass('disabled');
						}
						else {
							$('#future').removeClass('disabled');
						}
					});
			});
		}
		else {
			$('#future').addClass('disabled');
		}
	});	
	
	
/*
	// Older tweets
	$('#past').click(function(evt){
		evt.preventDefault();
			var next1 = parseInt($('.active_tweet:first').attr('rel')) + 2;
			var next2 = parseInt($('.active_tweet:last').attr('rel')) + 2;
			var total = $('#twitter_list li').length;
			console.log('next1 = ' + next1, 'next2 = ' + next2, 'total = '+ $('#twitter_list li').length);
			if(next1 <= total && next2 <= total){			
				$('#past').removeClass('disabled');
				$('#future').removeClass('disabled');				
				$('.active_tweet').fadeOut(400, function(){
					$('#twitter_list li[rel='+next1+'], #twitter_list li[rel='+next2+']')
							.fadeIn(400, function(){
								$(this).addClass('active_tweet');
								if(next1 >= total || next2 >= total ){
									$('#past').addClass('disabled');
								}
							});
						$(this).removeClass('active_tweet');
					});
			}
			else {
				$('#past').addClass('disabled');
				$('#future').removeClass('disabled');
			}
	});
	
	// Newer tweets	
	$('#future').click(function(evt){
		evt.preventDefault();
			var prev1 = parseInt($('.active_tweet:first').attr('rel')) - 2;
			var prev2 = parseInt($('.active_tweet:last').attr('rel')) - 2;
			console.log('prev1 = ' + prev1, 'prev2 = ' + prev2);
			if(prev1 >= 0 && prev2 >= 0 ){			
				$('#future').removeClass('disabled');
				$('.active_tweet').fadeOut(400, function(){
					$('#twitter_list li[rel='+prev1+'], #twitter_list li[rel='+prev2+']')
							.fadeIn(400, function(){
								$(this).addClass('active_tweet');
								if(prev1 <= 0 || prev2 <= 0){
									$('#future').addClass('disabled');
								}
							});
						$(this).removeClass('active_tweet');
					});
			}
			else {
				$('#future').addClass('disabled');
				$('#past').removeClass('disabled');				
			}
	});
	
*/
  
  /*
  $('#slider').css('height', '200px').hover(
    function(){
      $(this).stop().animate({height: '380px'}, 500) 
    },
    function(){
      $(this).stop().animate({height: '200px'}, 500) 
    }
  );
  */

});
