
	/*
	  "Strike Up Your Google Maps" Creation Tool
	  Copyright (c) 2006 Mart Web Studio
	
	  @author Martin Yung (www.martwebstudio.net)
	  @version 1.5 2006-04-30
	  
	  Changelog:
	  1.5 2006-04-29 Bugs fixed.
                         UTF-8 encoding support.
                         Performance enhancement for IE.
                         interface: added mouse wheel / key stroke support.
	  1.1 2006-04-12 Bugs fixed.
	*/
    
 
    var alert_saveForm = "Don't forget fill out all the information";
    var confirm_deleteMapData = "Click OK to create a new map and \n1. delete all makers\n2. delete all configuration";
    var confirm_openRss= "Click OK if you want to keep all markers shown\nCANCEL if you want to remove existing markers";
    var confirm_removeMarker = 'Remove this marker?';
    var prompt_openRss = "Tell me the web address of your GeoRSS file\n(e.g. http://www.mywebsite.com/georss.xml)";
    
    var iconSmall = new GIcon();
    iconSmall.image = "http://labs.google.com/ridefinder/images/mm_20_red.png";
    iconSmall.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
    iconSmall.iconSize = new GSize(12, 20);
    iconSmall.shadowSize = new GSize(22, 20);
    iconSmall.iconAnchor = new GPoint(6, 20);
    iconSmall.infoWindowAnchor = new GPoint(9, 2);
    iconSmall.infoShadowAnchor = new GPoint(18, 25);
    
    var marker = new Array();
    
    // "map" is the ID of the DIV in which the map contains
    var map = new GMap2(document.getElementById("map"));
    loadFile('plot.php');
	
    map.addControl(new GLargeMapControl());
    //map.addControl(new GSmallMapControl());
    map.addControl(new GMapTypeControl());
    map.addControl(new GOverviewMapControl());
    map.setCenter(new GLatLng(40.6890,-74.0443),2);
    //map.setMapType(G_NORMAL_MAP);
    //map.setMapType(G_SATELLITE_MAP);
    map.setMapType(G_HYBRID_MAP);
	
    GEvent.addListener(map, "dblclick", function(overlay, point){
  		var message = genForm(marker.length, 'Point '+marker.length, 'http://', '', parseFloat(point.y), parseFloat(point.x));
  		addMarker(new GLatLng(point.y,point.x), message, iconSmall);
  		marker[marker.length-1].openInfoWindowHtml(marker[marker.length-1].html);
    });
	
	function loadFile(fileName) {
	    
		// Your map data imported using XML external source
	    var request = GXmlHttp.create();
		request.open('GET', fileName, true);
		request.onreadystatechange = function() {
			
			if (request.readyState == 4) {
				
				var xmlDoc = request.responseXML;
				var items = xmlDoc.getElementsByTagName("item");
				
				/* Namespace 'geo' for non IE browsers */
				var xmlns_geo = 'http://www.w3.org/2003/01/geo/wgs84_pos#';
				
				for (var i = 0; i < items.length; i++) {
					
					var item = items[i];
					
					/* Create a point object */
					if (navigator.userAgent.toLowerCase().indexOf("msie") >= 0) {
					    var lng = item.getElementsByTagName('geo:long')[0].firstChild.nodeValue;
				        var lat = item.getElementsByTagName('geo:lat')[0].firstChild.nodeValue;
					}
					else {
				        var lng = item.getElementsByTagNameNS(xmlns_geo,'long')[0].firstChild.nodeValue;    // for Mozilla
					    var lat = item.getElementsByTagNameNS(xmlns_geo,'lat')[0].firstChild.nodeValue;     // for Mozilla
				    }
				    
					var point = new GLatLng(lat, lng);
					
					/* Create a marker object for the point we have just created */
					var title = item.getElementsByTagName("title")[0].firstChild.nodeValue;
					try{
					if (item.getElementsByTagName("link")[0] != null) {
						var link = item.getElementsByTagName("link")[0].firstChild.nodeValue;
					} else {
						var link = 'http://';
					}
					}catch(e) {}
          if (item.getElementsByTagName("description")[0].firstChild.nodeValue != '') {
            var description = item.getElementsByTagName("description")[0].firstChild.nodeValue;
  				} else {
  					var description = '';
  				}
  				try{
				  addMarker(point, genForm(i, title, link, description, lat, lng), iconSmall);
					document.getElementById("pointlist").innerHTML += title + '<br/>';
					}catch(e) {alert(e);}
			        if (i == 0) {
			            map.setCenter(point, 2);
			        }
	
				}
			}
		}
		
		request.send(null);	
	
	}

	
	function openRss(inUrl) {
		if (!inUrl) { inUrl = ''; }
    var url = prompt(prompt_openRss, inUrl);
		
		if (url != null) {
			if (!confirm(confirm_openRss)) {
				requestUrl('get','destroy=1');
				map.clearOverlays();
			}
			loadFile('download.php?url='+url);
		}
	}
	
	

    function goToThisPoint(id) {
	    marker[id].openInfoWindowHtml(marker[id].html);
    }
    
    
    function deleteMapData() {
        if (confirm(confirm_deleteMapData)) {
            requestUrl('get','destroy=1');
            map.clearOverlays();
        }
    }
    
    
    function saveConfig() {
        var theForm = document.forms["config"];
		var apikey = escape(theForm.apikey.value);
        var title = escape(theForm.title.value);
		var link = escape(theForm.link.value);
		var description = escape(theForm.description.value);
		var lat = escape(theForm.lat.value);
		var lng = escape(theForm.lng.value);
		var zoomlevel = escape(theForm.zoomlevel.value);
        requestUrl('GET','set_config=1&chan-apikey=' + apikey + '&chan-title=' + title + '&chan-link=' + link + '&chan-description=' + description + '&chan-lat=' + lat + '&chan-long=' + lng + '&chan-zoomlevel=' + zoomlevel);
    }
    
    
    function getCurrentView() {
        var theForm = document.forms["config"];
    	theForm.lat.value = map.getCenter().lat();
    	theForm.lng.value = map.getCenter().lng();
    	theForm.zoomlevel.value = map.getZoom();
	}
	
	
    function addMarker(point, htmlContent, icon) {
	    
	    marker.push(new GMarker(point, icon));
    	
    	var id = marker.length-1;
	    // Show this marker's index in the info window when it is clicked.
	    marker[id].html = '<div class="infowindow">' + htmlContent + '</div>';
	    
	    //GEvent.addListener(marker[id], 'mouseover', function() {
	    GEvent.addListener(marker[id], 'click', function() {
		    marker[id].openInfoWindowHtml(marker[id].html);
	    });
	    
	    map.addOverlay(marker[id]);
	    //window.setTimeout(plotPoint,timeOut);
	    return id;
    }
    
    
    function removeMarker(id) {
        
        var theForm = document.forms["newPoint-"+id];
        requestUrl('GET','remove=1&lat='+escape(theForm.lat.value)+'&long='+escape(theForm.lng.value));
        map.closeInfoWindow();
        map.removeOverlay(marker[id]);
        marker[id] = null;
    }
    
    
    
    
    function requestUrl(method, url) {
		var request = GXmlHttp.create();
		request.open(method, 'plot.php?'+url, true);
	    request.onreadystatechange = function() {if (request.readyState == 4) {}};
	    request.send(null);
	}
	
    
    function saveForm(id, showMessaage) {
	    
		var theForm = document.forms["newPoint-"+id];
		
	  //var title = escape(theForm.title.value.replace('&','&amp;'));
	  var title = escape(theForm.title.value);
		var link = escape(theForm.link.value);
		var description = escape(theForm.description.value);
		var lat = escape(theForm.lat.value);
		var lng = escape(theForm.lng.value);
		var oldLat = marker[id].getPoint().lat();
		var oldLng = marker[id].getPoint().lng();
		
        if (!showMessaage || (title != '' && description != '' && lat != '' && lng != '')) {
			var url = "title=" + title + "&link=" + link + "&description=" + description + "&lat=" + lat + "&long=" + lng;
			if (lat != oldLat || lng != oldLng) { 
				url += "&old-lat=" + oldLat + "&old-long=" + oldLng;
				var point = new GLatLng(lat, lng);
				var html = marker[id].html;
				removeMarker(id);
				id = addMarker(point, html, iconSmall);
				marker[id].html = marker[id].html.replace(/newPoint-\d+/g, "newPoint-"+id).replace(/saveForm\(\d+/g, "saveForm("+id).replace(/removeMarker\(\d+/g, "removeMarker("+id);
			}
		    requestUrl("GET", url);
		    marker[id].html = genForm(id, theForm.title.value, theForm.link.value, theForm.description.value, theForm.lat.value, theForm.lng.value);
		    map.closeInfoWindow();
		}
		else {
			alert(alert_saveForm);
		}
    }
    
    
    function genForm(id, title, link, description, lat, lng) {
      if (navigator.userAgent.toLowerCase().indexOf("msie") >= 0) {
        var message = document.getElementById("content").innerHTML;
      	message = message.replace(/%title%/g, '"'+title+'"').replace(/%description%/g, description); // IE needs it to run correctly
      	message = message.replace(/%lat%/g, lat).replace(/%long%/g, lng);
      	message = message.replace(/%id%/g, id).replace(/%link%/g, '"'+link+'"');
      	return message;
      } else {
        var message = document.getElementById("content").innerHTML;
      	message = message.replace(/%title%/g, title).replace(/%description%/g, description);
      	message = message.replace(/%lat%/g, lat).replace(/%long%/g, lng);
      	message = message.replace(/%id%/g, id).replace(/%link%/g, link);
      	return message;
      }
    }
	
	
	
	
    function resizeMap() {

	    /* Again, IE and Firefox have different ways to get the window's height */
	    if (document.documentElement &&	document.documentElement.clientHeight) {
		    var winHeight = document.documentElement.clientHeight;
	    }
	    else if (window.self && self.innerHeight) {
		    var winHeight = self.innerHeight;   // This is for Mozilla
	    }
    	
	    var e = document.getElementById("map");
	    var e2 = document.getElementById("sidebar");
	    var offset = e.offsetTop;
	    
	    var height = winHeight - offset - 70;
    	
	    e.style.height = height + "px";
	    e2.style.height = height + "px";
    }


    function listenToMouseWheel(e) {
      
      var wheelDelta;
      if (!e) { e = window.event; }
      
      if (e.wheelDelta) {
        wheelDelta = e.wheelDelta;
      } else if (e.detail) {
        wheelDelta = e.detail*-1;
      }

      if (wheelDelta > 0) {
        map.zoomIn();
      } else {
        map.zoomOut();
      }
    }
    
    function listenToKeyDown(e) {
    
      var keycode = event.keyCode;
      switch (keycode) {
          case 38:    // Up
            map.zoomIn();
            break;
          case 40:    // Down
            map.zoomOut();
            break;  
      }
    }
    
    window.onload = function() {
      
      // mouse resize
      resizeMap();
      
      // add event listener for mouse wheel and keydown
      var element = document.getElementById("map");
      if (element.attachEvent) {
      	document.onmousewheel = listenToMouseWheel;
      } else {
      	element.addEventListener("DOMMouseScroll",listenToMouseWheel,false); // for Mozilla
        //element.addEventListener("onkeydown",listenToKeyDown,false);  // for Mozilla
      }
    }
