var map;

var index = 0;
var point;

var deselectCurrent = function() {};

function initializeSortTab(type) {
    var listItem = document.createElement('li');
    var listItemLink = listItem.appendChild(document.createElement('a'));
    
    listItemLink.href = "#";
    listItemLink.innerHTML = type;
    listItemLink.onclick = function() {
        changeBodyClass('standby','loading');
        for (id in markers) {
            if (markers[id].type == type || 'All' == type) {
                markers[id].show();
            } else {
                markers[id].hide();
            }
        }
        
        changeBodyClass('loading','standby');
        return false;
    }
    document.getElementById('filters').appendChild(listItem);
}

function addMarker(longitude, latitude, description) {
	var marker = new GMarker(new GLatLng(latitude, longitude));

	GEvent.addListener(marker, 'click',
		function() {
			marker.openInfoWindowHtml(description);
		}
	);

	map.addOverlay(marker);
}

/*
function initializePoint(pointData) {
  var point = new GPoint(pointData.longitude, pointData.latitude);
  var marker = new GMarker(point);
  var listItem = document.createElement('li');
  var listItemLink = listItem.appendChild(document.createElement('a'));
  listItemLink.href = "#";
  listItemLink.innerHTML = '<strong>' + pointData.address + ' </strong><span>' +
      pointData.city + ', ' + pointData.state + ' (' + pointData.height + 'm)</span>';
  var focusPoint = function() {
    marker.openInfoWindowHtml(pointData.address);
    map.panTo(point);
    return false;
  }
  
  GEvent.addListener(marker, 'click', focusPoint);
  listItemLink.onclick = focusPoint;
  document.getElementById('sidebar-list').appendChild(listItem);
  map.addOverlay(marker);
}
*/

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 - 30;
	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 setAlertText(str) {
	document.getElementById('alert').innerHTML = '<p>' + str + '</p>';
}


function storeMarker(){
	var lng = document.getElementById("longitude").value;
	var lat = document.getElementById("latitude").value;

	var getVars =  "?api=" + api
	+ "&map=" + mapId
	+ "&location=" + encodeURIComponent(document.getElementById("location").value)
	+ "&desc=" + encodeURIComponent(document.getElementById("desc").value)
	+ "&icon=" + encodeURIComponent(document.getElementById("icon").value)
	+ "&lng=" + lng
	+ "&lat=" + lat ;

    
	var request = GXmlHttp.create();

	//open the request to storeMakres.php on your server
	request.open('GET', 'storeMarker.php' + getVars, true);
	request.onreadystatechange = function() {
		if (request.readyState == 4) {
			//the request in complete

			var xmlDoc = request.responseXML;

			//retrieve the root document element (response)
			var responseNode = xmlDoc.documentElement;

			//retrieve the type attribute of the node
			var type = responseNode.getAttribute("type");

			//retrieve the content of the responseNode
			var content = responseNode.firstChild.nodeValue;

			//check to see if it was an error or success
			if(type!='success') {
				alert(content);
			} else {
				//Create a new marker and add it's info window.
				var latlng = new GLatLng(parseFloat(lat),parseFloat(lng));
				var iconImage = responseNode.getAttribute("icon");
				var marker = createMarker(latlng, content, iconImage);

				map.addOverlay(marker);
				map.closeInfoWindow();
			}
		}
	}
	request.send(null);
	return false;
}

function createMarker(latlng, html, iconImage) {

    var visible = false;
    
  if (iconImage) {
    var icon = new GIcon();
    icon.image = iconImage;
    icon.iconSize = new GSize(25,25);
    icon.iconAnchor = new GPoint(14,25);
    icon.infoWindowAnchor = new GPoint(14,14);
    var marker = new GMarker(latlng, icon);    
  } else {
    var marker = new GMarker(latlng);
  }

					//allan, adding listItem
					var listItem = document.createElement('li');
					var listItemLink = listItem.appendChild(document.createElement('a'));
					listItemLink.href = "#";
					listItemLink.innerHTML = '<strong>'+'&nbsp;'+html+'</strong><br/>';
          
                    
          var focusPoint = function() {
            deselectCurrent();
            listItem.className = 'current';
            deselectCurrent = function() { listItem.className=''; }
            marker.openInfoWindowHtml(html);
            map.panTo(marker);
            return false;
          }
          
          GEvent.addListener(marker,'click', focusPoint);
          listItemLink.onclick = focusPoint;
          
          latlng.show = function() {
            if (!visible) {
                document.getElementById('sidebar-list').appendChild(listItem);
                map.addOverlay(marker);
                visible = true;
            }
          }
          
          latlng.hide = function() {
            if (visible) {
                document.getElementById('sidebar-list').removeChild(listItem);
                map.removeOverlay(marker);
                visible = false;
            }
          }
          
          latlng.show();
          //document.getElementById('sidebar-list').appendChild(listItem);
					//end of new code, 

/*  
  //var marker = new GMarker(latlng);
  GEvent.addListener(marker, 'click', function() {
    var markerHTML = html;
    marker.openInfoWindowHtml(markerHTML);
  });
*/  
  
  return marker;
  
					  
}

function retrieveMarkers() {
	var request = GXmlHttp.create();
	
	var getVars = "?api=" + api
	+ "&map=" + mapId;

	//tell the request where to retrieve data from.
	request.open('GET', 'retrieveMarkers.php' + getVars, true);

	//tell the request what to do when the state changes.
	request.onreadystatechange = function() {
		if (request.readyState == 4) {
			var xmlDoc = request.responseXML;

			var markers = xmlDoc.documentElement.getElementsByTagName("marker");

			for (var i = 0; i < markers.length; i++) {
				var lng = markers[i].getAttribute("lng");
				var lat = markers[i].getAttribute("lat");
				//check for lng and lat so MSIE does not error
				//on parseFloat of a null value
				if(lng && lat) {
					var latlng = new GLatLng(parseFloat(lat),parseFloat(lng));

					var html = '<div><b>地点</b> '
					+ markers[i].getAttribute("location")
					+ '</div><div><b>简介</b> '
					+ markers[i].getAttribute("desc")
					+ '</div>';

          var iconImage =  markers[i].getAttribute("icon");
					var marker = createMarker(latlng, html, iconImage);
					/*
					//allan, adding listItem
					var listItem = document.createElement('li');
					var listItemLink = listItem.appendChild(document.createElement('a'));
					listItemLink.href = "#";
					listItemLink.innerHTML = '<strong>'+i+'&nbsp;'+markers[i].getAttribute("location")+'</strong><br/><span>'+
            'lng=&nbsp;'+lng+',lat=&nbsp;'+lat+'</span>';
          
                    
          var focusPoint = function() {
            marker.openInfoWindowHtml(html);
            map.panTo(marker);
            return false;
          }
          
          GEvent.addListener(marker,'click', focusPoint);
          listItemLink.onclick = focusPoint;
          
          document.getElementById('sidebar-list').appendChild(listItem);
					//end of new code, 
					*/
					map.addOverlay(marker);
				}
			} //for

		} //if
	} //function

	request.send(null);
}

function init() {
var type;
var allTypes = {'All':[]};

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 GMap(document.getElementById("map"));
	map.addControl(new GLargeMapControl());
	map.addControl(new GMapTypeControl());
	map.addControl(new GOverviewMapControl(new GSize(150,150)));
	var location = new GLatLng(centerLatitude, centerLongitude);
	map.addMapType(G_PHYSICAL_MAP);
	map.setMapType(G_PHYSICAL_MAP);
	map.setCenter(location, startZoom);
	
	retrieveMarkers();
/*
	for(id in markers) {
		//addMarker(markers[id].longitude, markers[id].latitude, markers[id].name);
		initializePoint(markers[id]);
	}
*/

    for(type in allTypes)
    {
        initializeSortTab(type);
    }
  
  
    GEvent.addListener(map, "click", function(marker, point) {
      //map.addOverlay(new GMarker(point));
      var inputForm = document.createElement("form");
      inputForm.setAttribute("action","");
      inputForm.onsubmit = function() {storeMarker(); return false;};
      
      var lng = point.lng();
      var lat = point.lat();
      
      inputForm.innerHTML = '<fieldset style="width:150px;">'
            + '<legend>请填写兴趣点内容</legend>'
            + '<label for="location">地名</label>'
            + '<input type="text" id="location" style="width:100%;"/>'
            + '<label for="desc">简介</label>'
            + '<input type="text" id="desc" style="width:100%;"/>'
            + '<label for="icon">图标网址</label>'
            + '<input type="text" id="icon" style= "width:100%;">'
            + '<input type="submit" value="存储"/>'
            + '<input type="hidden" id="longitude" value="' + lng + '"/>'
            + '<input type="hidden" id="latitude" value="' + lat + '"/>'
            + '</fieldset>';
      
      map.openInfoWindow (point,inputForm);      
    });
    changeBodyClass('loading','standby');
	}
}


window.onresize = handleResize;

window.onload = init;

window.onunload = GUnload;
