addDOMLoadEvent(createMap);
addDOMLoadEvent(setupPeriodical);

// Simulates PHP's date function
Date.prototype.format = function(format) {
	var returnStr = '';
	var replace = Date.replaceChars;
	for (var i = 0; i < format.length; i++) {
		var curChar = format.charAt(i);
		if (replace[curChar]) {
			returnStr += replace[curChar].call(this);
		} else {
			returnStr += curChar;
		}
	}
	return returnStr;
};
Date.replaceChars = {
	shortMonths: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
	longMonths: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
	shortDays: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
	longDays: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],

	// Day
	d: function() { return (this.getDate() < 10 ? '0' : '') + this.getDate(); },
	D: function() { return Date.replaceChars.shortDays[this.getDay()]; },
	j: function() { return this.getDate(); },
	l: function() { return Date.replaceChars.longDays[this.getDay()]; },
	N: function() { return this.getDay() + 1; },
	S: function() { return (this.getDate() % 10 == 1 && this.getDate() != 11 ? 'st' : (this.getDate() % 10 == 2 && this.getDate() != 12 ? 'nd' : (this.getDate() % 10 == 3 && this.getDate() != 13 ? 'rd' : 'th'))); },
	w: function() { return this.getDay(); },
	z: function() { return "Not Yet Supported"; },
	// Week
	W: function() { return "Not Yet Supported"; },
	// Month
	F: function() { return Date.replaceChars.longMonths[this.getMonth()]; },
	m: function() { return (this.getMonth() < 9 ? '0' : '') + (this.getMonth() + 1); },
	M: function() { return Date.replaceChars.shortMonths[this.getMonth()]; },
	n: function() { return this.getMonth() + 1; },
	t: function() { return "Not Yet Supported"; },
	// Year
	L: function() { return (((this.getFullYear()%4==0)&&(this.getFullYear()%100 != 0)) || (this.getFullYear()%400==0)) ? '1' : '0'; },
	o: function() { return "Not Supported"; },
	Y: function() { return this.getFullYear(); },
	y: function() { return ('' + this.getFullYear()).substr(2); },
	// Time
	a: function() { return this.getHours() < 12 ? 'am' : 'pm'; },
	A: function() { return this.getHours() < 12 ? 'AM' : 'PM'; },
	B: function() { return "Not Yet Supported"; },
	g: function() { return this.getHours() % 12 || 12; },
	G: function() { return this.getHours(); },
	h: function() { return ((this.getHours() % 12 || 12) < 10 ? '0' : '') + (this.getHours() % 12 || 12); },
	H: function() { return (this.getHours() < 10 ? '0' : '') + this.getHours(); },
	i: function() { return (this.getMinutes() < 10 ? '0' : '') + this.getMinutes(); },
	s: function() { return (this.getSeconds() < 10 ? '0' : '') + this.getSeconds(); },
	// Timezone
	e: function() { return "Not Yet Supported"; },
	I: function() { return "Not Supported"; },
	O: function() { return (-this.getTimezoneOffset() < 0 ? '-' : '+') + (Math.abs(this.getTimezoneOffset() / 60) < 10 ? '0' : '') + (Math.abs(this.getTimezoneOffset() / 60)) + '00'; },
	P: function() { return (-this.getTimezoneOffset() < 0 ? '-' : '+') + (Math.abs(this.getTimezoneOffset() / 60) < 10 ? '0' : '') + (Math.abs(this.getTimezoneOffset() / 60)) + ':' + (Math.abs(this.getTimezoneOffset() % 60) < 10 ? '0' : '') + (Math.abs(this.getTimezoneOffset() % 60)); },
	T: function() { var m = this.getMonth(); this.setMonth(0); var result = this.toTimeString().replace(/^.+ \(?([^\)]+)\)?$/, '$1'); this.setMonth(m); return result;},
	Z: function() { return -this.getTimezoneOffset() * 60; },
	// Full Date/Time
	c: function() { return this.format("Y-m-d") + "T" + this.format("H:i:sP"); },
	r: function() { return this.toString(); },
	U: function() { return this.getTime() / 1000; }
};

function setupPeriodical()
{
    new Ajax.PeriodicalUpdater('twitpicWrapper', 'data/twitpic.php', {frequency: 600});
    new Ajax.PeriodicalUpdater('twitterWrapper', 'data/twitter.php', {frequency: 600});
    new Ajax.PeriodicalUpdater('audiobooWrapper', 'data/audioboo.php', {frequency: 600});
}

function createMap()
{
    var osMap = new OpenSpace.Map('map');
    var gridProjection = new OpenSpace.GridProjection();
    var myLonLat = new OpenLayers.LonLat(-0.852169, 52.1468);
    osMap.setCenter(gridProjection.getMapPointFromLonLat(myLonLat), 1);
    loadMarkers(osMap, false);

    if (getURLVariable("date")=="") {
        new PeriodicalExecuter(function() {
                            loadMarkers(osMap, true);
                       }, 600);
    }
}

function loadMarkers(osMap, refresh) {
    osMap.destroyFeatures();
    routeDate = getURLVariable("date");
    //if (routeDate!="") url = "data/route.php?r=" + Math.floor(Math.random()*1000000) + "&date=" + routeDate;
    //else url = "data/route.php?r=" + Math.floor(Math.random()*1000000);
    if (routeDate!="") {
        url = "data/routeNEW.php?x=map&y=offasdyke4ms&z="+routeDate+"&r=" + Math.floor(Math.random()*1000000);
    }
    else {
        todayDate = new Date();
        routeDate = todayDate.format("Y-m-d");
        //alert(routeDate);
        url = "data/routeNEW.php?x=map&y=offasdyke4ms&z="+routeDate+"&r=" + Math.floor(Math.random()*1000000);
    }
    buildMarkersFromXML(osMap, url, refresh);
}

function buildMarkersFromXML(osMap, fileName, refresh)
{
       var bounds = new OpenSpace.MapBounds();
       var gridProjection = new OpenSpace.GridProjection();
       var points = [];
       var style = {
            strokeColor: "#2099c1",
            strokeOpacity: 0.6,
            strokeWidth: 6
       };
       style = {
            strokeColor: "#FF9900",
            strokeOpacity: 0.7,
            strokeWidth: 10
       };
       var linesLayer = osMap.getVectorLayer();
       osMap.addLayer(linesLayer);

       //var twitterIconSize = new OpenLayers.Size(36,53);
       //var twitterIconOffset = new OpenLayers.Pixel(-18,-53);
       //var twitterInfoWindowAnchor = new OpenLayers.Pixel(18,53);
       //var twitterIcon = new OpenSpace.Icon('http://www.mycountryside.org.uk/markers/twitter.png', twitterIconSize, twitterIconOffset, null, twitterInfoWindowAnchor);

       var twitterIconSize = new OpenLayers.Size(20,20);
       var twitterIconOffset = new OpenLayers.Pixel(-10,-10);
       var twitterInfoWindowAnchor = new OpenLayers.Pixel(10,10);
       var twitterIcon = new OpenSpace.Icon('http://www.mycountryside.org.uk/markers/twitterNewIcon.png', twitterIconSize, twitterIconOffset, null, twitterInfoWindowAnchor);

       //var twitpicIconSize = new OpenLayers.Size(36,53);
       //var twitpicIconOffset = new OpenLayers.Pixel(-18,-53);
       //var twitpicInfoWindowAnchor = new OpenLayers.Pixel(18,53);
       //var twitpicIcon = new OpenSpace.Icon('http://www.mycountryside.org.uk/markers/twitpic.png', twitpicIconSize, twitpicIconOffset, null, twitpicInfoWindowAnchor);
       
       var twitpicIconSize = new OpenLayers.Size(20,20);
       var twitpicIconOffset = new OpenLayers.Pixel(-10,-10);
       var twitpicInfoWindowAnchor = new OpenLayers.Pixel(10,10);
       var twitpicIcon = new OpenSpace.Icon('http://www.mycountryside.org.uk/markers/twitpicNewIcon.png', twitpicIconSize, twitpicIconOffset, null, twitpicInfoWindowAnchor);

       //var bothIconSize = new OpenLayers.Size(36,53);
       //var bothIconOffset = new OpenLayers.Pixel(-18,-53);
       //var bothInfoWindowAnchor = new OpenLayers.Pixel(18,53);
       //var bothIcon = new OpenSpace.Icon('http://www.mycountryside.org.uk/markers/both.png', bothIconSize, bothIconOffset, null, bothInfoWindowAnchor);

       var bothIconSize = new OpenLayers.Size(20,20);
       var bothIconOffset = new OpenLayers.Pixel(-10,-10);
       var bothInfoWindowAnchor = new OpenLayers.Pixel(10,10);
       var bothIcon = new OpenSpace.Icon('http://www.mycountryside.org.uk/markers/allNewIcon.png', bothIconSize, bothIconOffset, null, bothInfoWindowAnchor);

       //var audiobooIconSize = new OpenLayers.Size(36,53);
       //var audiobooIconOffset = new OpenLayers.Pixel(-18,-53);
       //var audiobooInfoWindowAnchor = new OpenLayers.Pixel(18,53);
       //var audiobooIcon = new OpenSpace.Icon('http://www.mycountryside.org.uk/markers/audioboo.png', audiobooIconSize, audiobooIconOffset, null, audiobooInfoWindowAnchor);

       var audiobooIconSize = new OpenLayers.Size(20,20);
       var audiobooIconOffset = new OpenLayers.Pixel(-10,-10);
       var audiobooInfoWindowAnchor = new OpenLayers.Pixel(10,10);
       var audiobooIcon = new OpenSpace.Icon('http://www.mycountryside.org.uk/markers/audiobooNewIcon.png', audiobooIconSize, audiobooIconOffset, null, audiobooInfoWindowAnchor);

       var blobIconSize = new OpenLayers.Size(14,14);
       var blobIconOffset = new OpenLayers.Pixel(-7,-7);
       var blobInfoWindowAnchor = new OpenLayers.Pixel(7,7);
       var blobIcon = new OpenSpace.Icon('http://www.mycountryside.org.uk/markers/blobIcon/image.png', blobIconSize, blobIconOffset, null, blobInfoWindowAnchor);

       var startBlobIconSize = new OpenLayers.Size(14,14);
       var startBlobIconOffset = new OpenLayers.Pixel(-7,-7);
       var startBlobInfoWindowAnchor = new OpenLayers.Pixel(7,7);
       var startBlobIcon = new OpenSpace.Icon('http://www.mycountryside.org.uk/markers/startblobIcon/image.png', startBlobIconSize, startBlobIconOffset, null, startBlobInfoWindowAnchor);

       var endBlobIconSize = new OpenLayers.Size(14,14);
       var endBlobIconOffset = new OpenLayers.Pixel(-7,-7);
       var endBlobInfoWindowAnchor = new OpenLayers.Pixel(7,7);
       var endBlobIcon = new OpenSpace.Icon('http://www.mycountryside.org.uk/markers/endBlobIcon/image.png', endBlobIconSize, endBlobIconOffset, null, endBlobInfoWindowAnchor);

       GDownloadUrl(fileName, function(data) {
           var xml = GXml.parse(data);
           var markers = xml.documentElement.getElementsByTagName("marker");
           if (markers.length>0)
           {
               
               for (var i = 0; i < markers.length; i++) {
                    var infoWindowSize = new OpenLayers.Size(250,175);
                    myLonLat = new OpenLayers.LonLat(markers[i].getAttribute("lng"), markers[i].getAttribute("lat"));
                    myMapPoint = gridProjection.getMapPointFromLonLat(myLonLat);
                    bounds.extend(myMapPoint);
                    var infowindow = GXml.value(markers[i].getElementsByTagName("infowindow")[0]);
                    var iconName = markers[i].getAttribute("icon");

                    if (iconName == "bothIcon") {
                        useIcon = bothIcon.clone();
                        infoWindowSize = new OpenLayers.Size(400,250);
                    }
                    else if (iconName == "twitterIcon") {
                        useIcon = twitterIcon.clone();
                        infoWindowSize = new OpenLayers.Size(400,250);
                    }
                    else if (iconName == "twitpicIcon") {
                        useIcon = twitpicIcon.clone();
                        infoWindowSize = new OpenLayers.Size(400,250);
                    }
                    else if (iconName == "audiobooIcon") {
                        useIcon = audiobooIcon.clone();
                        infoWindowSize = new OpenLayers.Size(400,250);
                    }
                    else if (i==0) {
                        useIcon = startBlobIcon.clone();
                        var marker = osMap.createMarker(myMapPoint, useIcon, infowindow, infoWindowSize);
                    }
                    else if (i==markers.length-1&&getURLVariable("date")!="") {
                        useIcon = endBlobIcon.clone();
                        var marker = osMap.createMarker(myMapPoint, useIcon, infowindow, infoWindowSize);
                    }
                    else {
                        useIcon = blobIcon.clone();
                        var marker = osMap.createMarker(myMapPoint, useIcon, infowindow, infoWindowSize);
                    }

                    points.push(new OpenLayers.Geometry.Point(myMapPoint.getEasting(), myMapPoint.getNorthing()));

                    if (i==markers.length-1) {
                        lastPoint = gridProjection.getMapPointFromLonLat(myLonLat);
                        lastIcon = useIcon;
                        lastInfo = infowindow;
                        lastInfoWindowSize = infoWindowSize;
                    }
               }

               for (var i = 0; i < markers.length; i++) {
                    var infoWindowSize = new OpenLayers.Size(250,175);
                    myLonLat = new OpenLayers.LonLat(markers[i].getAttribute("lng"), markers[i].getAttribute("lat"));
                    myMapPoint = gridProjection.getMapPointFromLonLat(myLonLat);
                    var infowindow = GXml.value(markers[i].getElementsByTagName("infowindow")[0]);
                    var iconName = markers[i].getAttribute("icon");

                    if (iconName == "bothIcon") {
                        useIcon = bothIcon.clone();
                        infoWindowSize = new OpenLayers.Size(400,250);
                        marker = osMap.createMarker(myMapPoint, useIcon, infowindow, infoWindowSize);
                    }
                    else if (iconName == "twitterIcon") {
                        useIcon = twitterIcon.clone();
                        infoWindowSize = new OpenLayers.Size(400,250);
                        marker = osMap.createMarker(myMapPoint, useIcon, infowindow, infoWindowSize);
                    }
                    else if (iconName == "twitpicIcon") {
                        useIcon = twitpicIcon.clone();
                        infoWindowSize = new OpenLayers.Size(400,250);
                        marker = osMap.createMarker(myMapPoint, useIcon, infowindow, infoWindowSize);
                    }
                    else if (iconName == "audiobooIcon") {
                        useIcon = audiobooIcon.clone();
                        infoWindowSize = new OpenLayers.Size(400,250);
                        marker = osMap.createMarker(myMapPoint, useIcon, infowindow, infoWindowSize);
                    }
               }

               var lineString = new OpenLayers.Geometry.LineString(points);
               var lineFeature = new OpenLayers.Feature.Vector(lineString, null, style);
               linesLayer.addFeatures([lineFeature]);

               if (getURLVariable("date")=="") {
                   if (refresh) {
                       
                   } else {
                       osMap.openInfoWindow(lastIcon, lastPoint, lastInfo, lastInfoWindowSize);
                       osMap.setCenter(lastPoint, 7);
                   }
                   $('updateMessage').innerHTML = "Looks like we are walking today :) - the map (as well as tweets, photos, and audio) will automatically refresh every 10 minutes. Click on the markers to view altitude, speed and heading at each point, as well as any photos, tweets (text messages) and audio";
               } else {
                   osMap.setCenter(bounds.getCenterLonLat(), 5);
                   bounds.toBBOX();
                   osMap.zoomToExtent(bounds);
                   $('updateMessage').innerHTML = "The route you have selected has loaded on the map above - click on the markers to view altitude, speed and heading at each point, as well as any photos, tweets (text messages) and audio.";
               }    

           } else {
               if (getURLVariable("date")=="") $('updateMessage').innerHTML = "It does not look like we have started walking yet today. The map (as well as tweets, photos, and audio) will automatically refresh every 10 minutes, or select another route from the righthand menu.";
               else $('updateMessage').innerHTML = "No route available for this date. Please select another route from the righthand menu.";
           }
        });
}