var currentItemIndex = 0;
var googleMap = null;
var twitterWidget = null;
var previousTime = 0;

$(document).ready(function() {
  setupPlayer();
});

function setupPlayer() {
  $(".VidPlaylist").empty();
  var html = "";
  for (var i = 0; i < config.playlist.length; i++) {
    var item = config.playlist[i];
    var hash = item.title.indexOf("#");
    html += "<a href='#' onclick='loadPlaylistItem(" + i + ");'><li><img style='width: 110px;' src='" + item.image + "' /><span><strong>" + item.title.substring(0,hash) + "</strong><br />" + item.title.substring(hash+1,item.title.length) + "</span></li></a>";
  }
  $(".VidPlaylist").html(html);
  jwplayer("MainVideo").setup({
    flashplayer: "http://c3339901.r1.cf0.rackcdn.com/jwplayer/player.swf",
    playlist: config.playlist,
    skin: "http://c3339901.r1.cf0.rackcdn.com/skins/skewd.zip",
    width: 660,
    height: 370,
    events: {
      onTime: timeHandler,
      onPlaylistItem: playlistHandler,
      onComplete: completeHandler
    }
  });
}

function updateGoogleMaps(geolat, geolong, zoom) {
  if ($("#GoogMapsWidget .Loading").is(":visible")) {
    $("#GoogMapsWidget .Loading").fadeOut(function() {
      setGoogleMaps(geolat, geolong, zoom);
    });
  } else {
    $("#GoogMaps").fadeOut(function() {
      setGoogleMaps(geolat, geolong, zoom);
    });
  }
  $("#GoogMaps").fadeIn();
}

function setGoogleMaps(geolat, geolong, zoom) {
  var latlng = new google.maps.LatLng(geolat, geolong);
  googleMap.setCenter(latlng);
  googleMap.setZoom(zoom);
}

function updateTwitter(search) {
  if ($("#Twitter .Loading").is(":visible")) {
    $("#Twitter .Loading").fadeOut();
  } else {
    $("#TwitterContent").fadeOut();
  }
  twitterWidget.destroy().setSearch(search).start();
  $("#TwitterContent").fadeIn();
}

function updateFlickr(search) {
  if ($("#Flickr .Loading").is(":visible")) {
    $("#Flickr .Loading").fadeOut(function() {
      $(".FlickrLogo").fadeIn();
      $(".FlickrSearch").fadeIn();
    });
  } else {
    $("#FlickrImages").fadeOut();
  }
  $.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?",
  {
    tags: search,
    tagmode: "any",
    format: "json"
  },
  function(data) {
    var html = "";
    $.each(data.items, function(i,item){
      var imageURL = item.media.m;
      html += "<li><a href='#'><img src='" + imageURL + "' height='75' width='75' border='0'></a></li>";
      if (i == 2) return false;
    });
    $("#FlickrImages").html(html);
    $("#FlickrImages").fadeIn();
  });
  $(".FlickrSearch").html(search);
}

function updateFourSquare(geolat, geolong, q) {
  if ($("#FourSq .Loading").is(":visible")) {
    $("#FourSq .Loading").fadeOut(function() {
      $("#FourSqLogo").fadeIn();
    });
  } else {
    $("#FourSqContent").fadeOut();
  }
  var url = config.fourSquareOptions.url + "?geolat=" + geolat + "&geolong=" + geolong + "&q=" + q;
  makeAPICall("GET", url, function(responseText) {
    var details = eval("(" + responseText + ")");
    $(".VenueThumb").attr("src", details["icon"]);
    $(".VenueName").html(details["name"]);
    $(".CheckIns strong").html(details["checkins"]);
    $(".MayorThumb").attr("src", details["mayor_photo"]);
    $(".Mayor").html("<strong>" + details["mayor_first"] + " " + details["mayor_last"] + "</strong> is the Mayor - " + details["mayor_checkins"] + " check-ins");
    $("#FourSqContent").fadeIn();
  });
}

function timeHandler(event) {
  var currentTime = event.position;
  var playlist = config.playlist;
  var currItem = playlist[currentItemIndex];
  var thumbs = currItem.items;
  var newTime = searchItems(currentTime, thumbs);
  var currThumb = thumbs[newTime];
  if (typeof currThumb != 'undefined' && previousTime != newTime && currThumb.name != "") {
    updateFourSquare(currThumb.geolat, currThumb.geolong, currThumb.name);
    updateGoogleMaps(currThumb.geolat, currThumb.geolong, 15);
    updateFlickr(currThumb.name);
    updateTwitter(currThumb.name);
    previousTime = newTime;
  }
}

function playlistHandler(event) {
  currentItemIndex = event.index;
  $(".TimeCodes").empty();
  var html = "";
  for (var index in config.playlist[currentItemIndex].items) {
    var item = config.playlist[currentItemIndex].items[index];
    html += "<li><a href='#' onclick='seekTo(" + index + ");'><img src='" + item.thumbnail + "'</a></li>";
  }
  $(".TimeCodes").html(html);
}

function completeHandler(event) {
  clearWidgets();
}

function clearWidgets() {
  $("#GoogMaps").fadeOut(function() {
    $("#GoogMapsWidget .Loading").fadeIn();
  });
  $("#FourSqLogo").fadeOut();
  $("#FourSqContent").fadeOut(function() {
    $("#FourSq .Loading").fadeIn();
  });
  $("#FlickrSearch").fadeOut();
  $("#FlickrImages").fadeOut();
  $(".FlickrLogo").fadeOut(function() {
    $("#Flickr .Loading").fadeIn();
  });
  $("#TwitterContent").fadeOut(function() {
    $("#Twitter .Loading").fadeIn();
  });
}

function loadPlaylistItem(index) {
  jwplayer("MainVideo").playlistItem(index);
  clearWidgets();
}

function seekTo(pos) {
  //This is a workaround for a 5.3 bug fixed in 5.4
  jwplayer("MainVideo").play(true);
  setTimeout(function() {
    jwplayer("MainVideo").seek(pos);
  }, 0);
}

function searchItems(currentTime, thumbs) {
  var prevTime = 0;
  var count = 0;
  for (var thumb in thumbs) {
    if (prevTime < currentTime && thumb > currentTime) {
      return prevTime;
    } else if (count + 1 == 6 && currentTime > thumb) {
      return thumb;
    }
    prevTime = thumb;
    count++;
  }
  return previousTime;
}

function makeAPICall(method, url, callback, params) {
  var xmlhttp = createXMLHttpRequest();
  xmlhttp.onreadystatechange=function() {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
      var responseText = xmlhttp.responseText;
      if (responseText != "") {
        callback(responseText);
      }
    }
  }
  xmlhttp.open(method, url, true);
  xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  if (method == "GET") {
    xmlhttp.send();
  } else {
    xmlhttp.send(params);
  }
  return true;
}

function createXMLHttpRequest() {
  var req = null;
  if (window.XMLHttpRequest) {
    // code for IE7+, Firefox, Chrome, Opera, Safari
    req = new XMLHttpRequest();
  } else {
    // code for IE6, IE5
    req = new ActiveXObject("Microsoft.XMLHTTP");
  }
  return req;
}
