// Now with TimeMap object fun.

$(document).ready(function(){
	var tm = new TimeMap(
  		document.getElementById("timeline"), 
		document.getElementById("map"),
		{}
    );
    
    var artists = tm.createDataset("artists", {title:"Artists"});
    var authors = tm.createDataset("authors", {
            title:"Authors",
            theme:TimeMapDataset.greenTheme()
        });
    authors.eventSource = artists.eventSource;
    var events = tm.createDataset("events", {
            title:"Events",
            theme:TimeMapDataset.purpleTheme()
        });
    events.eventSource = artists.eventSource;
	
	var artistTheme = Timeline.ClassicTheme.create();
	artistTheme.event.track = {
            offset:         0.2, // em
            height:         1.2, // em
            gap:            0.2  // em
    };
    
	var artistBands = [
		Timeline.createBandInfo({
		             eventSource:    artists.eventSource,
		             width:          "80%", 
		             intervalUnit:   Timeline.DateTime.DECADE, 
		             intervalPixels: 100,
					 theme:	         artistTheme
		                                 }),
		Timeline.createBandInfo({
		             eventSource:    null,
		             width:          "20%", 
		             intervalUnit:   Timeline.DateTime.CENTURY, 
		             intervalPixels: 300,
		             trackHeight:    0.75,
		             trackGap:       0.2
                                         })
    ];
	
	tm.initTimeline(artistBands);
    tm.createLegend("legend");
	
    var query1 = [
        {
          "/common/topic/image" : {
            "limit" : 1,
            "id" : null,
            "optional" : true
          },
          "/people/deceased_person/date_of_death" : null,
          "/people/person/date_of_birth" : null,
          "/people/person/date_of_birth<" : "1700",
          "/people/person/date_of_birth>" : "1400",
          "/people/person/place_of_birth" : {
            "geolocation" : {
              "latitude" : null,
              "longitude" : null
            },
            "name" : null
          },
          "name" : null,
          "sort" : "/people/person/date_of_birth",
          "type" : "/visual_art/visual_artist"
        }
    ];
    var query2 = [
        {
          "/common/topic/image" : {
            "limit" : 1,
            "id" : null
          },
          "/people/deceased_person/date_of_death" : null,
          "/people/person/date_of_birth" : null,
          "/people/person/date_of_birth<" : "1700",
          "/people/person/date_of_birth>" : "1400",
          "/people/person/place_of_birth" : {
            "geolocation" : {
              "latitude" : null,
              "longitude" : null
            },
            "name" : null
          },
          "name" : null,
          "sort" : "/people/person/date_of_birth",
          "type" : "/people/person"
        }
    ];
    
    var query3 = [
        {
          "/common/topic/image" : {
            "limit" : 1,
            "id" : null,
            "optional" : true
          },
          "/people/deceased_person/date_of_death" : null,
          "/people/person/date_of_birth" : null,
          "/people/person/date_of_birth<" : "1700",
          "/people/person/date_of_birth>" : "1400",
          "/people/person/place_of_birth" : {
            "geolocation" : {
              "latitude" : null,
              "longitude" : null
            },
            "name" : null
          },
          "name" : null,
          "sort" : "/people/person/date_of_birth",
          "type" : "/book/author"
        }
    ];
    
    var query4 = [
        {
          "/common/topic/image" : {
            "limit" : 1,
            "id" : null,
            "optional" : true
          },
          "/people/deceased_person/date_of_death" : null,
          "/people/person/date_of_birth" : null,
          "/people/person/date_of_birth<" : "1700",
          "/people/person/date_of_birth>" : "1400",
          "/people/person/place_of_birth" : {
            "geolocation" : {
              "latitude" : null,
              "longitude" : null
            },
            "name" : null
          },
          "name" : null,
          "sort" : "/people/person/date_of_birth",
          "type" : "/religion/founding_figure"
        }
    ];
    
    var query5 = [
        {
          "locations" : {
            "geolocation" : {
              "latitude" : null,
              "longitude" : null
            },
            "name" : null
          },
          "name" : null,
          "start_date" : null,
          "start_date<" : "1700",
          "start_date>" : "1400",
          "type" : "/military/military_conflict"
        }
    ];
    
    Metaweb.read(query3, function(result) {
        authors.loadItems(result, transformPersonData);
    });
    
    Metaweb.read(query5, function(result) {
        events.loadItems(result, transformEventData);
    });
    
    Metaweb.read(query1, function(result) {
        artists.loadItems(result, transformPersonData);
	    tm.timeline.getBand(0).setCenterVisibleDate(artists.eventSource.getEarliestDate());
    });
	
});

function transformPersonData(data) {
	var start = data["/people/person/date_of_birth"];
	var end = data["/people/deceased_person/date_of_death"];
	var strBirth = data["/people/person/date_of_birth"].substr(0, 4);
    if (data["/people/deceased_person/date_of_death"] != null)
	    var strDeath = data["/people/deceased_person/date_of_death"].substr(0, 4);
    else return null;
	var title = data["name"] + " (" + strBirth + "-" + strDeath + ")";
	var description = data["/people/person/place_of_birth"]["name"];
    var newData = {
		"title" : title,
		"start" : start,
		"end" : end,
        "options" : {
    		"description" : description
        }
	};
    if ("geolocation" in data["/people/person/place_of_birth"]) {
        var lat = parseFloat(data["/people/person/place_of_birth"]["geolocation"]["latitude"]);
	    var lon = parseFloat(data["/people/person/place_of_birth"]["geolocation"]["longitude"]);
        newData["point"] = {
    		"lat" : lat,
            "lon" : lon
            };
    } else if ("polygon" in data["/people/person/place_of_birth"]) {
        newData["polygon"] = data["/people/person/place_of_birth"]["polygon"];
    }
    else if ("polyline" in data["/people/person/place_of_birth"]) {
        newData["polyline"] = data["/people/person/place_of_birth"]["polyline"];
    }
    if ("/common/topic/image" in data && data["/common/topic/image"] != null) {
        var imageUrl = "http://www.freebase.com/api/trans/image_thumb" + 
            data["/common/topic/image"]["id"] + 
            "?maxheight=120&maxwidth=120";
        var infoHtml = '<div class="infotitle"><b>' + title + '</b></div>';
        infoHtml += '<div style="padding:5px;width:130px;height:130px;"><img src="' + imageUrl + '"></div>';
        newData["options"]["infoHtml"] = infoHtml;
    }
	return newData;
}

function transformEventData(data) {
	var start = data["start_date"];
	var title = data["name"];
	var description = data["locations"]["name"];
    var newData = {
		"title" : title,
		"start" : start,
        "options" : {
    		"description" : description
        }
	};
    if ("geolocation" in data["locations"]) {
        var lat = parseFloat(data["locations"]["geolocation"]["latitude"]);
	    var lon = parseFloat(data["locations"]["geolocation"]["longitude"]);
        newData["point"] = {
    		"lat" : lat,
            "lon" : lon
            };
    } 
    if ("/common/topic/image" in data && data["/common/topic/image"] != null) {
        var imageUrl = "http://www.freebase.com/api/trans/image_thumb" + 
            data["/common/topic/image"]["id"] + 
            "?maxheight=120&maxwidth=120";
        var infoHtml = '<div class="infotitle"><b>' + title + '</b></div>';
        infoHtml += '<div style="padding:5px;width:130px;height:130px;"><img src="' + imageUrl + '"></div>';
        newData["options"]["infoHtml"] = infoHtml;
    }
	return newData;
}
