Array.prototype.sum = function(){
  for(var i=0,sum=0;i<this.length;sum+=this[i++]);
  return sum;
}
Array.prototype.max = function(){
  return Math.max.apply({},this)
}
Array.prototype.min = function(){
  return Math.min.apply({},this)
}

$(document).ready(function() {
  Cufon.replace('#nav div#projects a, #nav div#makers a', {hover: true});

  // li:hover support on IE6
  $(".ie6 #follow-us").hover(function() {
    $(this).children("ul").toggleClass("ie6-hover");
  });

  $("a#subscribe").fancybox({
    'autoDimensions' :  false,
    'width' : 325,
    'height' : 150
  });

  // NEWSLETTER

  $("#newsletter-subscribe").submit(function() {
    $.fancybox.showActivity();
    $.ajax({
      type  : "POST",
      url: "http://laquadra.tv/?page_id=92",
      cache: false,
      data  : $(this).serializeArray(),
      success: function(data) {
        $.fancybox(data);
      }
    });

    return false;
  });

  $("#terms-show").click(function() {
    $("div#terms").toggle();
    return false;
  });

  $("#contact a").click(function() {
    $(this).next('div#info').slideToggle();

    return false;
  });

  // PORTFOLIO

  resizeProjectsDiv = function (extraHeight) {
    var heights = [];
    $("div#projects > ul").each(function(index) {
        var sizes = [],
            items = $(this).children("li");
        items.each(function(index) {
         sizes[index] = $(this).outerHeight();
        });
        heights[index] = sizes.sum();
    });
    height = heights.max();
    $("div#projects").css("height", height + extraHeight + "px");
  }

  $("#nav li.with-subsection a.subsection-link").click(function() {
    // if ($("body").is(":not('.single-project')")) {
      $(this).next('div.section-tree').toggle();
      $(this).toggleClass('current_page_item');
      resizeProjectsDiv(3); // Resize project div to the total amount of li's
    // }
     console.log($(this));
    return false;
  });

  if ($("body").is(".single-project")) {
    resizeProjectsDiv(10);
  }

  var currentSlide = $("#projects ul li.current-project").parent().index(),
      slide = (currentSlide < 0) ? 0 : currentSlide;
  $("div#projects").cycle({
    fx: "scrollLeft",
    next: "#next-page",
    speed: 800,
    startingSlide: slide,
    delay: -2000
  }).cycle('pause');

  // MANAGING VIDEO GALLERY
  $("#post-videos br, #post-videos p").remove();
  var videos = $("#post-videos iframe");
  $(videos).hide().filter(':first').show();

  $("#post-videos iframe").each(function(index) {
    var id = $(this).attr("id"),
        i = index + 1,
        link = "<li>| <a href=#"+ id + ">Video " + i +"</a></li>";
    $("#post-files ul").append(link);
  });

  $("#post-files ul#links a").click(function() {
    $(videos).fadeOut().hide().filter(this.hash).fadeIn('fast');

    $("#post-files ul#links a").removeClass("selected");
    $(this).addClass("selected");
    return false;
  }).filter(':first').click();
});
