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

function xmlRequest(url, data, callback, id)
{
	xmlHttpReq = false; 
	if(window.XMLHttpRequest) { 
		try { 
			xmlHttpReq = new XMLHttpRequest(); 
		} catch(e) { 
			alert('bad: ' + e.Description);
			xmlHttpReq = false; 
		}
	} else if(window.ActiveXObject) { 
		try { 
			xmlHttpReq = new ActiveXObject("Msxml2.XMLHTTP"); 
		} catch(e) { 
			alert('bad1-1: ' + e.Description);
			try { 
				xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP"); 
			} catch(e) { 
				alert('bad1-2: ' + e.Description);
				xmlHttpReq = false; 
			} 
		} 
	}

	if (!xmlHttpReq) { alert('bad1'); return false; }

	var state = "0";
	try {

		xmlHttpReq.open('GET', url, true);
		state = "1";
		//xmlHttpReq.open('POST', url, true);
		//xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		xmlHttpReq.onreadystatechange = function() { 
		state = "2";
			if (xmlHttpReq.readyState == 4) {
				state = "3"; 
        			//document.getElementById('debug').innerHTML = xmlHttpReq.responseText;
				switch (xmlHttpReq.status) { 
					// TODO: handle other status values, error checking, etc
					case 200:
						state = "4"; 
						
						// Call the desired callback function 
						eval(callback + '(id, xmlHttpReq.responseXML);');
						state = "5"; 
						break; 
					default: 
						state = "6";
						eval(callback + '(id, "");');  // hack this for now and have the callback handle an empty return
						state = "7";
						break; 
				} 
			} 
		}
		state = "8"; 
		xmlHttpReq.send(data);
		state = "9";

		//
		
		return true;
	} catch (e) {
		alert('bad2: ' + e.Description + " state: " + state);
		return false;
	}
	
	
}

function displayTwitterResults(id, newsXML) {
	try
	{
		var content = document.getElementById('tweets');
		
    	var channel  = newsXML.getElementsByTagName('channel')[0];
    	var items    = channel.getElementsByTagName('item');
		
		var tweets = "";
		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 pubDate = item.getElementsByTagName('pubDate')[0].firstChild.nodeValue;
			
			tweets = tweets + '<a href="' + link + '" target="_blank" class="tweetlink">* ' + title + '</a><br><br>';
		}	
		
		content.innerHTML = tweets;
	} catch(e) { 
		status.innerHTML = "Failed to retrieve Twitter records!";
		status.innerHTML = e.description;
		showSectionStatus(id, "Failed to retrieve Twitter records!");
	}
}

function displayResults(id, newsXML)
{
	
        var status  = document.getElementById('status');
        //var status_hidden  = document.getElementById('status_hidden');
	try
	{
        	var channel  = newsXML.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('newsContent_' + 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 list_div = document.createElement("div");
					list_div.className = 'news';


				
					//var point = new GPoint(parseFloat(lng), parseFloat(lat));
					var point = new GLatLng(parseFloat(lat), parseFloat(lng));
					//alert(color);
					var marker = createMarker(point, color, link, title, desc);
					map.addOverlay(marker);
					mymarkers[news_id][index] = marker;
					
					
					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));
					title_link.innerHTML = title;
					
					list_div.appendChild(title_link);


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

			if (loc != '') {
						content.appendChild(list_div);
			}
			story_count++;
		}

		// parse the story update time out of the xml
		at_pos = m_status.indexOf(" At ");
		if (at_pos > 0)
		{
			var time = document.getElementById('newsTime_' + news_id);
			update_time = "updated at " + m_status.substring(at_pos+4);
			time.innerHTML = update_time;
		}

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

		//status.innerHTML = m_status;

	} catch(e) { 
		//status.innerHTML = e;
		status.innerHTML = "Failed to retrieve news stories!";
		status.innerHTML = e.description;
		showSectionStatus(id, "Failed to retrieve news stories!");
	}
	
	//loadTwitter();
}

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 = "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\">Read More &#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(defaultSection) 
{
	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(defaultSection);
		
		
	} 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 centerLat = 37.0625;//var centerLat = 48.106236;
	var centerLng = -95.677068;//var centerLng = 105.029297;
	
	
//http://maps.google.com/maps?f=q&source=s_q&hl=ru&q=&vps=2&jsv=160h&sll=37.0625,-95.677068&sspn=48.106236,105.029297&ie=UTF8&geocode=FViuIAId4aYQAw&split=0	
	var zoomLevel = 11;
	//http://maps.google.com/maps?f=q&source=s_q&hl=ru&geocode=&q=tehran+iran&sll=37.0625,-95.677068&sspn=48.106236,105.029297&ie=UTF8&z=10
	//map.centerAndZoom(new GPoint(centerLng, centerLat), zoomLevel);
	//map.setCenter(new GLatLng(centerLat, centerLng), zoomLevel);
	
	map.setCenter(new GLatLng(35.696216, 51.422945), zoomLevel);
	map.setMapType(G_HYBRID_MAP);
	//http://maps.google.com/maps?f=q&source=s_q&hl=ru&geocode=&q=athens+greece&sll=35.696216,51.422945&sspn=0.776231,1.641083&ie=UTF8&z=12&iwloc=A
}

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

function showSectionStatus(id, status)
{
	var content = document.getElementById('newsContent_' + 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 url = 'http://www.iranmapnews.com/getdata.php?section='+id+'&zz=' + Math.random();	
	//var url = 'http://www.iranmapnews.com/xml/'+id+'.xml?zz=' + Math.random();
	//var url = '/xml/'+id+'.xml?zz=' + Math.random();
	
	if (!xmlRequest(url, '', 'displayResults', id)) {
		showSectionStatus(id, 'Sorry, I failed to get the news stories.');
	}
	
	
		
	
	
	
}

function loadTwitter() {
	//var url = 'http://twitter.com/statuses/user_timeline/47455158.rss';
	var url = 'http://www.iranmapnews.com/ver2/twit.php?' + 'zz=' + Math.random();
	if (!xmlRequest(url, '', 'displayTwitterResults', 0)) 
	{ 
		showSectionStatus(id, 'Sorry, I failed to get Twitter records.');
	}
	
}

function showNews(id)
{
	Element.show('newsContent_'+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('newsContent_'+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);
		}
	}
}
