// This code (C) Stuart Lewis
var map;
var everything = new Array();
var currentIcon = 'normal';
var displayed = new Array();
var first = true;
var currentPlatform;
var currentCountry;
var currentFromMonth;
var currentFromYear;
var currentToMonth;
var currentToYear;
var totalcount = 0;

function load() {
	if (GBrowserIsCompatible()) {
		document.getElementById('button-sidebar-hide').onclick = function() { return changeBodyClass('sidebar-right', 'nosidebar'); };
		document.getElementById('button-sidebar-show').onclick = function() { return changeBodyClass('nosidebar', 'sidebar-right'); };
		handleResize();

        map = new GMap2(document.getElementById("map"));
		map.enableContinuousZoom();
		map.enableDoubleClickZoom();
		map.addControl(new GLargeMapControl());
		map.addControl(new GMapTypeControl());
		map.enableScrollWheelZoom();
		map.setCenter(new GLatLng(26, 26), 2);

		// Create our icons
        var eprintsicon = new GIcon();
        eprintsicon.image = "images/eprintssmall.png";
        eprintsicon.iconSize = new GSize(10, 10);
        eprintsicon.iconAnchor = new GPoint(5, 5);
        eprintsicon.infoWindowAnchor = new GPoint(7, 5);
        var dspaceicon = new GIcon();
        dspaceicon.image = "images/dspacesmall.png";
        dspaceicon.iconSize = new GSize(10, 10);
        dspaceicon.iconAnchor = new GPoint(5, 5);
        dspaceicon.infoWindowAnchor = new GPoint(7, 5);
        var fedoraicon = new GIcon();
        fedoraicon.image = "images/fedorasmall.png";
        fedoraicon.iconSize = new GSize(10, 10);
        fedoraicon.iconAnchor = new GPoint(5, 5);
        fedoraicon.infoWindowAnchor = new GPoint(7, 5);
        var oricon = new GIcon();
        oricon.image = "images/orsmall.png";
        oricon.iconSize = new GSize(10, 10);
        oricon.iconAnchor = new GPoint(5, 5);
        oricon.infoWindowAnchor = new GPoint(7, 5);
        var bepressicon = new GIcon();
        bepressicon.image = "images/bepresssmall.png";
        bepressicon.iconSize = new GSize(10, 10);
        bepressicon.iconAnchor = new GPoint(5, 5);
        bepressicon.infoWindowAnchor = new GPoint(7, 5);
        var opusicon = new GIcon();
        opusicon.image = "images/opussmall.png";
        opusicon.iconSize = new GSize(10, 10);
        opusicon.iconAnchor = new GPoint(5, 5);
        opusicon.infoWindowAnchor = new GPoint(7, 5);
        var etddbicon = new GIcon();
        etddbicon.image = "images/etddbsmall.png";
        etddbicon.iconSize = new GSize(10, 10);
        etddbicon.iconAnchor = new GPoint(5, 5);
        etddbicon.infoWindowAnchor = new GPoint(7, 5);
        var othericon = new GIcon();
        othericon.image = "images/othersmall.png";
        othericon.iconSize = new GSize(10, 10);
        othericon.iconAnchor = new GPoint(5, 5);
        othericon.infoWindowAnchor = new GPoint(7, 5);
	
        function createMarker(point, index, icon, rtype, rname, rurl, rbase, rcontents, items, rdate, rid, r66id) {
			var marker = new GMarker(point, {icon:icon, title:rname});
           
            var growthgraphurl = "http://celestial.eprints.org/identifiers?baseURL=" + rbase + "&format=graph&svg=0&cumu=1&logy_cumu=0";
            var infoTabs = [
				new GInfoWindowTab("Info", 
                                   "<b>" + rname + "</b><br />" + 
								   "<a href='" + rurl + "' target='_blank'>" + rurl + "</a><br />" + 
                                   "Type: " + rcontents + "<br />" + 
                                   "Platform: " + rtype + "<br />" + 
                                   "Registered: " + rdate + "<br />" + 
                                   "OAI-PMH base URL: " + rbase + "<br />" + 
                                   "Contains: " + items + " items"),
				new GInfoWindowTab("OpenDOAR",
								   "<iframe src='http://maps.repository66.org/opendoar.php?r66id=" + r66id + "&x=" + Math.random() + "'  width=\"350\" height=\"200\" frameborder=\"0\" scrolling=\"auto\" framespacing=\"0\" border=\"0\" />"),
                new GInfoWindowTab("Growth",
				                   "<iframe src='http://maps.repository66.org/ggraph.php?r66id=" + r66id + "&x=" + Math.random() + "' width=\"350\" height=\"200\" frameborder=\"0\" scrolling=\"no\" framespacing=\"0\" border=\"0\" />"),
                new GInfoWindowTab("Search", 
                                   "<form method=\"get\" action=\"search.php\"><b>Search this repository using:</b><br />" + 
                                   "<input type=\"text\" name=\"q\" /><br />" + 
                                   "<input type=\"radio\" name=\"s\" value=\"g\" checked=\"checked\" />Google<br />" + 
								   "<input type=\"radio\" name=\"s\" value=\"gs\" />Google Scholar<br />" + 
                                   "<!--<input type=\"radio\" name=\"s\" value=\"o\" />OAISter-->" + 
                                   "<input type=\"radio\" name=\"s\" value=\"a\" />Microsoft Live<br />" + 
                                   "<input type=\"submit\"><input type=\"hidden\" name=\"h\" value=\"" + rurl + "\" /></form>")
            ];
 
            GEvent.addListener(marker, "click", function() {
                marker.openInfoWindowTabsHtml(infoTabs);
            });

            return marker;
        }


        GDownloadUrl("dataset.php?set=uk&x="+Math.random(), function(data, responseCode) {
			document.getElementById("alert").innerHTML = "<p>Parsing repository data...<br /><img src='images/loading.gif' alt='Loading...' /></p>";
			var xml = GXml.parse(data);
            var markers = xml.documentElement.getElementsByTagName("repository");
            for (var i = 0; i < markers.length; i++) {
                var point = new GLatLng(parseFloat(markers[i].getAttribute("lat")),
                                        parseFloat(markers[i].getAttribute("lng")));
				var rtype = markers[i].getAttribute("rtype");
                var rname = markers[i].getAttribute("rname");
                var rurl = markers[i].getAttribute("rurl");
                var rbase = markers[i].getAttribute("rbase");
                var rcontents = markers[i].getAttribute("rcontents");
                var items = markers[i].getAttribute("items");
				var rdate = markers[i].getAttribute("m") + "/" + markers[i].getAttribute("y");
                var rid = markers[i].getAttribute("rid");
                var r66id = markers[i].getAttribute("r66id");
				var country = markers[i].getAttribute("c");
				var rdatedate = new Date();
				rdatedate.setFullYear(markers[i].getAttribute("y"), markers[i].getAttribute("m") - 1, 15);
				if ( (isNaN(markers[i].getAttribute("m"))) || (isNaN(markers[i].getAttribute("y"))) ||
                      (markers[i].getAttribute("m") == "") || (markers[i].getAttribute("y") == "") ||
                      (markers[i].getAttribute("m") == "0") || (markers[i].getAttribute("y") == "0") ) {
						//rdatedate.setFullYear(2999, 1, 1);
						rdatedate = new Date();
						rdate = "unknown";
				}

				// Create sized marker
				var sizeicon = new GIcon();
				sizeicon.image = "images/othersmall.png";
				if (rtype == 'dspace') { sizeicon.image = "images/dspacesmall.png"; }
				else if (rtype == 'eprints') { sizeicon.image = "images/eprintssmall.png"; }
				else if (rtype == 'fedora') { sizeicon.image = "images/fedorasmall.png"; }
				else if (rtype == 'bepress') { sizeicon.image = "images/bepresssmall.png"; }
				else if (rtype == 'openrepo') { sizeicon.image = "images/orsmall.png"; }
				else if (rtype == 'opus') { sizeicon.image = "images/opussmall.png"; }
				else if (rtype == 'etddb') { sizeicon.image = "images/etddbsmall.png"; }
				var min = 2;
				var max = 10;
				var sizecalc = items;
				if (isNaN(sizecalc)) { sizecalc = 10; }
				if (sizecalc < 10) { sizecalc = 10; }
				var size = 1 + ((Math.log(sizecalc) * Math.log(sizecalc)) / 4);
				sizeicon.iconSize = new GSize(size, size);
				sizeicon.iconAnchor = new GPoint(size / 2, size / 2);
				sizeicon.infoWindowAnchor = new GPoint(size / 3 * 2, size / 2);
				var mSize = createMarker(point, i, sizeicon, rtype, rname, rurl, rbase, rcontents, items, rdate, rid, r66id);
                
				// Create normal marker
				var icon = othericon; 
				if (rtype == "dspace") { icon = dspaceicon; } 
				else if (rtype == "eprints") { icon = eprintsicon; } 
				else if (rtype == "fedora") { icon = fedoraicon; }
				else if (rtype == "openrepo") { icon = oricon; } 
				else if (rtype == "bepress") { icon = bepressicon; }
				else if (rtype == "opus") { icon = opusicon; }
				else if (rtype == "etddb") { icon = etddbicon; }
				var m = createMarker(point, i, icon, rtype, rname, rurl, rbase, rcontents, items, rdate, rid, r66id);
				
				var bits = new Array();
				bits["marker"] = m;
				bits["sizemarker"] = mSize;
				bits["platform"] = rtype;
				bits["country"] = country;
				bits["date"] = rdate;
				bits["point"] = point;
				bits["date"] = rdatedate;
				everything.push(bits);
				
				totalcount++;
	    }	
	    document.getElementById("alert").innerHTML = "<p>Creating map points...<br /><img src=\"images/loading.gif\" alt=\"Loading...\" /><br />HINT: Click on a repository marker to see its full details</p>";
	    setTimeout('show("all", "all");', 20);
        });
	}
}


function windowHeight() {
	// Standard browsers (Mozilla, Safari, etc.)
	if (self.innerHeight)
		return self.innerHeight;
	// IE 6
	if (document.documentElement && document.documentElement.clientHeight)
		return document.documentElement.clientHeight;
	// IE 5
	if (document.body)
		return document.body.clientHeight;
	// Just in case.
	return 0;
}

function handleResize() {
	var height = windowHeight() - document.getElementById('toolbar').offsetHeight - 45;
	document.getElementById('map').style.height = height + 'px';
	document.getElementById('sidebar').style.height = height + 'px';
}

function changeBodyClass(from, to) {
	document.body.className = document.body.className.replace(from, to);
	return false;
}

function show(platform, country, frommonth, fromyear, tomonth, toyear, move) {
	var from=new Date();
	from.setFullYear(fromyear, frommonth -1, 1);
	if ((isNaN(fromyear)) || (isNaN(frommonth))) { from.setFullYear(1, 1, 1); }
	var to=new Date();
	to.setFullYear(toyear, tomonth, 1); 
	if ((isNaN(toyear)) || (isNaN(tomonth))) { to.setFullYear(3000, 1, 1); }    	
	
	if (country == '') { country = 'all'; }
	
	for (var i = 0; i < displayed.length; i++) { 
		map.removeOverlay(displayed[i]); 
	} 	
	
	displayed = new Array();
	var points = new Array();
	for (var i = 0; i < everything.length; i++) {
		if ((everything[i]["country"] == country) || (country == 'all')) {
			if ((everything[i]["platform"] == platform) || (platform == 'all')) {
				if ((everything[i]["date"] >= from) && (everything[i]["date"] < to)) {
					if (currentIcon == 'normal') {
						map.addOverlay(everything[i]["marker"]);
						displayed.push(everything[i]["marker"]);
						points.push(everything[i]["point"]);
					} else {
						map.addOverlay(everything[i]["sizemarker"]);
						displayed.push(everything[i]["sizemarker"]);
						points.push(everything[i]["point"]);
					}
				}
			}
		}
	}
	
	// Center and zoom on the bounds (not on first load)
	if (move != false) {
		if ((displayed.length > 0) && (displayed.length < totalcount)) {
			var bounds = new GLatLngBounds;
			for (var i = 0; i < points.length; i++) {
				bounds.extend(points[i]);
			}
			var zlevel = map.getBoundsZoomLevel(bounds);
			if (zlevel > 9) { zlevel = 9; }
			map.setZoom(zlevel);
			if (zlevel <= 2) {
				map.setCenter(new GLatLng(26, 26), 2);
			} else {
				map.setCenter(bounds.getCenter());
			}
		} else {
			// Go back to the default home screen if there are no repositories to show
			map.setCenter(new GLatLng(26, 26), 2);
		}
	}
	
	changeBodyClass('loading', 'standby');

	currentPlatform = platform;
	currentCountry = country;
	currentFromMonth = frommonth;
	currentFromYear = fromyear;
	currentToMonth = tomonth;
	currentToYear = toyear;
	
	first = false;
}

function icon(type) {
	if (currentIcon != type) {
		currentIcon = type;
		setTimeout('show(currentPlatform, currentCountry, currentFromMonth, currentFromYear, currentToMonth, currentToYear, false);', 20);
	}
}

function platform(platform) {
	if (currentPlatform != platform) {
		currentPlatform = platform;
		setTimeout('show(currentPlatform, currentCountry, currentFromMonth, currentFromYear, currentToMonth, currentToYear, false);', 20);
	}
}

function timeline() {
	for (var tlyear = 1997; tlyear < 2009; tlyear++) {
		show('all', 1, tlyear, 12, 2008);
		setTimeout('var dev-null;', 20);
	}
}

window.onresize = handleResize;
window.onload = load;
window.onunload = GUnload;

