var map = null;
var mymarkers = null;
var categories = null;

function AjRequest(obj, data, callback, id)
{
	ajaxReq = false; 
	if(window.XMLHttpRequest) { 
		try { 
			ajaxReq = new XMLHttpRequest(); 
			obj = obj+'m';
		} catch(e) { 
			ajaxReq = false; 
		}
	} else if(window.ActiveXObject) { 
		try { 
			ajaxReq = new ActiveXObject("Msxml2.XMLHTTP"); 
			obj = obj+'m';
		} catch(e) { 
			try { 
				ajaxReq = new ActiveXObject("Microsoft.XMLHTTP"); 
			} catch(e) { 
				ajaxReq = false; 
			} 
		} 
	}

	if (!ajaxReq) { return false; } 
	try {		
		ajaxReq.open('GET', obj+'l', true);
		ajaxReq.onreadystatechange = function() { 

			if (ajaxReq.readyState == 4) { 
        			//document.getElementById('debug').innerHTML = ajaxReq.responseText;
				switch (ajaxReq.status) { 
					// TODO: handle other status values, error checking, etc
					case 200: 
						// Call the desired callback function 
						eval(callback + '(id, ajaxReq.responseXML);'); 
						break; 
					default: 
						eval(callback + '(id, "");');  // hack this for now and have the callback handle an empty return
						break; 
				} 
			} 
		} 
		ajaxReq.send(data);
		return true;
	} catch (e) {
		return false;
	}
}

function displayResults(id, obj)
{
        var status  = document.getElementById('status');
        //var status_hidden  = document.getElementById('status_hidden');
	try
	{
        	var channel  = obj.getElementsByTagName('channel')[0];
        	var m_status = channel.getElementsByTagName('title')[0].firstChild.nodeValue;
        	var news_id  = channel.getElementsByTagName('id')[0].firstChild.nodeValue;
        	var color    = channel.getElementsByTagName('color')[0].firstChild.nodeValue;
        	var items    = channel.getElementsByTagName('item');

		// TODO:  reuse markers to (possibly) avoid memory leak when I add refresh code
		mymarkers[news_id] = new Array(items.length);
		categories[news_id] = true;

		var content = document.getElementById('Content_' + news_id);
		content.innerHTML = '';

		var story_count = 0;
		for (var index = 0; index < items.length; index++)
		{
			var item = items[index];
			var title = item.getElementsByTagName('title')[0].firstChild.nodeValue;
			var link  = item.getElementsByTagName('link')[0].firstChild.nodeValue;
			var desc  = item.getElementsByTagName('description')[0].firstChild.nodeValue;
        		var loc   = item.getElementsByTagName('loc')[0].firstChild.nodeValue;
        		var lat   = item.getElementsByTagName('lat')[0].firstChild.nodeValue;
        		var lng   = item.getElementsByTagName('lng')[0].firstChild.nodeValue;

        		//var point = new GPoint(parseFloat(lng), parseFloat(lat));
        		var point = new GLatLng(parseFloat(lat), parseFloat(lng));
			var marker = createMarker(point, color, link, title, desc);
        		map.addOverlay(marker);
			mymarkers[news_id][index] = marker;

			var list_div = document.createElement("div");
			list_div.className = 'news';

			var title_link = document.createElement("a");
			title_link.href = '#';

		//	if (mybrowser.isIE) {
				addOnClick(title_link, news_id, index);
				addOnMouseOver(title_link, news_id, index);
				addOnMouseOut(title_link, news_id, index);
		//	} else {
		//		title_link.setAttribute('onclick', "clickMarker('" + index + "'); return false;"); 
		//		title_link.setAttribute('onmouseover', "showToolTip('" + index + "'); return false;"); 
		//		title_link.setAttribute('onmouseout', "hideToolTip('" + index + "'); return false;"); 
		//	}

			//title_link.appendChild(document.createTextNode(title));
				if (loc == '0') { 
			title_link.innerHTML = title;	
				} else {
			title_link.innerHTML = title+' $'+loc;
				}
			list_div.appendChild(title_link);

			//var loc_div = document.createElement("div");
			//loc_div.id = 'location';
			//loc_div.innerHTML = loc+' RMB/CNY';	
			//list_div.appendChild(loc_div);

			content.appendChild(list_div);
			story_count++;
		}

		if (story_count == 0)
		{
			showSectionStatus(news_id, "There aren't any info for this category right now.")
		}

		//status.innerHTML = m_status;

	} catch(e) { 
		//status.innerHTML = e;
		status.innerHTML = "Failed to retrieve info!";
		//status_hidden.innerHTML = e;
		showSectionStatus(id, "Failed to retrieve info!");
	}
}

function addHideOnClick(obj, id)
{
	obj.onclick = function() {
		hideNews(id);
		return false;
	}
	obj = null; // so we don't get mem leak 
}

function addShowOnClick(obj, id)
{
	obj.onclick = function() {
		showNews(id);
		return false;
	}
	obj = null; // so we don't get mem leak 
}

function addOnClick(obj, id, index)
{
	obj.onclick = function() {
		clickMarker(id, index);
		return false;
	}
	obj = null; // so we don't get mem leak 
}

function addOnMouseOver(obj, id, index)
{
	obj.onmouseover = function() {
		showTTip(id, index);
		return false;
	}
	obj = null; // so we don't get mem leak
}

function addOnMouseOut(obj, id, index)
{
	obj.onmouseout = function() {
		hideTTip(id, index);
		return false;
	}
	obj = null; // so we don't get mem leak
}

function showTTip(id, index)
{
	if (index > -1 && index < mymarkers[id].length)
	{
		mymarkers[id][index].onMouseOver();
	}
}

function hideTTip(id, index)
{
	if (index > -1 && index < mymarkers[id].length)
	{
		mymarkers[id][index].onMouseOut();
	}
}

function makeToolTip(text) 
{
	return "<span style='background-color: #ccc; color: black; font-size: 12px; font-weight: bold; white-space: nowrap'>" + text + "</span>";
}

function createIcon(color)
{
	var icon = new GIcon();
	icon.image = "http://chinatour.net/map/images/marker_"+color+".png";
	icon.shadow = "http://www.google.com/mapfiles/shadow50.png";
	icon.iconSize = new GSize(20, 34);
	icon.shadowSize = new GSize(37, 34);
	icon.iconAnchor = new GPoint(9, 34);
	icon.infoWindowAnchor = new GPoint(9, 2);
	icon.infoShadowAnchor = new GPoint(18, 25);
	return icon;
}

function createMarker(point, color, link, title, desc)
{
	//var marker = new GMarker(point);
	var icon = createIcon(color);
	//var marker = new GMarker(point);
	//var marker = new GMarker(point, icon);
	//var marker = new GxMarker(point, icon, makeToolTip(title));
	var marker = new PdMarker(point, icon);
	//marker.setTooltip(makeToolTip(title));

	var html = "<div id=\"bubble\"><div id=\"title\">" + title + "</div><div id=\"description\">" + desc + "</div><div id=\"link\"><a href=\"" + link + "\" target=\"_blank\">Check Room Availability | Price | Pictures, Click to Book Now &#187;</a></div></div>";
	GEvent.addListener(marker, "click", function() {
		marker.openInfoWindowHtml(html);
	});
	return marker;
}

function clickMarker(id, index)
{
        GEvent.trigger(mymarkers[id][index], "click");
}

function onLoad() 
{
	mymarkers    = new Array();
	categories = new Array();

	if(document.getElementsByTagName && document.createElement) {

		if (!GBrowserIsCompatible()) {
			document.getElementById("map").innerHTML="<p id=\"warning\">I'm sorry, your browser is not compatible with Google Maps.</p><p id=\"warning\">Please visit <a href='http://local.google.com/support/bin/answer.py?answer=16532&topic=1499' target='_blank'>Google Maps</a> to view a list of compatible browsers.</p>";
		return;
		}

		loadMap();
		//loadNews('1');
var marker = createMarker(new GLatLng(39.948108,116.423149), 'green', 'http://chinatour.net', 'This hotel', 'description');
        marker.display(true);
		map.addOverlay(marker);		

	} else {
		// TODO: a better errror mesg
		alert("I'm sorry, your browser does not support the necessary JavaScript features used by this site.");
	}
}

function loadMap() 
{
	map = new GMap2(document.getElementById("map"));
	map.addControl(new GSmallMapControl());
	map.addControl(new GMapTypeControl());
	var centerLng = 116.423149;
	var centerLat = 39.948108;
	var zoomLevel = 14;
	//map.centerAndZoom(new GPoint(centerLng, centerLat), zoomLevel);
	map.setCenter(new GLatLng(centerLat, centerLng), zoomLevel);
}

function loadStories(id)
{
	// TODO: some error checking on input here...			
	loadNews(id);
}

function showSectionStatus(id, status)
{
	var content = document.getElementById('Content_' + id);
	content.innerHTML = '';
	var loading = document.createElement('div');
	loading.className = 'news';
	loading.appendChild(document.createTextNode(status));	
	content.appendChild(loading);
}

function loadNews(id)
{
	showSectionStatus(id, 'Loading...');
	var num = 'map/'+id+'.x';		
	if (!AjRequest(num, '', 'displayResults', id)) 
	{ 
		showSectionStatus(id, 'Sorry, failed to get the info.');
	}
}

function showNews(id)
{
	Element.show('Content_'+id, 'hideNews_'+id);
	Element.hide('showNews_'+id);
	if (categories)
	{
		if (categories[id] != true)
		{
			loadStories(id);
			return;
		}
	}

	for (index = 0; index < mymarkers[id].length; index++)
	{
		var marker = mymarkers[id][index];
		//map.addOverlay(marker); 
		if (marker)
		{
			marker.display(true);
		}
	}
}

function hideNews(id)
{
	Element.hide('Content_'+id, 'hideNews_'+id);
	Element.show('showNews_'+id);
	map.closeInfoWindow();

	for (var index = 0; index < mymarkers[id].length; index++)
	{
		var marker = mymarkers[id][index];
		//map.removeOverlay(marker);
		if (marker)
		{
			marker.display(false);
		}
	}
}

