/* global $, _gaq, google */

/**
    Tracking
**/

$(document).ready(function() {
  trackClicks();
  initPrintButton();
  initGoogleMap();
});

function trackClicks() {
  $("a").each(function(index, a) {
    var a_jq = $(a);
    var href = a_jq.attr("href");
    if (!href || href.length == 0)
      return;

    if (isExternalLink(href)) {
      a_jq.bind("click", function() {
	var base_dir = location.pathname.substring(0, location.pathname.lastIndexOf("/")) + "/";
	var track_url = '/virtual/outboundlink' + base_dir + stripProtocolFromURL($(this).attr("href"));
	//console.debug("Is external: " + $(this).attr("href") + ". Tracking: " + track_url);
        _gaq.push(['_trackPageview', track_url]);
        _gaq.push(['rollup._trackPageview', track_url]);
      });

    } else if (isPDFLink(href)) {
      a_jq.bind("click", function() {
	var track_url = $(this).attr("href");
	//console.debug("Is PDF: " + $(this).attr("href") + ". Tracking: " + track_url);
        _gaq.push(['_trackPageview', track_url]);
        _gaq.push(['rollup._trackPageview', track_url]);
      });
    }
    
  });
}

function isExternalLink(link) {
  var link_lc = link.toLowerCase();
  if (link_lc.match("http://") || link_lc.match("https://") || link_lc.match("ftp://")) {
    return !(link_lc.match("www.nai.uu.se") || link_lc.match("noak.nai.uu.se"));
  } else
    return false;
}

function isPDFLink(link) {
  return link.toLowerCase().match(".pdf");
}

/*
function getDomainFromURL(url) {
  var protocol;
  var url_lc = url.toLowerCase();
  
  if (url_lc.match("http://"))
    protocol = "http://";
  else if(url_lc.match("https://"))
    protocol = "https://";
  else if (url_lc.match("ftp://"))
    protocol = "ftp://";

  var url_stripped_protocol = url.substr(url_lc.indexOf(protocol) + protocol.length);
  return url_stripped_protocol.substring(0, url_stripped_protocol.indexOf("/"));
}
*/

function stripProtocolFromURL(url) {
  var protocol;
  var url_lc = url.toLowerCase();
  
  if (url_lc.match("http://"))
    protocol = "http://";
  else if(url_lc.match("https://"))
    protocol = "https://";
  else if (url_lc.match("ftp://"))
    protocol = "ftp://";

  var url_stripped_protocol = url.substr(url_lc.indexOf(protocol) + protocol.length);
  return url_stripped_protocol;
}

/**
   Media Gallery
**/

function MediaGallery(_options) {
  var options = {
    container_id          : _options.container_id || "media-gallery",
    item_class            : _options.item_class || "media-gallery-item",
    thumb_container_id    : _options.thumb_container_id || "media-gallery-thumbs",
    thumb_class           : _options.thumb_class || "media-gallery-thumb",
    selected_thumb_class  : _options.selected_thumb_class || "media-gallery-thumb-selected",
    play_button_class     : _options.play_button_class || "media-gallery-thumbs-play",
    left_button_class     : _options.left_button_class || "media-gallery-thumbs-left",
    right_button_class    : _options.right_button_class || "media-gallery-thumbs-right",
    slideshow_delay       : _options.slideshow_delay || 5000,
    counter_curr_class    : _options.counter_curr_class || "media-gallery-counter-current",
    counter_tot_class     : _options.counter_tot_class || "media-gallery-counter-total"
  };
  
  var fadein_delay = 500;
  var fadeout_delay = 200;
  var items_jq;
  var thumbs_jq;
  var counter_curr_jq;
  var counter_tot_jq;
  var pos, length;
  var self = this;
  var in_transit = false;
  var playing = false;
  var timeoutID;
  
  // Private

  var showItem = function(new_pos) {
    if (in_transit)
      return;
    in_transit = true;

    $(thumbs_jq).removeClass(options.selected_thumb_class);
    $(thumbs_jq[new_pos]).addClass(options.selected_thumb_class);

    $(items_jq[pos]).fadeTo(fadeout_delay, 0.01, function() {
      $(items_jq[pos]).css('visibility', 'hidden');
      $(items_jq[new_pos]).css('visibility', 'visible');
      $(items_jq[new_pos]).fadeTo(fadein_delay, 1);
      in_transit = false;
      pos = new_pos;
      setCounterHTML();
    });    
  };

  var setCounterHTML = function() {
    counter_curr_jq.empty().append(pos + 1);
  };

  // Public

  this.init = function() {
    counter_curr_jq = $("#" + options.container_id).find("*[class~='" + options.counter_curr_class + "']");
    counter_tot_jq = $("#" + options.container_id).find("*[class~='" + options.counter_tot_class + "']");
    items_jq = $("#" + options.container_id).find("div[class~='" + options.item_class + "']");
    thumbs_jq = $("#" + options.thumb_container_id).find("div[class~='" + options.thumb_class + "']");
    pos = 0;
    length = items_jq.length;

    var overlay = $("<div class='overlay'><span/><div>");
    var container = items_jq.first().find(".media-gallery-item-image");
    var height = container.height();
    var width = container.width();
    var button_size = 140;
    container.prepend(overlay);
    overlay.height(height);
    overlay.width(width);
    var span = overlay.children("span");
    span.css( { top: Math.max(height / 2 - button_size / 2, 0),
                left: width / 2 - button_size / 2 } );
    span.bind("click", self.play);

    counter_tot_jq.empty().append(length);
    counter_curr_jq.empty().append(1);

    $("#" + options.container_id + " ." + options.play_button_class + " .play").bind("click", self.play);
    $("#" + options.container_id + " ." + options.play_button_class + " .pause").bind("click", self.pause);

    $("#" + options.container_id).find("*[class~='" + options.left_button_class + "']").bind("click", function(event) {
      self.pause();
      self.prev();
    });

    $("#" + options.container_id).find("*[class~='" + options.right_button_class + "']").bind("click", function(event) {
      self.pause();
      self.next();
    });

    $(thumbs_jq[0]).addClass(options.selected_thumb_class);

    thumbs_jq.each(function(index, node) {
      $(node).bind("click", function(event) {
        playing = false;
	self.show(index);
      });
    });

    return this;
  };

  this.show = function(new_pos) {
    if (pos == new_pos)
      return;
    showItem(new_pos);
  };

  this.next = function() {
    $("#" + options.container_id + " .media-gallery-item-image span").hide();
    showItem((pos + 1) % length);
  };

  this.prev = function() {
    $("#" + options.container_id + " .media-gallery-item-image span").hide();

    var next_pos = pos - 1;
    if (next_pos < 0)
      next_pos = length - 1;

    showItem(next_pos);
  };

  this.play = function() {
    playing = true;

    function next_repeat() {
      self.next();
      timeoutID = setTimeout(next_repeat, options.slideshow_delay);
    }

    $("#" + options.container_id + " .media-gallery-item-image span").hide();
    $("#" + options.container_id + " ." + options.play_button_class + " .play").hide();
    $("#" + options.container_id + " ." + options.play_button_class + " .pause").show();

    if (timeoutID) clearTimeout(timeoutID);
    timeoutID = setTimeout(next_repeat, options.slideshow_delay);
  };

  this.pause = function () {
    playing = false;

    if (timeoutID) clearTimeout(timeoutID);

    $("#" + options.container_id + " ." + options.play_button_class + " .pause").hide();
    $("#" + options.container_id + " ." + options.play_button_class + " .play").show();
  };
}

/**
   Print button
**/

function initPrintButton() {
  var button = $("#nai-print");
  if (button) {
    button.bind("click", function () { window.print(); });
  }
}

/**
   Contact Map
**/

function initGoogleMap() {
  if ($("#contact-map-canvas").length > 0) {
    // Touch device does not work that well with this map.
    if (!!('ontouchstart' in window)) {
      return;
    }
    var script = document.createElement("script");
    script.type = "text/javascript";
    script.src = "//maps.googleapis.com/maps/api/js?key=AIzaSyA1KFBFpLe8AIs3Jbr-munvf45BkKRaPfk&sensor=false&callback=initializeContactMap";
    document.body.appendChild(script);
  }
}

function initializeContactMap () {
  var lat = $("#contact-map-canvas").attr("data-latitude");
  var lng = $("#contact-map-canvas").attr("data-longitude");
  var title = $("#contact-map-canvas").attr("data-title");
  var naiLatlng = new google.maps.LatLng(lat, lng);
  
  var myOptions = {
    zoom: 14,
    center: naiLatlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  var map = new google.maps.Map(document.getElementById("contact-map-canvas"), myOptions);

  var marker = new google.maps.Marker({
    position: naiLatlng,
    title:title,
    map: map
  });

  $("#contact-map-image").hide();
  $("#contact-map-canvas").show();
}

