var url = "/ajax/getCachesXML.php?param="; // The server-side script
var caches;
var cacheList = new Array();

function boldTerm(term,text) {
	sTerm = term.toUpperCase();
	sText = text.toUpperCase();
	var pos = sText.indexOf(sTerm);
	if (pos != -1) {
		return text.substr(0,pos)+"<b>"+text.substr(pos,term.length)+"</b>"+text.substr(pos+term.length)
	}
	else return text;
}

function handleHttpResponse() {
  if (http.readyState == 4) {
		var xmlDocument = http.responseXML;
		var root =		xmlDocument.getElementsByTagName("gccache")[0];

		var rcCode = 	xmlDocument.getElementsByTagName('rc')[0].firstChild.data;
		var resultCount = 	xmlDocument.getElementsByTagName('results')[0].firstChild.data;
		var search = 	xmlDocument.getElementsByTagName('search')[0].firstChild.data;

		var contents = document.getElementById("result-list");
		var searchText = document.getElementById("searchMessage");

		if (rcCode >= 0) {
			contents.innerHTML = "";
			//Loop Over Caches
			caches = root.getElementsByTagName("cache");
			for (var I = 0; I < caches.length; I++) {
				var gc = new geoCache(caches[I]);
				cacheList[gc.code] = I;
				//Extract Data From Node
				//li = document.createElement("li");
				sp1 = document.createElement("span");
				sp1.id = gc.code;
				sp1.onclick = doClick;
				arB = "";
				arE = "";
				if (gc.archived == "Y") {
					arB = "<s>";
					arE = "</s>";
				}
     		sp1.innerHTML = '<div align="right" style="cursor: pointer;background:#556950;font-size:10pt;color:#ffffff">'+boldTerm(search,gc.code)+'&nbsp;<img id="'+gc.code+'_div_head" src="/images/plus.gif" alt="Click Cache to see details"></div><div style="cursor:pointer;font-size:9pt;color:#0000ff">'+arB+boldTerm(search,gc.cacheName)+arE+'</div><b>by: </b>'+gc.placed_by;
     		contents.appendChild(sp1);
     		sp2 = document.createElement("span");
     		sp2.innerHTML += '<div style="display:none;background-color:#D3DCD1;width:150;border:1px solid #A2B59D;padding:1px;" id="'+gc.code+'_div"><div id="'+gc.code+'_text"></div></div><hr/>';
     		contents.appendChild(sp2);
     		//contents.appendChild(li);
			}
			if (rcCode == 1) {
				searchText.innerHTML = "Too Many matches for <b>"+search+"</b>. 150 shown.<hr>";
			} else {
				searchText.innerHTML = resultCount+" matches for <b>"+search+"</b><hr>";
			}

    } else {
     		searchText.innerHTML = "<b>"+search+"</b> Not Found";
     		res = document.getElementById("result-list");
				res.innerHTML = '';
    }
    isWorking = false;
  }
}

var isWorking = false;
var prevOpen = "";

function doClick() {
	var plus = '/images/plus.gif';
	var minus = '/images/minus.gif';
	var textTag = this.id+'_text';
	var divTag = this.id+'_div';
	var headTag = divTag+'_head';
	icImage = document.getElementById(headTag);
	icImage.src = (icImage.src.match(plus))?minus:plus;
	if (prevOpen != "" && prevOpen != divTag) {
		//alert('toggle old:'+prevOpen);
		Effect.toggle(prevOpen,'blind');
		var headPTag = prevOpen+'_head';
		icPImage = document.getElementById(headPTag);
		icPImage.src = (icPImage.src.match(plus))?minus:plus;
		//prevOpen = "";
	}
	var textTag = this.id+'_text';
	var divTag = this.id+'_div';
	var e = document.getElementById(textTag);
	c = new geoCache(caches[cacheList[this.id]]);
	e.innerHTML = formatInner(this.id, c);

	mapId = "map_"+this.id;
	//var opts = {size: new GSize(148,200)};
	//var map = new GMap2(document.getElementById(mapId), opts);
	//var xPoint = new GLatLng(c.lat, c.lon);
	//map.setCenter(xPoint,14);
	//var marker = new GMarker(xPoint);
	//map.addOverlay(marker);
	Effect.toggle(divTag,'blind',{afterFinish: showMap(c,mapId)});
	if (prevOpen == divTag) {
		 prevOpen = "";
	} else {
		prevOpen = divTag;
	}

	return false;
}

function showMap(c,mapId) {
	var opts = {size: new GSize(148,200)};
	var map = new GMap2(document.getElementById(mapId), opts);

	map.addControl(new GSmallMapControl());
	//map.addControl(new GMapTypeControl());

	var xPoint = new GLatLng(c.lat, c.lon);
	map.setCenter(xPoint,14);
	/*
	var icon = new GIcon();
	icon.image = "http://www.bcgeocaching.com/images/icons/cache_fg.png";
	icon.shadow = "http://www.bcgeocaching.com/images/icons/cache_sh.png";
	icon.iconSize = new GSize(28, 28);
	icon.shadowSize = new GSize(40, 28);
	icon.iconAnchor = new GPoint(6, 20);
	icon.infoWindowAnchor = new GPoint(5, 1);
	*/
	var marker = new GMarker(xPoint);

	//GEvent.addListener(marker, "click", function() {    marker.showMapBlowup("Geocache:<b>" + c.code + "</b>");  });

	map.addOverlay(marker);
}

function geoCache(cache) {
	//Extract Data From Node
	this.id = cache.getElementsByTagName("id")[0].firstChild.nodeValue;
	this.code = cache.getElementsByTagName("code")[0].firstChild.nodeValue;
	this.mailed = cache.getElementsByTagName("mailed")[0].firstChild.nodeValue;
	this.rating = cache.getElementsByTagName("rating")[0].firstChild.nodeValue;
	this.datelisted = cache.getElementsByTagName("datelisted")[0].firstChild.nodeValue;
	this.cacheName = cache.getElementsByTagName("name")[0].firstChild.nodeValue;
	this.location = cache.getElementsByTagName("location")[0].firstChild.nodeValue;
	this.lat = cache.getElementsByTagName("lat")[0].firstChild.nodeValue;
	this.lon = cache.getElementsByTagName("lon")[0].firstChild.nodeValue;
	this.type = cache.getElementsByTagName("type")[0].firstChild.nodeValue;

	this.terrain = cache.getElementsByTagName("terrain")[0].firstChild.nodeValue;
	this.difficulty = cache.getElementsByTagName("difficulty")[0].firstChild.nodeValue;
	this.owner = cache.getElementsByTagName("owner")[0].firstChild.nodeValue;
	this.placed_by = cache.getElementsByTagName("placed_by")[0].firstChild.nodeValue;
	this.archived = cache.getElementsByTagName("archived")[0].firstChild.nodeValue;
	this.available = cache.getElementsByTagName("available")[0].firstChild.nodeValue;
	this.container = cache.getElementsByTagName("container")[0].firstChild.nodeValue;
	if (this.lon != -9999 && this.lat != -9999) {
		//alert('getting map');
		this.gmX = cache.getElementsByTagName("gmX")[0].firstChild.nodeValue;
		this.gmY = cache.getElementsByTagName("gmY")[0].firstChild.nodeValue;
		this.gmZoom = cache.getElementsByTagName("gmZoom")[0].firstChild.nodeValue;
	}
}

function formatInner(id, c) {
	//c = new geoCache(caches[cacheList[id]]);
	content = '<b>Goto:</b> <a onclick="return true;" target="_new" href="http://www.geocaching.com/seek/cache_details.aspx?wp='+c.code+'">Cache Page</a>';
	arB = "";
	arE = "";
	if (c.archived == "Y") {
		arB = "<s>";
		arE = "</s>";
	}
	//content += '<br/>'+arB+c.cacheName+arE;
	//content += '<br/><b>By:</b> '+c.placed_by;
	content += '<br/><b>Terrain:</b> '+c.terrain;
	content += '<br/><b>Difficulty:</b> '+c.difficulty;
	if (c.container != "Unknown") {
		content += '<br/><b>Size:</b> '+c.container;
	}
  content += '<br/><b>Type:</b> '+c.type;
  //content += '<br/><b>Type:</b> '+c.type;
  if (c.lon != -9999 && c.lat != -9999) {
  	// with coords content += '<br/><b>Location:</b><br/><a target="_new" href="http://maps.google.com/maps?f=q&hl=en&q='+c.lat+'+'+c.lon+'">'+c.location+'</a>';
  	//content += '<br/><a target="_new" href="http://maps.google.com/maps?f=q&hl=en&q='+c.lat+'+'+c.lon+'"><img border="0" width="120" src="http://mt1.google.com/mt?v=w2.39&x='+c.gmX+'&y='+c.gmY+'&zoom='+c.gmZoom+'"></a>';
  	mapId = "map_"+id;
  	content += '<br/><div id="'+mapId+'" style="width: 148px; height: 200px"></div>';
  	//alert(mapId);
  }

	return content;
}

function updateGCData() {
	if (!isWorking && http) {
		prevOpen = "";
		var searchText = document.getElementById("searchMessage");
		searchText.innerHTML = "Searching Please Wait";
		res = document.getElementById("result-list");
		res.innerHTML = '<img width="120" height="12" src="/images/progress.gif">';
		var gcCode = 		document.getElementById("gc").value;
		var sUserId = document.getElementById("searchUser").value;
		http.open("GET", url + escape(gcCode)+ '&sId=' + escape(sUserId), true);
	  http.onreadystatechange = handleHttpResponse;
	  isWorking = true;
	  http.send(null);
	} //else  alert("Server is Not Responding "+isWorking);
}
function clearGCData() {
		prevOpen = "";
		var searchText = document.getElementById("searchMessage");
		searchText.innerHTML = "Enter Search Term Above";
		res = document.getElementById("result-list");
		res.innerHTML = '';
}
/*
 * Returns a new XMLHttpRequest object, or false if this browser
 * doesn't support it
 */
function getHTTPObject() {
  var xmlhttp;
  /*@cc_on
  @if (@_jscript_version >= 5)
    try {
      xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
      try {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (E) {
        xmlhttp = false;
      }
    }
  @else
  xmlhttp = false;
  @end @*/
  if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
    try {
      xmlhttp = new XMLHttpRequest();
    } catch (e) {
      xmlhttp = false;
    }
  }
  return xmlhttp;
}
var http = getHTTPObject(); // We create the HTTP Object

