var padding = 12, rowHeight = 70;
$(function(e) {
  /* calculate size of items on resize */
  $(".row").each(function(rowIndex, rowElm) {
    var countSingles = $(rowElm).find(".item").length+$(rowElm).find(".item.double").length-$(rowElm).find(".item.square").length;
    var squares = 0;
    $(rowElm).find(".item.square").each(function(i, elm) {
      squares += $(elm).width()+padding*2;
    });
    $(window).resize(function(e) {
      var left = 0;
      var width = $(window).width() - squares;
      var singleWidth = (width-(countSingles-1)*padding)/countSingles - 2*padding;
      $(rowElm).find(".item").each(function(index, item) {
        $(item).css({left: left+"px", bottom:rowIndex*(rowHeight+2*padding)+"px"});
        if (!$(item).hasClass("square")) {
          $(item).width($(this).hasClass("double") ? (singleWidth*2+padding) : singleWidth);
        }
        left += $(item).width() + 3*padding;
      });
    }).resize();
  });

  /* show / hide submenu */
  var showSubMenu = function(e) {
    elm = $(e.srcElement);
    elm.switchClass("more", "less");
    elm.unbind('click', showSubMenu);
    elm.bind('click', hideSubMenu);
    $("#sub-menu").show("slow");
  }
  var hideSubMenu = function(e) {
    elm = $(e.srcElement);
    elm.switchClass("less", "more");
    elm.unbind('click', hideSubMenu);
    elm.bind('click', showSubMenu);
    $("#sub-menu").hide("slow");
  }
  $("#expander").click(showSubMenu);


  /* expand effect */
  var expand = function(e) {
    $(this).animate({height:68}).css({cursor:"pointer"});
  }
  var contract = function(e) {
    $(this).animate({height:60}).css({cursor:"default"});
    $(this).find(".content").html("");
  }
  $(".item:not(.non-expand)").mouseenter(expand).mouseout(contract);

  /* show content */
  var contentModeOn = function() {
    $("#mask").fadeIn("fast");
    $("#loader").show();
    $("#grid").fadeOut("slow", function() {
      $("#content").fadeIn("slow");
    });
  }
  var contentModeOff = function() {
    $("#loader").hide();
    $("#content").fadeOut("fast", function() {
      $("#content-content").css({display:"none"});
      $("#content-content").html("");
      $("#mask").fadeOut("fast", function() {
        $("#grid").fadeIn("fast");
      });
    });
  }

  /* load content */
  $([
    {id:"#video", url:'http://andyoureoff.dk/wordpress/?page_id=152&request_type=json'},
    {id:"#about", url:'http://andyoureoff.dk/wordpress/?page_id=148&request_type=json'},
    {id:"#contact", url:'http://andyoureoff.dk/wordpress/?page_id=146&request_type=json'},
    {id:"#live", url:'http://andyoureoff.dk/wordpress/?page_id=175&request_type=json'},
    {id:"#events", url:'http://andyoureoff.dk/wordpress/?page_id=178&request_type=json'},
    {id:"#lyrics", url:'http://andyoureoff.dk/wordpress/?page_id=180&request_type=json'},
    {id:"#photo", url:'http://andyoureoff.dk/wordpress/?page_id=150&request_type=json', postload:function(){
      /* do cool shit with gallery */
      var img = [];
      $(".content a:has(img)").each(function(i,e) {
        img.push(
          {
            src: e.href,
            thumbsrc: $(e).find("img:first").attr("src")
          }
        );
      });
      $(".content").html("");
      var thumbheight = 75, thumbwidth=100;
      var viewport    = $("<div id='viewport'></div>").appendTo(".content");
      var previewport = $("<div id='preview-port'></div>").appendTo(".content");
      var preview     = $("<div id='preview'></div>").appendTo(previewport);
      /* Scroll Right */
      $("<div id='scroll-right'></div>").appendTo(".content").click(function(e) {
        var margin = parseInt(preview.css("margin-left").replace("px"));
        var newM   = preview.width()+margin-(thumbwidth+padding)*6 < previewport.width() ? previewport.width()-preview.width()+padding : margin-(thumbwidth+padding)*6;
        preview.animate({"margin-left":newM+"px"});
      });
      /* Scroll Left*/
      $("<div id='scroll-left'></div>").appendTo(".content").click(function(e) {
        var m = parseInt(preview.css("margin-left").replace("px"));
        var newM = (m*-1)-(thumbwidth+padding)*6 < 0 ? 0 : m+(thumbwidth+padding)*6;
        preview.animate({"margin-left":newM+"px"});
      });

      preview.width(0);
      $(img).each(function(i, e) {
        preview.width(preview.width()+thumbwidth+padding);
        var thumbnail = $("<img />").attr("src", e.thumbsrc).appendTo(preview).click(function(ev) {
          viewport.html($("<a></a>").attr({href: e.src, target: "_blank"}).append($("<img />").attr("src", e.src)));
        });
      });
      preview.find("img:first").click();
    }},
    {id:"#blog", url:'http://andyoureoff.dk/wordpress/?request_type=json', postload:function() {
      var match = document.location.href.match(/#([0-9]+)$/);
      if (match) {
        var offset = $("#post-"+match[1]).position();
        $(window).scrollTop(offset.top);
        console.log(offset);
      }
    }},
    {id:"#twitter", url:function(dataHandler) {
      $.getJSON("remote.php?ressource=twitter", function(o) {
        if (o.length > 0) {
          var content = $("<div class=\"content\"></div>");
          $(o).each(function(index,obj) {
            content.append("<p>"+obj.created_at+" <span class=\"slash active\">//</span> "+obj.text+"</p>");
          });
          var post = $("<div class=\"post\"></div>")
            .append("<div class=\"title\"><h3><span class=\"slash active\">//</span> Twitter</h3></div>")
            .append(content)
          ;
          dataHandler(post);
        }
      });
    }}
  ]).each(function(index, elm) {
    $(elm.id).click(function(e) {
      $("#content-content").html("");

      var presentData = function(data) {
        try {
          $("#loader").hide();
          $("#content-content").html(data);
          $("#content-content").fadeIn("slow");
        } catch (e) {}
        if (typeof(elm.postload) != "undefined") {
          setTimeout(elm.postload, 1);
        }
      }
      if (typeof(elm.url) == "function") {
        elm.url(presentData);
      } else if (typeof(elm.url) != "undefined") {
        $.get(elm.url, presentData);
      }
      contentModeOn();
    });
  });

  $("#close").click(contentModeOff);
  $("#mask").click(contentModeOff);

  /* Load twitter */
  $.getJSON("remote.php?ressource=twitter", function(o) {
    if (o.length > 0) {
      var firstObj = o.shift();
      $("#twitter-content").html(firstObj.created_at+": "+firstObj.text);
    }
  });

  /* open blog if deep-link */
  var match = document.location.href.match(/#([0-9]+)$/);
  if (match) {
    $("#blog").click();
  }
});

/* soundcloud player */
$(document).bind('onPlayerInit.scPlayer', function(event) {
  var current = 0,
      tracks  = $(".sc-trackslist li a"),
      playCurrent = function() {
        tracks.filter(":eq("+current+")").click();
        $(".sc-pause").html("||");
      }
  ;
  $(document).bind('onPlayerTrackSwitch.scPlayer', function(event, track){
    $("#track-title").html(track.title);
  });

  $(".sc-play").remove();
  $(".sc-pause").html("&gt;").click(function(e) {
    e.preventDefault();
    $("#track-title").html(tracks.filter(":eq("+current+")").html());
    $(this).html($(this).html()=="||" ? "&gt;" : "||");
  });
  $("<a href=\"#previous\"/>").html("&lt;&lt;").prependTo(".sc-controls").click(function(e) {
    e.preventDefault();
    current = current-1 < 0 ? tracks.length-1 : current-1;
    playCurrent();
  });
  $("<a href=\"#next\"/>").html("&gt;&gt;").appendTo(".sc-controls").click(function(e) {
    e.preventDefault();
    current = (current+1) >= tracks.length ? 0 : current+1;
    playCurrent();
  });
});
