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

    $('#content > div, #video').center( {vertical : false, horizontal: true });
    win_height = $(window).height();
    v_margin = (win_height > 600)? Math.floor(($(window).height()-600)/2) : 0;
    $('html').css({'margin-top': v_margin, 'margin-bottom': v_margin });

    current_url = document.location.hash;
    
    /*
    disable history logging for ie, as it currently doesn't work anyway.
    FIXME: implement iframe solution
    */
    if (!$.browser.msie)
      checkHistory();
    
    if (current_url != "") {
      url_resolve(current_url);
    }
  }
  
  function drawStripes (gradient) {
    s = "";
    
    for (var i = 1; i < 169; i++){
      if (gradient) {
        o = String(Math.floor((i+13)/14)/12);
        o = o.substr(0,3);
      } else {
        o = "1";
      };
      
      s += '<div class="stripes s' + String(i) +
           ' mini_item" style="opacity: '+o+';"></div>';
    };
    $('#stripes').html(s);
  }
  
  $("[class*=menu-page]").click(function() {
    if ($.browser.msie)
    {
      document.location.href = getHash($(this).attr('href'));
    } else {
      window.location = getHash($(this).attr('href'));
    }
    doFade = false;
    writeHistory();
    $("#menu > li a").removeClass('active');
    $(this).addClass('active');
    $('#quicktime').css({'visibility': 'hidden'});
    $('#wall').fadeOut();
    $('#video').hide('', function (){
      try {
        clearTimeout(ft);
      } catch (e) {}
      doFade = false;
      $('#video').empty();
    });
    $('#maincontent').fadeOut();
    $('#textcontent').fadeOut();
  });
  
  $("[class*=menu-page-article]").click(function() {
    $('#background').fadeIn();
    $('#auth').fadeOut();
    $('#project_media').fadeOut();
    $('#submenudiv').fadeOut();
    var href = $(this).attr('href');
    if ($('#textcontent').is(':animated')) {
      $('#textcontent').animate({'padding': 0}, 200, function() {
        loadPage(href);
      });
    } else {
      loadPage(href);
    };
    return false;
  });
  
  $("[class*=menu-page-projects]").click(function() {
    $('#get_tags').trigger('click');
    $('#project_media').fadeOut();
    $('#submenudiv').fadeIn();
    loadAllProjects();
    $('#auth').fadeOut();
    return false;
  });
  
  $("[class*=menu-page-auth]").click(function() {
    $('#background').fadeOut();
    window.location = '#/client_login/';
    writeHistory();
    $('#project_media').fadeOut();
    $('#maincontent').load('/client_media/');
    $('#submenudiv').fadeOut();
    $('#maincontent').fadeIn();
    $('#auth').fadeIn();
    return false;
  });

  $("[class*=menu-page-showreel]").click(function() {
    $('#wall').hide();
    $('#project_media').empty();
    $('#project_media').fadeIn();
    loadProject($(this).attr('href'));
    return false;
  });
  
  $('#get_tags').click(function() {
    $('#get_clients').removeClass('active');
    loadAllProjects();
    $('.tag-button').removeClass('active');
    $('#client_list').fadeOut(function (e) {
      $('#get_tags').addClass('active');
      $('#tag_list').fadeIn();
    });
    return false;
  });


  $('#get_clients').click(function() {
    $('#get_tags').removeClass('active');
    loadAllProjects();
    $('.client-button').removeClass('active');
    $('#tag_list').fadeOut(function(e) {
      $('#get_clients').addClass('active');
      $('#client_list').fadeIn();
    });
    return false;
  });

  $('.tag-button').click(function() {
    window.location = getHash("#"+$(this).children("a").attr('href'));
    writeHistory();
    $('.tag-button').removeClass('active');
    get_objects( $(this) );
    return false;
  });

  $('.tag-button').mouseover(function() {
    highlightObj( $(this), true );
  });

  $('.tag-button').mouseout(function() {
    highlightObj( $(this), false );
  });
  
  $('.client-button').mouseover(function() {
    highlightObj( $(this), true );
  });
  $('.client-button').mouseout(function() {
    highlightObj( $(this), false );
  });
  
  $('.client-button').click(function() {
    window.location = getHash($(this).children("a").attr('href'));
    writeHistory();
    $('.client-button').removeClass('active');
    get_objects( $(this) );
    return false;
  });
  
  $().mousemove(function(e)
  {
    if (doFade)
    {
      if (e.pageX != mousePos) {
        if (!fullscreen)
          if (! ($.browser.msie && $.browser.version < 7))
          {
            $('#content,#quicktime_controller,#project_description').fadeIn();
          } else {
            $('#content,#quicktime_controller,#project_description').show();
          }
        else
          $('#quicktime_controller').fadeIn();
        try {
          clearTimeout(ft);
        } catch (e) {}
        fadeOutBackground(true);
        mousePos = e.pageX;
      }
    } else {
      $('#content').show();
    }
  });
  
  init();

});

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 url_resolve (url) {
  doFade = false;
  $('#content').show();
  try {
    clearTimeout(ft);
  } catch(e) {}
  writeHistory();
  current_url = getHash(url).substr(1);
  parts = current_url.split('/');
  switch (parts[1])
  {
    case "tag":
      $('#project_media,#textcontent').fadeOut();
      $('#submenudiv').fadeIn();
      $('#video').hide();
      $('#tag_list').show();
      $('#client_list').hide();
      $('[class*=menu-page-projects]').addClass('active');
      $('#get_tags').addClass('active');
      $('#tag_list .'+parts[2]).trigger('click');
      if (!all_projects_loaded())
      {
        loadAllProjects("/"+parts[1]+"/"+parts[2]+"/");
      } else {
        $('#wall').fadeIn();
      }
      break;
    case "client":
      $('#project_media,#textcontent').fadeOut();
      $('#video').hide();
      $('[class*=menu-page-projects]').addClass('active');
      $('#submenudiv').fadeIn();
      $('#tag_list').hide();
      $('#client_list').show();
      $('#get_clients').addClass('active');
      $('#get_tags').removeClass('active');
      $('#client_list .'+parts[2]).trigger('click');
      if (!all_projects_loaded())
      {
        loadAllProjects("/"+parts[1]+"/"+parts[2]+"/");
      } else {
        $('#wall').fadeIn();
      }
      break;
    case "projects":
      $('[class*=menu-page-projects]').trigger('click');
      break;
    case "project":
      $('#textcontent,#maincontent').fadeOut();
      url = "/"+parts[1]+"/"+parts[2]+"/";
      if (parts[3])
        url += parts[3]+"/";
      loadProject(url);
      break;
    case "show_media":
      url = "/"+parts[1]+"/"+parts[2]+"/";
      $('#textcontent,#maincontent,#project_media').fadeOut();
      $('#auth').fadeIn();
      loadProject(url);
      break;
    case "page":
      $('[class*=menu-page-article-'+parts[2]+']').trigger('click');
      break;
    case "client_login":
      $('[class*=menu-page-auth]').trigger('click');
      break;
  }
}

function loadPage(url)
{
  $('#textcontent').load(url, 
    function(responseText, textStatus, XMLHttpRequest) {
      $('#textcontent').fadeIn();
    });
}

function loadProject(url)
{
  window.location = getHash(url);
  writeHistory();
  $('#wall').fadeOut();
  $('#background').fadeOut();
  $('#video').load(url, 
    function(responseText, textStatus, XMLHttpRequest) {
      $('#video').fadeIn('', function () {
      });
      $('#submenudiv').fadeOut();
    });
}

function all_projects_loaded()
{
  ret = ($.trim($('#wall').html()) != "" && 
          $('#all_projects_loaded').html() == "true");
  return ret;
}

function fadeOutBackground(wait)
{
  if (wait)
  {
    ft = setTimeout("fadeOutBackground()", 3000);
  } else {
    if (doFade) {
      if (! ($.browser.msie && $.browser.version < 7))
      {
        $('#content,#quicktime_controller,#project_description').fadeOut();
      } else {
        $('#content,#quicktime_controller,#project_description').hide();
      }
      
    }
  }
}

function loadAllProjects(url)
{
  $('#background').fadeOut();
  if (url == undefined)
  {
    url = "/projects/";
  }
  if (all_projects_loaded())
  {
    $('#wall').fadeIn();
    $('.wallitem').show();
    $('.wallitem').fadeTo('fast',0.6);
  } else {
    $('#wall').html('');
    $('#wall').load(url, 
      function(responseText, textStatus, XMLHttpRequest) {
        $('#wall').fadeIn('fast', function() {
          $('.wallitem').fadeTo('fast',0.6);
          $('#submenudiv').fadeIn();
        });
      });
  }
}
function highlightObj (obj, highlight) {
  var item = $(obj).attr('class').split(' ')[1];
  $('.'+item).each(function() {
    if ($(this).attr('class').indexOf('wallitem') != -1)
    {
      if (highlight)
      {
        $(this).addClass("hiddenstripes");
        $(this).fadeTo('fast', 1);
      } else {
        $(this).removeClass("hiddenstripes");
        $(this).fadeTo('fast', 0.6);
      }
    }
  });
}

function get_objects (obj) {
  $(obj).addClass('active');
  //highlightObj( $(obj), true );
  var item = $(obj).attr('class').split(' ')[1];
  $('.wallitem').fadeOut('fast').animate({'padding': 0}, 500 , function() {
    $('#wall > .'+item).fadeIn();
  });
}

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,'');
      url_resolve(url);
      $('#history').empty();
      writeHistory();
    }
  }
}
mousePos = 1;
doFade = false;
