$(document).ready(function(){
  
  // Adjust vertical lines.
  ui.vr();

  // Add event listener to blog search form.
  $("#sidebar-search").keypress(function(e) {
    if (e.keyCode == 13)
    {
      window.location = "/?s=" + $("#sidebar-search").val();
    }
  });
  
  ui.init();
  flashlightReader.init();
  videoCarousel.init();
  quoteCarousel.init();
  screenshotCarousel.init();
  campaignCarousel.init();
  buyButtonShaker.init();
  
});

var buyButtonShaker = (function() {

  return {
    
    init: function() {
      setInterval(this.shake, 7000);
    },
    
    shake: function() {
      setTimeout(function(){$(".purchase").css("left", -5);}, 0);
      setTimeout(function(){$(".purchase").css("left", 4);}, 100);
      setTimeout(function(){$(".purchase").css("left", 0);}, 200);
      setTimeout(function(){$(".purchase").css("left", -1);}, 300);
      setTimeout(function(){$(".purchase").css("left", 1);}, 400);
    }
  
  }

})();

var flashlightReader = (function() {
  
  return {

    init: function()
    {

      // Close manuscript event.
      $("#manuscript .shadow").click(this.closeReader);
      
    },
    
    openReader: function()
    {
      $("#manuscript").show().addClass("ManuScript");
      this.setContent("<div class=\"manuscript-loading\">Loading...</div>");
    },
      
    setContent: function(source)
    {
      $("#manuscript .manuscript-padding").html(source);
    },

    closeReader: function()
    {
      $("#manuscript").hide();
    },
    
    openPost: function(id)
    {
      
      flashlightReader.openReader();
      $.ajax({
        url: '?p=' + id + '&ajax=true',
        dataType: 'html',
        success: function(source)
        {
          flashlightReader.setContent(source);
        }
      });
      
    }

  }

})();

var videoCarousel = (function() {

  var videos = [];
  var current = 0;
  
  return {
  
    OPEN_VIDEOS_ON_PAGE: 0,
    OPEN_VIDEOS_IN_OVERLAY: 1,
    mode: 0,
    limit: 5,
    
    defaultWidth: 568,
    defaultHeight: 388,
  
    init: function()
    {
      _.bindAll(this, "thumbnailClick", "next", "previous");
      
      // Bind previous and next evets.
      $(".video-left").click(this.previous);
      $(".video-right").click(this.next);
      
      if (videos.length > 0)
      {
        this.render();
        this.openVideo(videos[0].url);
      }
      
    },
  
    /**
     * Open video on frontpage.
     */
    openVideo: function(url)
    {
  
      // Load template.
      var template = _.template($("#youtube-player").html());
      
      var width = this.defaultWidth;
      var height = this.defaultHeight;
      var paddings = 22;
      
      if ($(window).width() < width - paddings)
      {
        width = $(window).width() - paddings;
        height = width / (16 / 9);
      }
      
      // Render.
      var source = template({
        url : url,
        width: width,
        height: height
      });
      
      // Set container dimensions.
      $("#videoplayer").width(width + 2).height(height + 2);
  
      // Inject.
      $("#videoplayer").html(source);
      
    },
    
    openVideoInOverlay: function(url)
    {
  
      flashlightReader.openReader();
      
      // Load template.
      var template = _.template($("#youtube-player").html());
      
      // Render.
      var source = template({
        url : url,
        width: 720,
        height: 405
      });
  
      // Inject.
      flashlightReader.setContent(source);
  
    },

    add: function(title, url, thumb)
    {
      videos.push({
        title: title,
        url: url,
        thumb: thumb
      });
    },
    
    /**
     * Render all videos
     */
    render: function()
    {
      //$(".videobrowser").width(123 * videos.length);
      for (var i = 0; i < videoCarousel.limit; i++)
      {
      
        var element = "";
        
        if (typeof videos[i] != "undefined")
        {

          var template = _.template($("#video-carousel").html());
          element = $(template(videos[i]))
                            .click({id:i}, this.thumbnailClick);

        } else {

          var template = _.template($("#video-carousel-empty").html());
          element = $(template({}));

        }

        if (i == videoCarousel.limit) 
        {
          $(element).addClass("last");
        }
        $(".videobrowser").append(element);
      
      }
    },
    
    thumbnailClick: function(e)
    {
      
      if (this.mode == this.OPEN_VIDEOS_ON_PAGE)
      {
        current = e.data.id;
        this.openVideo(videos[e.data.id].url);
      } else {
        current = e.data.id;
        this.openVideoInOverlay(videos[e.data.id].url);
      }
      
    },

    next: function()
    {
      current = (current + 1) % videos.length;
      this.openVideo(videos[current].url);
    },
    
    previous: function()
    {
      current = (current - 1) < 0 ? videos.length - 1 : current - 1;
      this.openVideo(videos[current].url);
    }
    
  }

})();

/**
 * Screenshot carousel.
 */
var screenshotCarousel = (function() {

  var images = [];
  var imageSet = 0;
  var limit = 4;
  var current = 0;

  return {

    init: function()
    {
      _.bindAll(this, "thumbnailClick", "next", "previous", "nextImage", "previousImage", "render");

      // Bind click events.
      $(".game-screenshots .previous").click(this.previous);
      $(".game-screenshots .next").click(this.next);
      $(".game-screenshots .previous-image").click(this.previousImage);
      $(".game-screenshots .next-image").click(this.nextImage);
      
      // Reset limit on mobile devices.
      if (ui.isMobile)
      {
        limit = 1000;
      }
      
      this.render();
    },
    
    add: function(thumbnail, image, width, height) 
    {
      images.push({
        thumbnail: thumbnail, 
        image: image,
        width: width,
        height: height
      });
    },

    render: function()
    {
    
      // Clear screenshot area.
      $(".screenshot-thumbnails").html("");

      // Render four thumbnails.
      var k = 0;
      for (var i = imageSet * limit; i < images.length && k < limit; i++)
      {
        var template = _.template($("#screenshot-template").html());
        var element = $(template(images[i]))
                        .click({id:i}, this.thumbnailClick)
                        .css("opacity", 0)
                        .delay(Math.random() * 500)
                        .animate({opacity:1}, 200);
        $(".screenshot-thumbnails").append(element);
        k++;
      }
    
    },
    
    thumbnailClick: function(e)
    {
      current = e.data.id;

      // Show loading screen.
      if ($("#screenshot-display").is(":visible"))
      {

        this.showLoaderAndLoadImage(images[current].image, images[current].width, images[current].height);
        
        /*
        var self = this;
        $("#screenshot-display").fadeOut(function() {
          $("#screenshot-loader").fadeIn(function() {
            self.showImage(images[current].image, images[current].width, images[current].height);
          });
        });
        */
          
      } else {

        $("#screenshot-loader").fadeIn(function() {
          self.showImage(images[current].image, images[current].width, images[current].height);
        });

      }
      
    },
    
    showLoaderAndLoadImage: function(image, width, height)
    {

      var self = this;
      $("#screenshot-display").fadeOut(function() {
        $(".previous-image, .next-image").hide();
        $("#screenshot-loader").fadeIn(function() {
          self.showImage(image, width, height);
        });
      });
    },
    
    showImage: function(url, width, height)
    {
      
      // Create image.
      var image = new Image();
      if(ui.isMobile == false){
    	  $(image).width(width).height(height);
      }
      image.onload = function() {
        $("#screenshot-loader").fadeOut(function(){
          if(ui.isMobile == false){
        	  $(".previous-image, .next-image").show();
          }
          $("#screenshot-display").html("").append(image).fadeIn(function(){
            // Fix height.
            $(".game-screenshots").height("inherit");
            $(".game-screenshots").height($(".game-screenshots").height());
          });
        });
      };
      image.src = url;
      
    },

    next: function()
    {
      if ((imageSet + 1) * limit > images.length)
      {
        return;      
      }
      imageSet++;
      this.cleanAndRender();
    },
    
    previous: function()
    {
      if ((imageSet - 1) < 0)
      {
        return;      
      }
      imageSet--;
      this.cleanAndRender();
    },
    
    nextImage: function()
    {
      current++;
      if (current >= images.length)
      {
        current = images.length - 1;
      }
      console.log(current);
      this.showLoaderAndLoadImage(images[current].image, images[current].width, images[current].height);
    },
    
    previousImage: function()
    {
      current--;
      if (current < 0)
      {
        current = 0;
      }
      console.log(current);
      this.showLoaderAndLoadImage(images[current].image, images[current].width, images[current].height);
    },
    
    cleanAndRender: function()
    {
    
      // Hide all thumbnails.
      $(".screenshot-thumbnails .screenshot").each(function(i, value)
      {
        $(value)
          .delay(Math.random() * 500)
          .animate({opacity:0}, 200);
      });
      
      setTimeout(this.render, 700);
    
    }

  }

})();

var campaignCarousel = (function() {

  var itemsLength = 0;
  var currentItem = 0;
  
  var delay = 8000;
  var autoRotate = true;

  return {
    
    init: function()
    {
      _.bindAll(this, "openItem", "nextItem");
      itemsLength = $(".spotlight-items > *").length;
      this.openItem(0, true);
      setTimeout(this.nextItem, delay);
    },
    
    openItem: function(id, automatic)
    {
    
      if (ui.isMobile)
      {
        return;
      }
    
      $(".spotlight-items").animate({ left: id * -860 }, 500);
      $(".spotlight-bullets li").removeClass("selected");
      $(".spotlight-bullets li:nth-child(" + (id + 1) + ")").addClass("selected");

      if (typeof automatic == "undefined")
      {
        autoRotate = false;
      }
    
    },
    
    nextItem: function()
    {

      if (ui.isMobile)
      {
        return;
      }

      if (autoRotate)
      {
        currentItem = (currentItem + 1) % itemsLength;
        this.openItem(currentItem, true);
        setTimeout(this.nextItem, delay);
      }

    }
  
  }

})();

/**
 * Display quotes on page header.
 */
var quoteCarousel = (function() {

  var quotes = [];
  var current = 0;
  var quoteSlots = [ 2, 0, 1 ]; // change order
  
  return {
  
    init: function()
    {

      _.bindAll(this, "next", "shakeFrame");
      
      if (quotes.length == 0)
      {
        return false;
      }
      
      if ($(".quote-area").length == 0)
      {
        return false;
      }
      
      // Add first items.
      for (var i = 0; i < quoteSlots.length; i++)
      {

        // Create slot.
        var slot = $("<div>").addClass("quote-slot").addClass("quote-slot-" + i);

        // Get next quote.
        var quote = this.getNextQuote();

        // Replace quote.
        var template = _.template($("#quote-template").html());
        var element = $(template(quote));
        $(slot).append(element);
        $(".quote-area").append(slot);

        // Hide splashes
        $(slot).find(".splash").hide();
        
        // Fix slot height.
        //$(slot).height($(slot).height());
        
      }
      
      this.next();

    },
  
    add: function(quote, source)
    {
      quotes.push({quote:quote, source:source});
    },
    
    /** 
     * Change next item.
     */
    next: function()
    {
    
      if (ui.isMobile)
      {
        return false;
      }

      var slot = quoteSlots[current % quoteSlots.length];

      // Fade out current quote.
      var self = this;
      this.shakeHide($(".quote-area .quote-slot-" + slot + " .quotes")[0], function() {
        self.showNextQuote(slot)
      });

    },

    showNextQuote: function(slot)
    {

      var quote = this.getNextQuote();

      // Replace quote.
      var template = _.template($("#quote-template").html());
      var element = $(template(quote)).hide();
      $(".quote-slot-" + slot).append(element);
      
      var height = $(element).height() + 60;

      var splash = $(".quote-slot-" + slot).find(".splash");
      var text = $(".quote-slot-" + slot).find(".quotes");

      //$(splash).height(100).show();

      //$(splash).fadeOut();
      $(text).show();

      setTimeout(this.next, 4000);
      
      // Animate to new height.
      /*
      var self = this;
      $(".quote-slot-" + slot).animate(
        { height: height },
        function()
        {
          // Fix splash height.
          $(splash).fadeIn(100, "swing", function(e) {
            splash.fadeOut(500);
            element.fadeIn();
          });

          setTimeout(self.next, 2000);
        }
      );
      */

    },
    
    shakeHide: function(element, callback)
    {
      
      
      // Clone quote.
      var anchor = $("<div>").addClass("quote-anchor");
      var clone = $(anchor).append($(element).clone());
      $(clone).insertBefore(element);

      // Shake.
      this.shakeFrame(clone, element, 15, 0, 50, callback);
      
    },
    
    shakeFrame: function(element1, element2, limit, frame, delay, callback)
    {

      frame++;

      var rotation = 0;
      var x = 0;
      var y = 0;

      rotation = -3 + 6 * Math.random();
      x = -3 + 6 * Math.random();
      y = -3 + 6 * Math.random();
      
      $(element1).css("-moz-transform", "rotate(" + rotation + "deg) translate(" + x + ", " + y + ")");
      $(element1).css("-webkit-transform", "rotate(" + rotation + "deg) translate(" + x + ", " + y + ")");
      $(element1).css("-o-transform", "rotate(" + rotation + "deg) translate(" + x + ", " + y + ")");
      $(element1).css("-ms-transform", "rotate(" + rotation + "deg) translate(" + x + ", " + y + ")");
      $(element1).css("transform", "rotate(" + rotation + "deg) translate(" + x + ", " + y + ")");

      rotation = Math.round(-3 + 6 * Math.random());
      x = Math.round(-3 + 6 * Math.random());
      y = Math.round(-3 + 6 * Math.random());
      $(element2).css("-moz-transform", "rotate(" + rotation + "deg) translate(" + x + "px, " + y + "px)");
      $(element2).css("-webkit-transform", "rotate(" + rotation + "deg) translate(" + x + "px, " + y + "px)");
      $(element2).css("-o-transform", "rotate(" + rotation + "deg) translate(" + x + "px, " + y + "px)");
      $(element2).css("-ms-transform", "rotate(" + rotation + "deg) translate(" + x + "px, " + y + "px)");
      $(element2).css("transform", "rotate(" + rotation + "deg) translate(" + x + "px, " + y + "px)");

      if (frame == limit)
      {

        $(element1).parent().html("")
        
        callback();

      } else {
        var self = this;
        setTimeout(function()
        {
          self.shakeFrame(element1, element2, limit, frame, delay, callback);
        }, delay);
      }
      
    },
    
    getNextQuote: function()
    {
      current++;
      return quotes[current % quotes.length];
    }
  
  };

})();

var ui = (function() {

  var template = function(){};

  return {

    isMobile: false,

    init: function()
    {

      // Get selected menu item.
      var selected = $("#mainmenu a.selected");
      
      if ($(window).width() < 700)
      {
        ui.isMobile = true;
      }

      // Set viewport settings for various devices.
      if ($(window).width() > 700)
      {
        $('meta[name=viewport]').attr("content", "width=960");
      } else if ($(window).width() > 400) {
        $('meta[name=viewport]').attr("content", "width=480");
      } else {
        $('meta[name=viewport]').attr("content", "width=360");
      }


      // Move ink splat.
      if (selected.length > 0 && !ui.isMobile)
      {
        var parent = $(selected).parent();
        $("#selectedInk").css("left", parent.position().left + parent.width() / 2 - 40).show();
      }


    },


    /*
    menuMouseEnter: function(e)
    {
      
      if (!hoverEnabled)
      {
        return false;
      }

      var li = e.currentTarget;
      var link = $(e.currentTarget).find("a");
      
      var hover = $(template({
        title: $(link).html(),
        href: $(link).attr("href")
      })).css("width", $(li).width());
      
      hover.find("a").css("width", $(li).width());
 
      
      $(hover).insertBefore(link)

    },

    menuMouseLeave: function(e)
    {
      $(".menu-hover").detach();
    },
    */

    /** 
     * Align vertical lines.
     */
    vr: function() 
    {
    
      $(".vr").each(function(i, item)
      {
      
        // Get next and previous sibling heights.
        var previousSiblingHeight = $(item).prev().height();
        var nextSiblingHeight = $(item).next().height();
        
        // Use higher to set height.
        $(item).height(Math.max(previousSiblingHeight, nextSiblingHeight));
      
      });
    
    },
    
  }

})();


function hideManuScriptShadow(){
	document.getElementById('manuscript').style.display = "none";
}

function hideManuScript(){
	var manuscript = document.getElementById('manuscript');
	setTimeout("hideManuScriptShadow()" , 500 );
	document.getElementById('manuscript').className = "hiddenManuScript";
}

function showManuScript(){
	document.getElementById('manuscript').style.display = "block";
	document.getElementById('manuscript').className = "ManuScript";
}

function shuffle(o)
{ //v1.0
	for(var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
	return o;
};

/*
window.onscroll = scroll;
var lowestScroll;
function scroll(){
  var bodyHeight = document.getElementById('body').clientHeight;
  var upperAreaHeight = 350;
  var lowerAreaHeight = 100;
  var theValue = bodyHeight-upperAreaHeight-lowerAreaHeight-(window.innerHeight-window.pageYOffset);
  var theOtherValue = bodyHeight-upperAreaHeight-lowerAreaHeight-window.innerHeight;
  if (theValue > 0) {
    $("html").css("background-position", "50% -" + (theOtherValue+window.pageYOffset) + "px");
    //document.getElementById('html').style.backgroundPosition = "50% -" + (theOtherValue+window.pageYOffset) + "px";
    document.getElementById('header').style.top = "-" + (theOtherValue+window.pageYOffset) + "px";
    document.getElementById('topBg').style.top = "-" + (theOtherValue+window.pageYOffset) + "px";
  } else {
    $("html").css("background-position", "50% 0px");
    //document.getElementById('html').style.backgroundPosition = "50% 0px";
    document.getElementById('header').style.top = "0px";
    document.getElementById('topBg').style.top = "0px";
  }
  //document.getElementById('lol').innerHTML = "50% -"+(window.innerHeight-window.pageYOffset)+"px"+bodyHeight+" / "+window.pageYOffset+" ; "+theValue;
  // korkeus-yläkuvanarvo-alakuvanarvo-scroll
  // + " - " + window.innerHeight
}
*/
