// Copyright 2007 Google Inc.
// All Rights Reserved.

/**
 * @fileoverview JS code for populating Our Stories map.
 * @author groovebot@google.com (Lori Meiskey), muralidhar@google.com (Muralidhar K)
 */   
var map = null;
var geocoder = null;
var gmarkers = [];
var indices = [];
var orderedStories = [];
var currentMarker = null;
var currentStoryList = null;
var currentStoryIndex = null;

// === Create an associative array of GIcons() ===
var baseIcon = new GIcon(G_DEFAULT_ICON);
baseIcon.iconSize = new GSize(22, 30);

var gicons = [];

function createMap(datafile) {
  if (GBrowserIsCompatible()) {
    // ==== first part of the select box ===
    // =====================================           
    // create the map
    map = new GMap2(document.getElementById("map"));
    
    gicons["sc"] = new GIcon(baseIcon,"s_small.png"); 
    gicons["other"] = new GIcon(baseIcon,"ox_small.png"); 
    gicons["many"] = new GIcon(baseIcon,"ox_many.png");  

    // ====== Restricting the range of Zoom Levels =====
    // Get the list of map types      
    var mt = map.getMapTypes();
    // Overwrite the getMinimumResolution() and getMaximumResolution() methods
    for (var i=0; i<mt.length; i++) {
      mt[i].getMinimumResolution = function() {return 0;}
      mt[i].getMaximumResolution = function() {return 17;}
    }

    map.addControl(new GLargeMapControl());
    map.addControl(new GMapTypeControl());
    map.enableScrollWheelZoom();
    map.setCenter(new GLatLng(27.000, 0),1);

    ///////////////////////Geo-coder Search
    geocoder = new GClientGeocoder(); 

    GEvent.addListener(map, "click", function(overlay, point) {      
      document.trailerFlash.TGotoAndPlay("/", '6');
    });
    GEvent.addListener(map, "infowindowclose", function() {
      map.setCenter(new GLatLng(currentMarker.lat, currentMarker.lng), map.getZoom());
    });

    // Read the stories from data xml file. 
    // Parse the stories then index them by lat/lng.
    parseStories(datafile);

    //  ======== Add a map overview ==========
    //map.addControl(new GOverviewMapControl(new GSize(150,150)));
  }

  else {
    alert("Sorry, the Google Maps API is not compatible with this browser");
  }
}

// Read and index the stories.
function parseStories(datafile) {
    GDownloadUrl(datafile, function (doc) {
      var xmlDoc = GXml.parse(doc);
      var markers = xmlDoc.documentElement.getElementsByTagName("marker");
      for (var i = 0; i < markers.length; i++) {
        // obtain the attribues of each marker
        var lat = parseFloat(markers[i].getAttribute("lat"));
        var lng = parseFloat(markers[i].getAttribute("lng"));
        var point = new GLatLng(lat,lng);
        var label = markers[i].getAttribute("label");
        var source = markers[i].getAttribute("source");
        var movieLink = markers[i].getAttribute("movieLink");
        var speakers = markers[i].getAttribute("speakers");
        var location = markers[i].getAttribute("location");
        var sourceLink = markers[i].getAttribute("sourceLink");
        var sourceName = markers[i].getAttribute("sourceName");
	var visible = markers[i].getAttribute("visible");

        // === create and index the story ===
        if (visible != "false") {
          var story = createStory(label, movieLink, speakers, location, source, sourceLink, sourceName, lat, lng, point);
	  addStory(story);
        }
      }

      // Iterate through the indexed stories and add a marker for each one.
      for (var i = 0; i < indices.length; i++) {
	  createMarker(indices[i]);
      } 
    });
}

// Create a story container
function createStory(label, movieLink, speakers, location, source, sourceLink, sourceName, lat, lng, point) {
    var story = new Object();
    story.label = label;
    story.movieLink = movieLink;
    story.speakers = speakers;
    story.location = location;
    story.source = source;
    story.sourceLink = sourceLink;
    story.sourceName = sourceName;
    story.lat = lat;
    story.lng = lng;
    story.point = point;

    return story;
}

// A function to create a story and index it by lat/lng.
// For the first instance at each lat/lng, adds a map marker.
function addStory(story) {
    // Order markers by lat/lng
    var index = story.lat + "|" + story.lng;
    var tempStories = orderedStories[index];

    if (tempStories == null || tempStories.length == 0) {
	// This is a new lat/lng
	indices[indices.length] = index;
	tempStories = [];
        orderedStories[index] = tempStories;
    } 
    // Add this story.
    tempStories[tempStories.length] = story;              
  }

function createMarker(index) {
    var storyList = orderedStories[index];
    // lat, lng and point should be the same for all stories in 
    // the list.
    var lat = storyList[0].lat;
    var lng = storyList[0].lng;
    var point = storyList[0].point;
    var source;    

    if (storyList.length === 1) {
	source = storyList[0].source;
    } else {
	// TODO(groovebot): Add multi-story icon
	source = storyList[0].source;
    }

    var marker = new GMarker(point,gicons[source]);
    marker.lat = lat;
    marker.lng = lng;
    marker.index = index;    
    
    GEvent.addListener(marker, "click", function() { 
	    currentMarker = marker;	    
	    var html = getBubbleHtml(index);
	    //alert("html: " + html);
	    marker.openInfoWindowHtml(html);
        });              

    gmarkers[index] = marker;
    
    map.addOverlay(marker);
}


// Construct the html for the bubble
function getBubbleHtml(index) {
    var storyList = orderedStories[index];
    randomizeStories(storyList);
    currentStoryList = storyList;
    currentStoryIndex = 0;

    var topHtml = '<table border="0" cellpadding="1"><tr><td width="100%" colspan="3"><div id="storyDisplay" style="height:160px;">';
    var innerHtml = getStoryHtml(storyList[0]);    

    // TODO(groovebot): If storyLength > 1, add a scroller (next/prev)
    // Make the element above a div whose content be replaced
    // For "Next" and "Prev" links-- call js function that replaces the div
    // content with the next (or previous) item.
    var bottomHtml = '</div></td></tr></table>';
    if (storyList.length > 1) {
	bottomHtml = '</div></td></tr><tr>' +
	    '<td width="33%"><div id="previousLink">' + getEmptyLinkText() + '</div></td>'
	    + '<td align="center" nowrap="nowrap" width="34%"><div id="storyIndex">' + getStoryIndexDisplay() + '</div></td>'
	    + '<td align="right" width="33%"><div id="nextLink">' + getNextLink() + '</div></td></tr></table>';
    }
     
    return topHtml + innerHtml + bottomHtml;
  }

function getStoryIndexDisplay() {
    var indexDisplay = '<font size="-2">' 
	+ (currentStoryIndex + 1) + '&nbsp;of ' + currentStoryList.length 
	+ '&nbsp;stories</font>';
    return indexDisplay;
}

// Display the story with index i
function displayNextStory() {
    var newStoryIndex = currentStoryIndex + 1;
    document.getElementById('storyDisplay').innerHTML = getStoryHtml(currentStoryList[newStoryIndex]);
    currentStoryIndex = newStoryIndex;
    document.getElementById('storyIndex').innerHTML = getStoryIndexDisplay();
    document.getElementById('previousLink').innerHTML = getPreviousLink();

    // If not at the end of the story list, show Next link.
    var nextLinkText = getEmptyLinkText();
    if (currentStoryIndex <  (currentStoryList.length - 1)) {
	nextLinkText = getNextLink();
    } 
    document.getElementById('nextLink').innerHTML = nextLinkText;
} 

// Display the previous story
function displayPreviousStory() {
    var newStoryIndex = currentStoryIndex - 1;
    document.getElementById('storyDisplay').innerHTML = getStoryHtml(currentStoryList[newStoryIndex]);
    currentStoryIndex = newStoryIndex;
    document.getElementById('storyIndex').innerHTML = getStoryIndexDisplay();
    document.getElementById('nextLink').innerHTML = getNextLink();

    // If index > 0, show previous link
    var previousLinkText = getEmptyLinkText();
    if (currentStoryIndex > 0) {
	previousLinkText = getPreviousLink();
    }
    document.getElementById('previousLink').innerHTML = previousLinkText;
} 

function randOrd() {
    return (Math.round(Math.random())-0.5); 
}

function randomizeStories(stories) {
    stories.sort(randOrd);
}

function getEmptyLinkText() {
    var linkText = "&nbsp;";
    return linkText;
}

function getNextLink() {
    var linkText = '<font size="-2"><a href="#" onclick="displayNextStory()">Next&nbsp;&gt;&gt;</a>&nbsp;</font>';
    return linkText;
}

function getPreviousLink() {
    var linkText = '<font size="-2"><a href="#" onclick="displayPreviousStory()">&lt;&lt;&nbsp;Previous</a>&nbsp;</font>';
    return linkText;
}

// Construct the story portion of html for the bubble
function getStoryHtml(story) {
    var html = '<table width="400"><tr valign=top><td>' +      
	'<object width="125" height="94"><param name="movie" value="' + story.movieLink + '&rel=0"></param>' +
      '<param name="wmode" value="transparent"></param>' +
      '<embed src="' + story.movieLink + '&rel=0" type="application/x-shockwave-flash" wmode="transparent" width="125" height="94"></embed>' +
      '</object></td><td>&nbsp;</td>' +
      '<td width="270"><div id="label" style="height:90px; overflow:auto;"><font face="Arial" size="-1"><strong>'+ story.label + '</strong></font></div><br>--' + 
      story.speakers + '<br><font face="Arial" size="-2">Recorded in ' + story.location + '<br>Source: <a href="' + story.sourceLink + '">' + 
	story.sourceName +'</strong></a></font></td></tr></table>';

    return html;
  }


// ======= This function handles selections from the select box ====
// === If the dummy entry is selected, the info window is closed ==
function handleSelected(opt) {
  var i = opt.selectedIndex - -2; 
  if (i > -1) {
    GEvent.trigger(gmarkers[i],"click");
    map.addOverlay(new GMarker(point,(new GIcon(baseIcon, "yellow.png"))));
   }
   else {
     map.closeInfoWindow();
   }
 } 

//////////////////////////////////Geo-coder Search
  function showAddress(address) {
    if (geocoder) {
      geocoder.getLatLng(
        address,
        function(point) {
            if (!point) {
              alert(address + " not found");
            } else {
              map.setCenter(point, 5);
              var marker = new GMarker(point);
		map.openInfoWindow(map.getCenter(),document.createTextNode(address));
            }
          }
        );
      }
    }
