$(GLOBAL).bind("showPositionFirstTimeDone", function () {
  consoleLog("showPositionFirstTimeDone event captured");
  var timezone = jstz.determine();
  setTimezone(timezone.name());
});

var placesArray = [];
var placesObjArray = [];
var pozcardNickname = "";
var defaultLatLng;
var map;
var mc;
var markers = [];
var markersObjArray = [];
var radius = "5000000";
var line;
var playPosition = 0;
var linesArray = [];
var zoom = 1;
var initialZoom = true;
var currentPosition;
var animatePozcard = true;
var lineSymbol;

if (typeof (google) != "undefined") {
  defaultLatLng = new google.maps.LatLng(52.13, 5.18);
  lineSymbol = {
    path: google.maps.SymbolPath.FORWARD_OPEN_ARROW,
    scale: 3,
    strokeColor: '#000'
  };
}


// Sets the map on all markers in the array.
function setAllMap(map) {
  for (var i = 0; i < markers.length; i++) {
    markers[i].setMap(map);
  }
}

// Removes the markers from the map, but keeps them in the array.
function clearMarkers() {
  setAllMap(null);
}

// Shows any markers currently in the array.
function showMarkers() {
  setAllMap(map);
}

// Deletes all markers in the array by removing references to them.
function deleteMarkers() {
  clearMarkers();
  markers = [];
  markersObjArray = [];
  if(mc != null) {
    mc.clearMarkers();
  }
}

// Deletes all places in the array by removing references to them.
function deletePlaces() {
  placesArray = [];
  placesObjArray = [];
}

function centerGMap(defaultLatLng) {
  map.setCenter(defaultLatLng);
}

function zoomMap() {
  var zoomLevel = map.getZoom();
  map.setZoom((zoomLevel * 2));
}

function play() {
  playPosition = 0;
  clearMarkers();
  removeLines();
  if (map.getZoom() > 1) {
    zoom = 1;
    map.setZoom(zoom);
  }
  initialZoom = true;
  playPozcard();
}

function playPozcard() {
  //infowindow.close();
  bounds = new google.maps.LatLngBounds();

  if (playPosition == 0) {
    clearMarkers();
  }

  if (playPosition < markers.length) {
    markers[playPosition].setMap(map);

    var prevPlaceLoc = markers[playPosition].position;
    currentPosition = markers[playPosition].position;
    if (playPosition > 0) {
      prevPlaceLoc = markers[playPosition - 1].position;
    }
    var coordinates = new Array();
    coordinates.push(prevPlaceLoc);
    coordinates.push(currentPosition);
    bounds.extend(prevPlaceLoc);
    bounds.extend(currentPosition);

    // Set the zoom
    if (zoom == 1) {
      zoom = 21;
      map.setCenter(currentPosition);
      map.setZoom(2);
    } else {
      map.fitBounds(bounds);
      drawLine(coordinates);
    }
  } else {
    for (var key in markers) {
      //infowindow.close();
      bounds.extend(markers[key].position);
      map.fitBounds(bounds);
    }
  }
}

function showMarkerPersonalMessage() {
  if (playPosition < markers.length) {
    //infowindow.open(map, markers[playPosition]);
    var html = '<div>';
    var website = placesObjArray[placesArray[playPosition].getPlaceResult()["id"] + "" + placesArray[playPosition].getCheckinDate()].getWebsite();

    var vcard = createVcard($("<div/>").text(placesObjArray[placesArray[playPosition].getPlaceResult()["id"] + "" + placesArray[playPosition].getCheckinDate()].getPlaceResult()["name"]).html(),
      $("<div/>").text(placesObjArray[placesArray[playPosition].getPlaceResult()["id"] + "" + placesArray[playPosition].getCheckinDate()].getPlaceResult()["vicinity"]).html(),
      website
      );

    var description = $("<div/>").text(placesObjArray[placesArray[playPosition].getPlaceResult()["id"] + "" + placesArray[playPosition].getCheckinDate()].getPozcardDescription()).html().replace(/\n/g, '<br />');
    var date = $("<div/>").text(placesObjArray[placesArray[playPosition].getPlaceResult()["id"] + "" + placesArray[playPosition].getCheckinDate()].getPlaceResult()["checkin_date"]).html();
    var blockquote = createQuote(description, date, pozcardNickname);

    html += vcard + blockquote;

    if ((playPosition + 1) < markers.length) {
      html += '<a href="javascript: void(0);" class="tiny button secondary left" onClick="$(\'#checkinDescriptionModalCloseButton\').click(); animatePozcard = false; playPozcard();">' + $("#i18SkipToEndLabel").html() + '</a>';
      html += '<a href="javascript: void(0);" class="tiny button right" onClick="$(\'#checkinDescriptionModalCloseButton\').click(); animatePozcard = true; playPozcard();">' + $("#i18NextLabel").html() + '</a>';
    } else {
      html += '<a href="javascript: void(0);" class="tiny secondary button right" onClick="$(\'#checkinDescriptionModalCloseButton\').click(); playPozcard();">' + $("#i18CloseLabel").html() + '</a>';
    }

    html += '</div>';
    $("#checkinDescription").html(html);
    revealDialog("#checkinDescriptionModal");
    //infowindow.setContent(html);
    playPosition++;
  }
}

function createQuote(quote, quoteDate, cite) {
  if (cite == null || cite.length == 0) {
    cite = "Anonymous Pozzian";
  }
  var cite = '<cite>' + cite + ", <small>" + quoteDate + '</small></cite>';
  var blockquote = '<blockquote>';
  blockquote += quote;
  blockquote += cite;
  blockquote += '</blockquote>';
  return blockquote;
}

function createVcard(name, vicinity, website) {
  var vcard = '<ul class="vcard">';
  vcard += '<li class="fn">' + name + '</li>';
  vcard += '<li class="street-address">' + vicinity + '</li>';
  if (website != null && website.length > 0) {
    vcard += '<li class="website"><a href="' + website + '">website</a></li>';
  }
  vcard += '</ul>';
  return vcard;
}

function drawLine(coordinates) {
  consoleLog(coordinates);
  line = new google.maps.Polyline({
    path: coordinates,
    icons: [{
      icon: lineSymbol,
      offset: '0%'
    }],
    geodesic: true,
    strokeColor: '#FF0000',
    strokeOpacity: 0.8,
    strokeWeight: 2,
    map: map
  });
  linesArray.push(line);
  animateSymbol();
}

function animateSymbol() {
  if (animatePozcard) {
    var count = 0;
    var intervalObj = window.setInterval(function () {
      count = (count + 2);
      var icons = line.get('icons');
      if (icons != null) {
        icons[0].offset = (count) + '%';
        line.set('icons', icons);
      }
      if (count == 100) {
        line.setOptions({
          icons: null
        });
        showMarkerPersonalMessage();
        clearInterval(intervalObj);
      }
    }, 20)
  } else {
    line.setOptions({
      icons: null
    });
    playPosition++;
    playPozcard();
  }
}

function removeLines() {
  for (var key in linesArray) {
    linesArray[key].setVisible(false);
    linesArray[key].setMap(null);
  }
  linesArray = [];
}


function createPozcardMarker(place) {
  var marker = new google.maps.Marker({
    map: map,
    position: new google.maps.LatLng(place["lat"], place["lng"]),
    icon: "/img/challenge-icon.png"
  });

  google.maps.event.addListener(marker, 'click', function () {
    var vcard = createVcard(place["name"], place["vicinity"], place["website"])
    var description = $("<div/>").text(place["description"]).html().replace(/\n/g, '<br />');
    var blockquote = createQuote(description, place["checkin_date"], pozcardNickname)

    revealMessageDialog("", vcard + blockquote);
  });

  markers.push(marker);
  markersObjArray[place.id] = marker;

  var placeCont = new Place();
  placeCont.setPlaceResult(place);
  placeCont.setLat(place["lat"]);
  placeCont.setLng(place["lng"]);
  placeCont.setCheckinDate(place["date_time"]);
  placeCont.setPozcardDescription(place["description"]);
  placeCont.setWebsite(place["website"]);
  placesArray.push(placeCont);
  placesObjArray[place["id"] + place["date_time"]] = placeCont;
}

/**
 *  The function for calculating the cluster icon image.
 *
 *  @param {Array.<google.maps.Marker>} markers The markers in the clusterer.
 *  @param {number} numStyles The number of styles available.
 *  @return {Object} A object properties: 'text' (string) and 'index' (number).
 *  @private
 */
calculator_ = function (markers, numStyles) {
  var index = 0;
  var count = markers.length;
  var male = 0;
  var female = 0;
  for (var idx in markers) {
    if (markers[idx].icon.indexOf("venus") > -1) {
      female++;
    } else {
      male++;
    }
  }

  var percentageMale = (male / (female + male) * 100).toFixed(0);
  if (percentageMale == 0) {
    index = 1;
  } else if (percentageMale >= 0 && percentageMale <= 10) {
    index = 2;
  } else if (percentageMale > 10 && percentageMale <= 20) {
    index = 3;
  } else if (percentageMale > 10 && percentageMale <= 20) {
    index = 4;
  } else if (percentageMale > 20 && percentageMale <= 30) {
    index = 5;
  } else if (percentageMale > 30 && percentageMale <= 40) {
    index = 6;
  } else if (percentageMale > 40 && percentageMale <= 50) {
    index = 7;
  } else if (percentageMale > 50 && percentageMale <= 60) {
    index = 8;
  } else if (percentageMale > 60 && percentageMale <= 70) {
    index = 9;
  } else if (percentageMale > 70 && percentageMale <= 80) {
    index = 10;
  } else if (percentageMale > 80 && percentageMale <= 90) {
    index = 11;
  } else if (percentageMale > 90 && percentageMale < 100) {
    index = 12;
  } else if (percentageMale == 100) {
    index = 13;
  } else {
    index = 14;
  }

  index = Math.min(index, numStyles);
  return {
    text: count,
    index: index
  };
};
