//<script language="javascript">
//Copyright LearningBrook GmbH 2007
var thisbusmarker;	//the marker for the current business
var ishotspot;
var blntooltipcreated = false;
var blnnewmarker=false;
var newmarker;
var tooltipA = [];
var currentselectedlhs = -1;
//var configbusmarker = false;	//true, then just show this business marker
var onemarker = false;	//true, then just show this business marker
try{
	if (configbusmarker){onemarker = true;}
}catch(err){
	var configbusmarker = false;
}
try{
	if (document.getElementById("markerid").value > 0){
		onemarker = true;
	}
}catch(err){;}

var countrys = new Array();
var timer1;
var cidx = 0;
//alert ("blnmarkeraddon:"+blnmarkeraddon+" blnmarkerking:"+blnmarkerking);
var marker2sidebarhtml = new Array();	//for mapping marker indexes to sidebarhtml indexes ...
var markerbounds = null;
var showmarkertype = new Array();
var showalltypes = true;
var showallchains = true;
var markertotype = new Array();
var markertocert = new Array();
var markertostatus = new Array();
var showcertonly = false;
var ptyp = new Array(0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16);
var pname = new Array();
var typcnt = new Array();
var typlogo = new Array();
var oldzoom = null;
var label2marker = new Array();
var chainlabelcnt = new Array();
var batch = [];
var batchcountry = [];
var batchcity = [];
var batchcont = [];
var mgr = null;
//var tdesc = new Array();
//tdesc['en'] = new Array('', 'Airport','Car','Hotel','Pub','Water','Entertainment','Travel','Building','Cafe','Zone','Golf','Medical','Other','Gas','House','Restaurant');
//var userlang = 'en';
//alert(userlang);
var showgreen = true;
var showamber = true;
var showred = true;
//var showallstatus = true;
var zlevel = null;
var mySlide1 = null;
var mySlide2 = null;
var mySlide3 = null;
var mySlide4 = null;
var filterhtml = "";
var blnfiltershow = false;
var nowopenwindow = null;
/*
function eventHandler(e) {
    e = e || window.event;
    var target = e.srcElement || e.target;
	//alert(target.id)     ;
    if (target.id != 'map_legend_wrapper') return;
	filtershow(false);
}
*/

function eventHandler3(e) {
	filtershow(false);
	var thisdate = new Date();
	//$('sidebar_links').innerHTML = '3 - :'+thisdate.getTime()+':'+blnfiltershow;
	//$('sidebar_links').innerHTML = 'now0:'+mySlide4.now[0] + ' now1:'+mySlide4.now[1];
	return false;
}

function eventHandler2(e) {
    e = e || window.event;
    var target = e.srcElement || e.target;
	//alert(target.id)     ;

	var thisdate = new Date();
	//$('sidebar_links').innerHTML = thisdate.getTime()+':link:'+target.id+':'+blnfiltershow;
	//$('sidebar_links').innerHTML = 'now0:'+mySlide4.now[0] + ' now1:'+mySlide4.now[1];

    switch (target.id){
		case "wrapper":
		case "whitebox_tr":
		case "maincolumn":
    	case "map_legend_wrapper":
    	case "area":
    	case "whitebox":
    	case "map":
    	//case "":
    		filtershow(false);
		    //$('sidebar_links').innerHTML = $('sidebar_links').innerHTML + ' set FALSE';
    		break;
    	default:
	    	//alert(target.id);
    }
	return false;    
}

function filtershow(blnshow){
//	alert(blnfiltershow+":"+blnshow);

	try{	
		if (mySlide4.now[1] == 0){blnfiltershow = false;}
		if (mySlide4.now[0] == 0){blnfiltershow = true;}
	}catch(err){;}

	if (blnfiltershow != blnshow){
		//blnfiltershow = blnshow;
		if (blnshow){
			document.getElementById("map_legend_wrapper").className = "map_legend_wrapper";
			//dp = "block";
	//b		document.getElementById("map_legend_type").style.display = dp;
	//b		document.getElementById("map_legend_status").style.display = dp;
			$('map_legend_type').className = "map_legend_type";
			$('map_legend_type').setOpacity(0.85);
			$('map_legend_status').className = "map_legend_type";
			$('map_legend_status').setOpacity(0.85);
			try{
	//b			document.getElementById("map_legend_chain").style.display = dp;			
				$('map_legend_chain').className = "map_legend_chain";
				$('map_legend_chain').setOpacity(0.85);		
			}catch(err){;}
			try{	
				//mySlide1.slideIn();
				//mySlide2.slideIn();
				//mySlide3.slideIn();
				mySlide4.slideIn();
			}catch(err){;}
		}else{
			//$('map_legend_type').className = "map_legend_type_hidden";
			//$('map_legend_status').className = "map_legend_type_hidden";
			//try{
			//	$('map_legend_chain').className = "map_legend_chain_hidden";
			//}catch(err){;}
			
			//dp = "none";	
			//document.getElementById("map_legend_type").style.display = dp;
			//document.getElementById("map_legend_status").style.display = dp;
			//try{
			//	document.getElementById("map_legend_chain").style.display = dp;			
			//}catch(err){;}
			try{	
				//mySlide1.slideOut();
				//mySlide2.slideOut();
				//mySlide3.slideOut();
				mySlide4.slideOut();
			}catch(err){;}
		}
		blnfiltershow = blnshow;
	}else{
		if (!blnshow){
//alert("in here");
//			try{	
//				mySlide4.slideOut();
//			}catch(err){;}

			//$('map_legend').className = "map_legend_type_hidden";
			//dp = "none";	
			//document.getElementById("map_legend_wrapper").style.display = dp;
		}		
	}
}
function setfhs(){
	//bordercolors = "#99FF33";
	//document.getElementById("searchDiv").style.borderColor = bordercolors;
	//document.getElementById("map_legend").style.borderColor = bordercolors;
	//document.getElementById("logoDiv").innerHTML = '<img src="images/free-hotspot/logo.gif"></img>';
}

function getloccnt(xmlDoc){
	locitems = xmlDoc.getElementsByTagName("loc");
	for (var i in typcnt){
		typcnt[i] = 0;
	}
	for (var j = 0; j < locitems.length; j++) {
		var theid = locitems[j].getAttribute("id");
		var thecnt = locitems[j].getAttribute("cnt");
		var thelogo = locitems[j].getAttribute("l");
		var thename = locitems[j].getAttribute("n");
		typcnt[theid] = thecnt;
		typlogo[theid] = thelogo;
		ptyp[theid] = theid;
		pname[theid] = thename;
		sublocitems = locitems[j].getElementsByTagName("cnt");
		tmpary = new Array();
		for (var k = 0; k < sublocitems.length; k++) {
			var thelabel = sublocitems[k].getAttribute("n");
			var thecnt = sublocitems[k].getAttribute("no");
			//alert("sub ... thelabel:"+thelabel+" thecnt:"+thecnt);
			tmpary[label2marker[thelabel]] = thecnt;
			//alert("mapping:"+label2marker[thelabel]);
		}
		chainlabelcnt[theid] = tmpary;
	}
}

function getdownloadhtml(){
	var str = '<div class="downloadoptions">POI:&nbsp;';
	str += '<select name="downloadtype" id="downloadtype" class="downloadtype" size="1">';
	str += '<option value="0" >-- select format --</option>';
	str += '<option value="0" >KML</option>';
	str += '<option value="0" >CSV</option>';
	str += '<option value="0" >GPX</option>';
	str += '<option value="0" >ov2</option>';
	str += '</select>';
	str += '&nbsp;&nbsp;<input type="button" value="Download" class="downloadtype"></input>';
	str += '</div>';
	return str;
}
function setlhslinks(){
	try{
		//var str = '<div class="link1"><div style="text-align:center"><a target="_blank" href="index.php?option=com_local_clients&view=business&layout=setup&Itemid=16734"><input type="button" value="Join our Hotspot directory - for free" class="_downloadtype"></input></a></div></div>';
//a		var str = '<div class="link1"><div style="text-align:center"><a target="_self" href="index.php?option=com_local_clients&view=business&layout=newsetup&Itemid=16734">Join our Hotspot directory - for free</a></div></div>';
		
		//str    += '<div class="link2"><div style="text-align:center"><a target="_blank" href="http://www.free-hotspot.com/become_form.htm"><input type="image" src="images/free-hotspot/offers/btn_bec.gif" class="downloadtype"></input></a></div></div>';
//a		document.getElementById("sidebar_links").innerHTML = str;
	}catch(err){;}
}
function alignmaindivs(){
//alert("about to align");
	//	alert("left:"+document.getElementById("leftcolumn").style.width+":main:"+document.getElementById("maincolumn").style.width)
//alert(document.getElementById("leftcolumn").style.width);
	document.getElementById("leftcolumn").style.width='305px';
//alert(document.getElementById("leftcolumn").style.width);
	document.getElementById("maincolumn").style.marginLeft='310px';
	document.getElementById("leftcolumn").className = 'lhscolmapsearch';
	document.getElementById("maincolumn").className = 'maincolmapsearch';
	rbott = findPos(document.getElementById("miscDiv"));
	ltop = findPos(document.getElementById("google_maps_sidebar"))
	//htlinks = document.getElementById("sidebar_links").style.height;

//	htlinks = 60;
	htlinks = 5;

	//document.getElementById("google_maps_sidebar").style.height = (rbott[1] - ltop[1] - 5)+"px" ;//;
	//leght = document.getElementById("map_legend").style.height;
	//alert("leght:"+leght+"rbott:"+rbott+" ht:"+document.getElementById("google_maps_sidebar").style.height);
	document.getElementById("google_maps_sidebar").style.height = (rbott[1] - ltop[1] - 5 - htlinks)+"px" ;//;
	//alert("leght:"+leght+"rbott:"+rbott+" ht:"+document.getElementById("google_maps_sidebar").style.height);
	document.getElementById("map_legend").style.width = document.getElementById("map").style.width;
	
	//alert("ht:"+ $('map').style.height);
	
//	alert("1");
}
/*
function initoptions(){
	var chkstatus = "";

	if (showcertonly){chkstatus = "CHECKED";}
	//var str = '<div class="sidebar_marker_options"><input id="ck_certonly" onclick="applycertfilter()" type="checkbox" '+chkstatus+'></input></div>';
	//var str = '<input id="ck_certonly" onclick="applycertfilter()" type="checkbox" '+chkstatus+'></input>';
	var str = '<div class="certcheck"><input width="100%" id="ck_certonly" onclick="applycertfilter()" type="checkbox" '+chkstatus+'></input></div>';
	//	var str = '';

str += getdownloadhtml();

	document.getElementById("google_maps_search_options").innerHTML = str;
	document.getElementById("google_maps_search_options").className = "sidebar_marker_options";
	rbott = findPos(document.getElementById("miscDiv"));
	ltop = findPos(document.getElementById("google_maps_sidebar"))
	document.getElementById("google_maps_sidebar").style.height = (rbott[1] - ltop[1] - 5)+"px" ;//;
}
*/ 
function counttypes(){
	for (var i in typcnt){
		typcnt[i] = 0;
	}
	for(var i = 0; i < markers.length ; i++  ) {
		try{
			if (map.getBounds().contains(markers[i].getLatLng())){	//should be same index for markers and sidebar_htmls
				if (typcnt[markertotype[i]] > 0){
					typcnt[markertotype[i]]++;
				}else{
					typcnt[markertotype[i]] = 1;
				}
			}
		}catch(err){alert("in catch 11");	}
	}			
}

function initlegend(){	
	//var userlang = navigator.language ? navigator.language : navigator.userLanguage;
	//alert(userlang);
	//alert("in initlegend zoom:"+map.getZoom());
	try{
		if (map.getZoom() >= 10 ){
		//if (map.getZoom() >= 7 ){
			counttypes();
		}
	}catch(err){;}
	var chkstatus = "";
	if (showalltypes){
		chkstatus = "CHECKED";
	}
	var ex = '';
	var cl2 = 'leg_all';
	var str = '';

	if (map.getZoom() >= 10 ){
	//if (map.getZoom() >= 7 ){
		//str = '<div id="map_legend" class="map_legend" '+ex+' onmouseover="filtershow(true);" onmouseout="filtershow(false);">';
		//str = '<div id="map_legend" class="map_legend" '+ex+' onmouseover="filtershow(true);" onmouseout="filtershow(false);">';
		//str = '<div id="map_legend" class="map_legend" '+ex+' onmouseover="filtershow(true);" >';

		str = '<div id="map_legend" class="map_legend" '+ex+' >';
		//if (map.getZoom() >= 10 ){
		var ht=0;

		if (map.getZoom() >= 7 ){
			//str += '	<div id="map_legend_heading" class="map_legend_heading" onmouseover="filtershow(true);">';	
			//str += '		<div class="inline"><b>&nbsp;&nbsp;'+sfilters+' >> </b></div>';
			//str += '		<div id="selectedfilters" class="selectedfilters" ></div>';	
			//str += '		<div id="minilegend" class="minilegend" >';	
			//str += '			<div class="minilegend_green"></div><div class="minilegend_desc"><p class="minilegend_desc">'+son+'</p></div><div class="minilegend_red"></div><div class="minilegend_desc"><p class="minilegend_desc">'+soff+'</p></div><div class="minilegend_amber"></div><div class="minilegend_desc"><p class="minilegend_desc">'+sunknown+'</b></div>';
			//str += '		</div>'
			//str += '	</div>'

			str += '	<div id="map_legend_heading" class="map_legend_heading" onmouseover="filtershow(true);">';	
			str += '		<div class="inline"><b>&nbsp;&nbsp;'+sfilters+' >> </b></div>';
			str += '		<div id="selectedfilters" class="selectedfilters" ></div>';	
			str += '		<div id="minilegend" class="minilegend" >';	
			str += '			<div class="minilegend_green"></div><div class="minilegend_desc"><div class="minilegend_text">'+son+'</div></div><div class="minilegend_red"></div><div class="minilegend_desc"><div class="minilegend_text">'+soff+'</div></div><div class="minilegend_amber"></div><div class="minilegend_desc"><div class="minilegend_text">'+sunknown+'</div></div>';
			str += '		</div>';
			str += '	</div>';

		}
		//if (map.getZoom() >= 10 ){
		if (map.getZoom() >= 7 ){
			ht += 30;
			str += '	<div id="map_legend_wrapper" class="map_legend_wrapper_ns">';
			str += '		<div id="map_legend_type" class="map_legend_type_hidden" >';
			str += '			<div class="legname" >'+stype+':</div>';
			str += '			<div id="l_0" class="leg0" ></div>';
			str += '			<div id="l_all" class="'+cl2+'" ><input id="ck_l_all" onclick="applyfilter(-1)" type="checkbox" '+ chkstatus +' >All</input></div>';
			//alert("ptyp len:"+ptyp.length);	
			for (var t in ptyp){
				if (!isNaN(ptyp[t]) && ptyp[t] < 100 ){
					//alert("t:"+t+":ptyp[t]:"+ptyp[t]+":typcnt[ptyp[t]]:"+typcnt[ptyp[t]]);
					if (ptyp[t] != null && ptyp[t] != 0 && typcnt[ptyp[t]] > 0){		
						var ex = '';
						//alert(ptyp[t]);
						tt = ptyp[t];
						var cnt = "";
						if (typcnt[ptyp[t]] > 0){cnt = typcnt[ptyp[t]];}
						var chkstatus = "";						
						if (typeof(showmarkertype[ptyp[t]]) == "undefined"){
							setdefaultshow(ptyp[t],showalltypes);
						}
						if (!showalltypes && showmarkertype[ptyp[t]]){
							chkstatus = "CHECKED";
						}
						str += '	<div class="leg_chk"><input '+chkstatus+' id="ck_l_'+ptyp[t]+'" onclick="applyfilter('+ptyp[t]+')" type="checkbox"></input></div>';
						str += '	<span class="zoomTip" title="'+tdesc[userlang][tt] +'">';
						str += '		<div id="l_'+ptyp[t]+'" class="leg'+tt+'" '+ex+'><div class="loccnt" style="text-align:left">'+cnt+'</div></div>';
						str += '	</span>';
						//alert(str);
					}
					//alert(tdesc[userlang][0]);
				//}else{
				//	alert("t:"+t+":ptyp[t]:"+ptyp[t]+":typcnt[ptyp[t]]:"+typcnt[ptyp[t]]);
				}
			}
			str += '		</div>'
		}
		if (map.getZoom() >= 7 ){
			ht += 30;
			var chkstatus = "";
			var chkstatus1 = "";
			var showall = showgreen && showamber && showred; 
			if (showall){chkstatus1 = "CHECKED";}
			str += '		<div id="map_legend_status" class="map_legend_status_hidden">';	
			str += '			<div class="legname" >'+sstatus+':</div>';
			str += '			<div id="l_0" class="leg0" ></div>';
			str += '			<div id="l_all" class="'+cl2+'" ><input id="ck_l_all_status" onclick="applystatusfilter(-1)" type="checkbox" '+chkstatus1+' >All</input></div>';
			str += '			<div id="status_green" class="status_green">';
			if (!showall && showgreen){chkstatus = "CHECKED";}
			str += '				<span class="zoomTip" title="Hotspot '+sstatus+' = '+son+'"><div class="statuscheck"><input width="100%" id="ck_greenonly" onclick="applystatusfilter()" type="checkbox" '+chkstatus+'></input></div></span>';
			str += '			</div>'
			str += '			<div id="status_amber" class="status_amber">';
			chkstatus = "";
			if (!showall && showamber){chkstatus = "CHECKED";}
			str += '				<span class="zoomTip" title="Hotspot '+sstatus+' = '+sunknown+'"><div class="statuscheck"><input width="100%" id="ck_amberonly" onclick="applystatusfilter()" type="checkbox" '+chkstatus+'></input></div></span>';
			str += '			</div>'
			str += '			<div id="status_red" class="status_red">';
			chkstatus = "";
			if (!showall && showred){chkstatus = "CHECKED";}
			str += '				<span class="zoomTip" title="Hotspot '+sstatus+' = '+soff+'"><div class="statuscheck"><input width="100%" id="ck_redonly" onclick="applystatusfilter()" type="checkbox" '+chkstatus+'></input></div></span>';
			str += '			</div>'
			str += '		</div>'
		}

	
		/* keep for chains
		//if (map.getZoom() >= 10 ){
		if (map.getZoom() >= 7 ){
			if (showallchains){
				chkstatus = "CHECKED";
			}
			str1 = '		<div id="map_legend_chain" class="map_legend_chain_hidden" >';
			str1 += '			<div class="legname" >Chains:</div>';
			str1 += '			<div id="l_0" class="leg0" ></div>';
			str1 += '			<div id="l_all" class="'+cl2+'" ><input id="ck_l_all_chains" onclick="applyfilter(-1)" type="checkbox" '+chkstatus+' >All</input></div>';
			var blnshowchains = false;
			for (var t in ptyp){
				if (!isNaN(ptyp[t]) && ptyp[t] > 100 ){
					//alert("t:"+t+":ptyp[t]:"+ptyp[t]+":typcnt[ptyp[t]]:"+typcnt[ptyp[t]]);
					if (ptyp[t] != null && ptyp[t] != 0 && typcnt[ptyp[t]] > 0){		
						blnshowchains = true;
						var ex = '';
						//alert(ptyp[t]);
						if (map.getZoom() >= 10){
							tt = 1000;
						}else{
							tt = 10000;
						}				
						if (typlogo[ptyp[t]] != ""){
							ex = 'style="background-image:url('+typlogo[ptyp[t]]+')"';
						}
						var cnt = "";
						if (typcnt[ptyp[t]] > 0){cnt = typcnt[ptyp[t]];}
						var chkstatus = "";
						if (showmarkertype[ptyp[t]]){
							chkstatus = "CHECKED";
						}
						str1 += '	<div class="leg_chk"><input '+chkstatus+' id="ck_l_'+ptyp[t]+'" onclick="applyfilter('+ptyp[t]+')" type="checkbox"></input></div>';
						str1 += '	<span class="zoomTip" title="'+pname[t] +'">';
						str1 += '		<div id="l_'+ptyp[t]+'" class="leg'+tt+'" '+ex+'><div class="loccnt" style="text-align:left">'+cnt+'</div></div>';
						str1 += '	</span>';
						//alert(str);
						//showmarkertype[ptyp[t]] = true;
					}
					//alert(tdesc[userlang][0]);
				}
			}
			str1 += '		</div>';
			if (blnshowchains){
				str += str1;
				ht += 30;
			}
		}
		*/
		if (map.getZoom() >= 7 ){
			str += '		</div>';
		}
		
		str += '</div>';
		if ( $('loadingDiv').style.display != "block") {
			$('legendheadingspaceDiv').style.display = "block";
		}
	}else{
		$('legendheadingspaceDiv').style.display = "none";		
	}	
//alert(str);
//str = "";
	document.getElementById("legendDiv").innerHTML = str;
	if ( typeof window.addEventListener != "undefined" ){
		//$('map_legend_wrapper').addEventListener('mouseout',eventHandler,false); 
		$('wrapper').addEventListener('mouseover',eventHandler2,false); 
		//$('map').addEventListener('mousemove',eventHandler2,false); 
		$('map').addEventListener('mousemove',eventHandler3,false); 
	}else if ( typeof window.attachEvent != "undefined" ){
		//$('map_legend_wrapper').attachEvent('onmouseout',eventHandler); 
		$('wrapper').attachEvent('onmouseover',eventHandler2); 
		//$('map').attachEvent('onmousemove',eventHandler2); 
		$('map').attachEvent('onmousemove',eventHandler3); 
	}


//a	mySlide1 = new Fx.Slide('map_legend_type', {duration: 500});		
//a	mySlide2 = new Fx.Slide('map_legend_status', {duration: 500});		
	try{
//a		mySlide3 = new Fx.Slide('map_legend_chain', {duration: 500});				
	}catch(err){;}
	mySlide4 = new Fx.Slide('map_legend_wrapper', {duration: 400});				

//alert ($('map_legend_type').style.height);
//$('map_legend-wrapper').style.height = ht +"px";
//alert ($('map_legend-wrapper').style.height);

	filtershow(false);
	alignmaindivs();
	updatefiltersumm()
}

function updatefiltersumm(){
	var filter = "";
	//alert(showgreen+":"+showamber+":"+showred);
	
	if (!(showgreen && showamber && showred) ){
		if (showgreen) {
			//filter += '<span class="zoomTip" title="Hotspot Status = On"><div class="minilegend_green"></div></span>';	
			filter += '<span class="zoomTip" title="Hotspot '+sstatus+' = '+son+'"><div class="minilegend_green"></div></span>';	
		}
		if (showamber) {
			filter += '<span class="zoomTip" title="Hotspot '+sstatus+' = '+sunknown+'"><div class="minilegend_amber"></div></span>';	
		}
		if (showred) {
			filter += '<span class="zoomTip" title="Hotspot '+sstatus+' = '+soff+'"><div class="minilegend_red"></div></span>';	
		}
	}
	try{
		$('selectedfilters').innerHTML = filter + filterhtml;	
	}catch(err){;}
}

function applystatusfilter(ckn){
	if (ckn == -1){
		document.getElementById("ck_l_all_status").checked = true;
		document.getElementById("ck_greenonly").checked = false;	
		document.getElementById("ck_amberonly").checked = false;	
		document.getElementById("ck_redonly").checked = false;	
	}else{
		showgreen = false;
		showamber = false;
		showred = false;
		if (document.getElementById("ck_greenonly").checked) {showgreen = true;	}
		if (document.getElementById("ck_amberonly").checked) {showamber = true;	}
		if (document.getElementById("ck_redonly").checked) {showred = true;	}
		showany = showgreen || showamber || showred;
		//showall = showgreen && showamber && showred;
		document.getElementById("ck_l_all_status").checked = !showany;
	}
	//if (showall || document.getElementById("ck_l_all_status").checked){
	if (document.getElementById("ck_l_all_status").checked){
		showgreen = true;
		showamber = true;
		showred = true;		
	}
	showsidebar(sidebar_num,null,null);
	showhidemarkers();		
	updatefiltersumm();	
}

function applycertfilter(){
	if (document.getElementById("ck_certonly").checked) {
		showcertonly = true;	
	}else{
		showcertonly = false;
	}
	//alert(showcertonly);
	showsidebar(sidebar_num,null,null);
	showhidemarkers();			
}

function setdefaultshow(typ,showalltypes){
	
	showmarkertype[typ] = showalltypes;
}

function applyfilter(ckn){
	//alert(document.getElementById("ck_l_"+typ).checked );
	if (ckn != -1){
		document.getElementById("ck_l_all").checked = false;
	}
	var cntchecked = 0;
	filterhtml = "";
	for (var t in ptyp){
		if (!isNaN(ptyp[t])){
			if (ptyp[t] > 0){
				if (ckn == -1){
					try{
						document.getElementById("ck_l_"+ptyp[t]).checked = false;
					}catch(err){;}
				}
				try{
					showmarkertype[ptyp[t]] = document.getElementById("ck_l_"+ptyp[t]).checked;
					if (document.getElementById("ck_l_"+ptyp[t]).checked){
						//filterhtml += ptyp[t] + ":";
						filterhtml += '<span class="zoomTip" title="'+tdesc[userlang][ptyp[t]] +'"><div class="leg'+ptyp[t]+'" style="background-position: 0 0px;"></div></span>';
						cntchecked ++;
					}
				}catch(err){;}
			}else{
				if (ckn == -1){
					showmarkertype[0] = true;
				}else{
					showmarkertype[0] = false;
				}
			}
		}
	}	
	//alert("2 typcnt[6]:"+typcnt[6]);
	if (cntchecked == 0){document.getElementById("ck_l_all").checked = true;}
	showalltypes = document.getElementById("ck_l_all").checked;
	//if (document.getElementById("ck_l_"+typ).checked) {
	//	showmarkertype[typ] = 1;
	//}else{
	//	showmarkertype[typ] = 0;		
	//}

	try{
		showallchains = document.getElementById("ck_l_all_chains").checked;
	}catch(err){;}

	showsidebar(sidebar_num,null,null);
	showhidemarkers();			
	updatefiltersumm();	
}
function showhidemarkers(){
	//alert("in showhide: len:"+markers.length+ " zoomlevel:"+map.getZoom());
	//alert ("marker count:"+mgr.getMarkerCount(map.getZoom() ) );
	markertoopen = -1;
	if (map.getZoom() >= 10){batch = [];}
	//if (map.getZoom() >= 1 && map.getZoom() <= 3){batchcont = [];}
	if (map.getZoom() >= 4 && map.getZoom() <= 6){batchcountry = [];}
	if (map.getZoom() >= 7 && map.getZoom() <= 9){batchcity = [];}
	for(var i = 0; i < markers.length ; i++  ) {
		try{
			if (map.getBounds().contains(markers[i].getLatLng())){	//should be same index for markers and sidebar_htmls
				if (map.getZoom() >= 10){
					//alert("showalltypes:"+showalltypes+": i:"+i+" markertotype[i]:"+markertotype[i]+" :showmarkertype[markertotype[i]]"+":"+ showmarkertype[markertotype[i]]  + " markertostatus[i]:"+markertostatus[i]);
					var blnshowstatus = false;
					if (markertostatus[i] == 0){if (showred){blnshowstatus = true;}	}
					if (markertostatus[i] == 1){if (showgreen){blnshowstatus = true;}	}
					if (markertostatus[i] == 2){if (showamber){blnshowstatus = true;}	}
					//if ((showalltypes || (!showalltypes && showmarkertype[markertotype[i]] != 0)) && (!showcertonly || ( showcertonly &&  markertocert[i] ))    ){
					if ((showalltypes || (!showalltypes && showmarkertype[markertotype[i]] != 0)) && blnshowstatus ){
						markers[i].show();			
						batch.push(markers[i]);
					}else{
						markers[i].hide();
					}					
					if (nowopenwindow){
						if (markers[i].getLatLng().lat() == nowopenwindow.lat() && markers[i].getLatLng().lng() == nowopenwindow.lng()){
							//alert ("found the marker");
							markertoopen = i;
							//a nowopenwindow = null;
						}
					}
				}else{
					//b var tmpcnt = 0;
					//b for (var t in chainlabelcnt){
					//b 	if (!isNaN(chainlabelcnt[t][i])){
					//b 		//alert("marker "+i+ " is an N    t:"+t + "  chainlabelcnt[t][i]:"+chainlabelcnt[t][i]);
					//b 		//alert("showmarkertype["+t+"]:"+showmarkertype[t]);
					//b 		if (showmarkertype[t]){
					//b 			tmpcnt += parseInt(chainlabelcnt[t][i]);
					//b 		}
					//b 	}
					//b }	
					//alert("i:"+i+":tmpcnt:"+tmpcnt);
					//b if (showalltypes || tmpcnt > 0 ){
						markers[i].show();
						if (map.getZoom() >= 1 && map.getZoom() <= 3){batchcont.push(markers[i]);}
						if (map.getZoom() >= 4 && map.getZoom() <= 6){batchcountry.push(markers[i]);}
						if (map.getZoom() >= 7 && map.getZoom() <= 9){batchcity.push(markers[i]);}
					//b }else{
					//b 	markers[i].hide();
					//b }
				}
			}
		}catch(err){alert("in catch 1");	}
	}
//alert ("marker count2 at this zoom: "+mgr.getMarkerCount(map.getZoom() ) );
	//mgr = new GMarkerManager(map);
	//mgr = new MarkerManager(map);
//alert("in here infowindow:"+map.getInfoWindow().isHidden() );
	try{
		mgr.clearMarkers();
		mgr.addMarkers(batchcont, 1,3);
		mgr.addMarkers(batchcountry, 4,6);
		mgr.addMarkers(batchcity, 7,9);
		mgr.addMarkers(batch, 10);
		mgr.refresh();
//alert(markertoopen);
		if (markertoopen > -1){
	       markers[markertoopen].openInfoWindowHtml(infoWindowsHtml[markertoopen]);			
		}
	}catch(err){;}
	
	updatefiltersumm();												
	
//alert ("marker count3 at this zoom: "+mgr.getMarkerCount(map.getZoom() ) );

	//alert("after refresh batch len:"+batch.length);
		
//alert("end showhide");
//				mgr.refresh();
//alert("after mgr refresh");
}
function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		do {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		} while (obj = obj.offsetParent);
	}
	return [curleft,curtop];
}

function showsidebar(num,place,direction){
	//alert("in showsidebar: num="+num + " place="+place+ " direction="+direction);
//alert(iphone);
if (iphone == false){

	var current_sidebar = "";
	var catset = 0;	
	var countloc = 0;
	var s;

//	if (map.getZoom() >= 10){
	if (map.getZoom() >= 7){
		for(var i = 0; i < markers.length ; i++  ) {
			try{
				if (map.getBounds().contains(markers[i].getLatLng())){	//should be same index for markers and sidebar_htmls
					//if (showmarkertype[markertotype[i]] != 0){
					//alert("i:"+i+":showcertonly:"+showcertonly+":markertocert:"+markertocert[i]);
					//if ((showmarkertype[markertotype[i]] != 0) && (!showcertonly || ( showcertonly &&  markertocert[i] ))    ){					
					//alert(i+":"+markertotype[i]+":"+showmarkertype[markertotype[i]]);
					if (map.getZoom() >= 10){
						var blnshowstatus = false;
						if (markertostatus[i] == 0){if (showred){blnshowstatus = true;}	}
						if (markertostatus[i] == 1){if (showgreen){blnshowstatus = true;}	}
						if (markertostatus[i] == 2){if (showamber){blnshowstatus = true;}	}
						//if (( showalltypes || (!showalltypes && showmarkertype[markertotype[i]] != 0)) && (!showcertonly || ( showcertonly && markertocert[i] ))    ){					
						if (( showalltypes || (!showalltypes && showmarkertype[markertotype[i]] != 0)) && blnshowstatus ){					
							//alert(i+":"+markertotype[i]+":"+showmarkertype[markertotype[i]]);
							//alert(i+":"+marker2sidebarhtml[i]+":"+sidebar_htmls[ marker2sidebarhtml[i] ]);
							current_sidebar += sidebar_htmls[ marker2sidebarhtml[i] ];
							countloc++;
							//sidebar_place = i;
							//if (typcnt[markertotype[i]] > 0){
							//	typcnt[markertotype[i]]++;
							//}else{
							//	typcnt[markertotype[i]] = 1;
							//}
							ptyp[markertotype[i]] = markertotype[i];
							//ptyp[ptyp.length] = markertotype[i];
							//alert("idx:"+markertotype[i]+":"+typcnt[markertotype[i]]);
						}
					}else{
						//b var tmpcnt = 0;
						//b for (var t in chainlabelcnt){
						//b 	if (!isNaN(chainlabelcnt[t][i])){
						//b 		//alert("marker "+i+ " is an N    t:"+t + "  chainlabelcnt[t][i]:"+chainlabelcnt[t][i]);
						//b 		//alert("showmarkertype["+t+"]:"+showmarkertype[t]);
						//b 		if (showmarkertype[t]){
						//b 			tmpcnt += parseInt(chainlabelcnt[t][i]);
						//b 		}
						//b 	}
						//b }	
						//alert("i:"+i+":tmpcnt:"+tmpcnt);
						//b if (showalltypes || tmpcnt > 0 ){						
							//current_sidebar += sidebar_htmls[ marker2sidebarhtml[i] ];
						//b 	if (!showalltypes){
						//b 		current_sidebar += sidebar_htmls[ marker2sidebarhtml[i] ].replace(/[0-9]+ Hotspots/,tmpcnt+' Hotspots');
						//b 	}else{
								current_sidebar += sidebar_htmls[ marker2sidebarhtml[i] ];						
						//b 	}
							countloc++;
							ptyp[markertotype[i]] = markertotype[i];
						//b }
					}
				}
			}catch(err){alert("in catch 1");	}
		}
	}
	//alert(ptyp.length);
	//if (countloc > 0){
	//	initoptions();
	//}
	document.getElementById("google_maps_sidebar").innerHTML = current_sidebar;
	alignmaindivs();

}

}

// Display the correct number of items in the sidebar.
// Also makes sure the "Next" and "Prev" links change the sidebar correctly.
function showItems(num, place) {

//alert ("num:"+num+":place:"+place+":htmls length:"+sidebar_htmls.length);
   current_sidebar = "<ul>";
   var num = parseInt(num);
   var catset = 0;
   for(var i = 0; i < num && i + place < sidebar_htmls.length; i++) {
       var j = i + place;
       current_sidebar += sidebar_htmls[j];
   }
   sidebar_place = parseInt(place);
   prevplace = sidebar_place - num;
   nextplace = sidebar_place + num;
   current_sidebar += '<br />';
   if(place > 0) {
       current_sidebar += "<a href=\"javascript:showItems(sidebar_num, prevplace)\">Previous</a>\n";
   }
   if(nextplace < sidebar_htmls.length) {
       current_sidebar += "<a href=\"javascript:showItems(sidebar_num, nextplace)\">Next</a>\n";
   }
   current_sidebar += "</ul>\n";
   document.getElementById("google_maps_sidebar").innerHTML = current_sidebar;
}

function centerzoom(lng,lat,zoom){
  try {
	//alert("centerzoom");  	
    map.closeInfoWindow();
    tooltipMouseout();
  } catch(err) {}
  map.setCenter(new GLatLng(lat,lng),zoom);
  currentselectedlhs = -1;
}

// This function picks up the click and opens the corresponding info window
function myclick(i,lng,lat) {
//alert("in myclick");
  try {
    map.closeInfoWindow();
    tooltipMouseout();
  } catch(err) {}
  map.setCenter(new GLatLng(lat,lng));
  if(!infoWindowsHtml[i]) {
     if(safariCompat == 1) {
          infoWindowsHtml[i] = infoHtml(infoWindows[i]);
     } else {
          //infoWindowsHtml[i] = xsltProcess(infoWindows[i], xmlHttp.responseXML);
          //infoWindowsHtml[i] = xsltProcess(infoWindows[i+1], xmlHttp.responseXML);	//JM note (i+1)
          //infoWindowsHtml[i] = xsltProcess(infoWindows[i+1], GXml.parse(xmlHttp.responseText) );	//responseXML not working on www server anymore !!!!
          infoWindowsHtml[i] = xsltProcess(infoWindows[i], GXml.parse(xmlHttp.responseText) );	//responseXML not working on www server anymore !!!!
     }
  }
  markers[i].openInfoWindowHtml(infoWindowsHtml[i]);
  if(tooltipShow != 0 ) tooltip.style.visibility="hidden";
//alert(currentselectedlhs);
  if (currentselectedlhs > -1){
	//document.getElementById("sb_"+currentselectedlhs).className = 'sidebar_marker';
    document.getElementById("sb_"+currentselectedlhs).className = 'sidebar_marker_element';
    //alert(document.getElementById("sb_"+currentselectedlhs).offsetTop);
  }
  //document.getElementById("sb_"+i).className = 'sidebar_marker_selected';
  document.getElementById("sb_"+i).className = 'sidebar_marker_element_selected';
  currentselectedlhs = i;
 }

function myclick_mouseover(i) {
//alert("in myclick_mouseover");
  try {
    map.closeInfoWindow();
    tooltipMouseout();
  } catch(err) {}
  if(!infoWindowsHtml[i]) {
     if(safariCompat == 1) {
          infoWindowsHtml[i] = infoHtml(infoWindows[i]);
     } else {
          //infoWindowsHtml[i] = xsltProcess(infoWindows[i], xmlHttp.responseXML);
          //infoWindowsHtml[i] = xsltProcess(infoWindows[i+1], xmlHttp.responseXML);	//JM note (i+1)
          //infoWindowsHtml[i] = xsltProcess(infoWindows[i+1], GXml.parse(xmlHttp.responseText) );	//responseXML not working on www server anymore !!!!
          infoWindowsHtml[i] = xsltProcess(infoWindows[i], GXml.parse(xmlHttp.responseText) );	//responseXML not working on www server anymore !!!!
     }
  }
  markers[i].openInfoWindowHtml(infoWindowsHtml[i]);
  if(tooltipShow != 0 ) tooltip.style.visibility="hidden";
 }

function lhs_mouseover(i){
	
    showTooltip(markers[i]);
	//if (currentselectedlhs > -1){
	//	try{
	//		document.getElementById("sb_"+currentselectedlhs).className = 'sidebar_marker_element';
	//	}catch(err){;}
	//}
	if (currentselectedlhs != i){
		document.getElementById("sb_"+i).className = 'sidebar_marker_element_looking';
	}
//	currentselectedlhs = i;
//	var thepos = findPos(document.getElementById("sb_"+i));
//	var theposp = findPos(document.getElementById("google_maps_sidebar"));
//	document.getElementById("google_maps_sidebar").scrollTop = thepos[1]-theposp[1];
}

function lhs_mouseout(i){
//alert("in lhs_mouseout i:"+i)	;
	tooltip.style.visibility="hidden";
	document.getElementById("sb_"+i).className = 'sidebar_marker_element';
	
	if (currentselectedlhs > -1){
		try{
			if (currentselectedlhs == i){
				document.getElementById("sb_"+currentselectedlhs).className = 'sidebar_marker_element_selected';				
			}
	//		document.getElementById("sb_"+currentselectedlhs).className = 'sidebar_marker_element_selected';
	//		var thepos = findPos(document.getElementById("sb_"+currentselectedlhs));
	//		var theposp = findPos(document.getElementById("google_maps_sidebar"));
	//		document.getElementById("google_maps_sidebar").scrollTop = thepos[1]-theposp[1];
		}catch(err){;}
	}
}


function myclick_lhs(i) {
//alert("in myclick_lhs");
  try {
    map.closeInfoWindow();
    tooltipMouseout();
  } catch(err) {}
  if(!infoWindowsHtml[i]) {
     if(safariCompat == 1) {
          infoWindowsHtml[i] = infoHtml(infoWindows[i]);
     } else {
          //infoWindowsHtml[i] = xsltProcess(infoWindows[i], xmlHttp.responseXML);
          //infoWindowsHtml[i] = xsltProcess(infoWindows[i+1], xmlHttp.responseXML);	//JM note (i+1)
          //infoWindowsHtml[i] = xsltProcess(infoWindows[i+1], GXml.parse(xmlHttp.responseText) );	//responseXML not working on www server anymore !!!!
          infoWindowsHtml[i] = xsltProcess(infoWindows[i], GXml.parse(xmlHttp.responseText) );	//responseXML not working on www server anymore !!!!
     }
  }
  nowopenwindow = markers[i].getLatLng()

  markers[i].openInfoWindowHtml(infoWindowsHtml[i]);
  if (currentselectedlhs > -1){
    document.getElementById("sb_"+currentselectedlhs).className = 'sidebar_marker_element';
  }
  document.getElementById("sb_"+i).className = 'sidebar_marker_element_selected';
  currentselectedlhs = i;  
  if(tooltipShow != 0 ) tooltip.style.visibility="hidden";
 }

 
 //This function initializes the tooltips. Without it tooltips will not showup.
 function initTooltip(show) {
    if(show != 0) {
         tooltip = document.createElement("div");
         //tooltip.style.zIndex=-1000;
         tooltip.style.position = "relative";
         //tooltip.style.zIndex="2400000";
         //alert(tooltip.style.zIndex);         
	     //JM ... should be G_MAP_MARKER_PANE ... FLOAT_PLANE is used for info window ... and that is on top
	     //map.getPane(G_MAP_FLOAT_PANE).appendChild(tooltip);
	     map.getPane(G_MAP_MARKER_PANE).appendChild(tooltip);
         tooltip.style.visibility="hidden";
    }
 }
 
 function initTooltipA(show,markerid) {
    if(show != 0) {
		markerid = parseInt(markerid);
		tooltipA[markerid] = document.createElement("div");
	    //map.getPane(G_MAP_FLOAT_PANE).appendChild(tooltipA[markerid]);
	    map.getPane(G_MAP_MARKER_PANE).appendChild(tooltipA[markerid]);
        tooltipA[markerid].style.visibility="hidden";
        tooltipA[markerid].style.zIndex=-1000;
        //alert(tooltipA);
        //alert(tooltipA[markerid]);
    }
 }
  
 // The sidebar utilizes these functions to open/close tooltips when the mouse hovers over the sidebar link.
 function tooltipMouseover(i) {
  if(tooltipShow != 0 ) showTooltip(markers[i])
 } 
 function tooltipMouseout() {
  if(tooltipShow != 0 ) tooltip.style.visibility="hidden";
 }
 
 // This is the Safari compatibility function, that supposedly doesn't work.
 function infoHtml(info) {
    var name = GXml.value(info.getElementsByTagName("n")[0]);
    var address = GXml.value(info.getElementsByTagName("a")[0]);
    var city = GXml.value(info.getElementsByTagName("c")[0]);
    var state = GXml.value(info.getElementsByTagName("s")[0]);
    var zipcode = GXml.value(info.getElementsByTagName("z")[0]);
	var html = '<div class="infoWindow" ><b>' + name + '</b><br />' + address + '<br />' + city + ', ' + state + ' ' + zipcode + '<br /><br /></div>';
    return html;
 }
 
 // This function grabs the name of a category using the catid and then spits out the appropriate sidebar html.
 function getCatName(singleCat,allCats, prevCat) {
    catName = "";
	for (var i = 0; i < allCats.length; i++) {
        var catId = allCats[i].getAttribute("id");
        if(catId == singleCat && (catId != prevCat || sidebar_htmls.length % sidebar_num == 0) && sidebar_showcat != 0) {
           catName = allCats[i].getAttribute("name");
           var catTitle = "<div class=\"sidebar_category\"><u>" + catName + "</u></div>"
           return catTitle;
           break;
        }
    }
    return catName;
 }

 // This function creates the marker, the sidebar html, the event listeners, the tooltip, etc
 // It also puts the marker onto the map. It does it all.
 function createMarker(info, i) {
//alert(info);
    var localId = info.getAttribute("id");
    var localType = info.getAttribute("t");
    if (localType != 3 || cbRealname != 1) {
        var localName = info.getAttribute("n");        
		//alert("i:"+i+":localName:"+localName);
		label2marker[localName] = i;
        localName = localName.replace(/ /g,"&nbsp;");
        var localOffer = info.getAttribute("n");	//todo? why here with offer?
        var camp = info.getElementsByTagName("cam")[0];
		if (camp){
	        var localenddate = camp.getAttribute("de");	//todo ... what if multiple campaigns ... and why do we need to look here anyway ... doesn't XSL do everything?
		}else{
			var localenddate = "";
		}
    } else {
        var localName = info.getAttribute("username");
    }
    var localCatid = info.getAttribute("cat");
    var localDrag = info.getAttribute("d");

	//if (configbusmarker){
	if (onemarker){
		var localLat = document.getElementById('thelat').value;	//in case xml not updated yet
		var localLng = document.getElementById('thelng').value;				
	}else{
		var localLat = info.getAttribute("la");
		var localLng = info.getAttribute("ln");
	}
//alert("lat:"+localLat+" lng:"+localLng);
    var localTitle = getCatName(localCatid,xmlCats,prevcat);
	
	var ty = "";
	var ch = "";
	//alert(localCatid);
	if (localCatid != 38){	//no country
		var localaddress = info.getAttribute("a")+", "+info.getAttribute("c");
		ty = info.getAttribute("b");        
		ch = info.getAttribute("ch");        
		var ex = '';
		if (ty == ""){ty = 0;}
		var tyd = ty;
		//if (ty > 100){
		//	if (typlogo[ty] != ""){	ex = 'style="background-image:url('+typlogo[ty]+')"';}
		//	tyd = 1000;
		//}
		//if (ch > 100){
		if (ch > 60){
			//alert("ch:"+ch+ " typlogo:"+typlogo[ch]);
			if (typlogo[ch] != "" && typlogo[ch] != undefined){	ex = 'style="background-image:url('+typlogo[ch]+')"';}
			//tyd = 1000;
		}
		//alert(localName+":"+ty);
		var idx=2;
		if (localCatid==34||localCatid==41){
			idx = info.getAttribute("st");        		
		}
		if (localCatid==43){idx=2;}
		//alert(localCatid+":"+idx);
		if (localCatid == 44){
			idx=3;
			var cnt = info.getAttribute("no");        
			var cname = localName.toLowerCase();
			var dz = info.getAttribute("dz");        
			if (dz == null || dz == 0 || dz == '' ){dz = 13;	}
			sidebar_htmls.push('<div id="sb_'+i+'" class="sidebar_marker_element" onmouseover="lhs_mouseover('+i+')" onmouseout="lhs_mouseout('+i+')"><div id="sb_wf_'+i+'" class=""></div><div id="sb_b_'+i+'" class="sb_cntry_name"><a href="javascript:centerzoom('+localLng+','+localLat+','+dz+')" onmousedown="centerzoom('+localLng+','+localLat+','+dz+')"  >'+ localName + '</a></div><div class="sb_hs_cnt">' + cnt + ' Hotspots</div></div>');												
		} else if (localCatid == 45){
			var cnt = info.getAttribute("no");        
			var cname = localName.toLowerCase();
			var dz = info.getAttribute("dz");        
			if (dz == null || dz == 0 || dz == '' ){dz = 4;	}
			sidebar_htmls.push('<div id="sb_'+i+'" class="sidebar_marker_element" onmouseover="lhs_mouseover('+i+')" onmouseout="lhs_mouseout('+i+')"><div id="sb_wf_'+i+'" class=""></div><div id="sb_b_'+i+'" class="sb_cntry_name"><a href="javascript:centerzoom('+localLng+','+localLat+','+dz+')" onmousedown="centerzoom('+localLng+','+localLat+','+dz+')"  >'+ localName + '</a></div><div class="sb_hs_cnt">' + cnt + ' Hotspots</div></div>');												
		}else{
			if (idx == 0){ex1 = '<span class="zoomTip" title=" '+sstatus+' = '+soff+'">';}
			if (idx == 1){ex1 = '<span class="zoomTip" title="Hotspot '+sstatus+' = '+son+'">';}
			if (idx == 2){ex1 = '<span class="zoomTip" title=" '+sstatus+' = '+sunknown+'">';}
			//sidebar_htmls.push('<div id="sb_'+i+'" class="sidebar_marker_element" onmouseover="lhs_mouseover('+i+')" onmouseout="lhs_mouseout('+i+')"><div id="sb_wf_'+i+'" class="sidebar_marker_wf_element'+idx+'" ></div><div id="sb_b_'+i+'" class="sidebarmarkerbuselement_'+tyd+'" '+ex+'><a href="javascript:myclick('+i+',' + localLng + ',' + localLat +')" onmousedown="myclick_lhs('+i+')"  >'+ localName + '</a><br>'+localaddress+'</div></div>');				
			//sidebar_htmls.push('<div id="sb_'+i+'" class="sidebar_marker_element" onmouseover="lhs_mouseover('+i+')" onmouseout="lhs_mouseout('+i+')">'+ex1+'<div id="sb_wf_'+i+'" class="sidebar_marker_wf_element'+idx+'" ></div></span><span class="zoomTip" title="'+tdesc[userlang][tyd] +'"><div class="leg'+tyd+'"></div></span><div id="sb_b_'+i+'" class="sidebarmarkerbuselement_'+tyd+'" '+ex+'><a href="javascript:myclick('+i+',' + localLng + ',' + localLat +')" onmousedown="myclick_lhs('+i+')"  >'+ localName + '</a><br>'+localaddress+'</div></div>');							
			sbm =  '<div id="sb_'+i+'" class="sidebar_marker_element" onmouseover="lhs_mouseover('+i+')" onmouseout="lhs_mouseout('+i+')">'+ex1+'<div id="sb_wf_'+i+'" class="sidebar_marker_wf_element'+idx+'" ></div></span><span class="zoomTip" title="'+tdesc[userlang][tyd] +'">';
//alert(localName + ":" + tyd);
			if (ex != ''){
				sbm += '<div class="leg0" '+ex+'></div></span>';
			}else{
				sbm += '<div class="leg'+tyd+'"></div></span>';
			}
			//sbm += '<div class="leg'+tyd+'"></div></span><div id="sb_b_'+i+'" class="sidebarmarkerbuselement_'+tyd+'"><a href="javascript:myclick('+i+',' + localLng + ',' + localLat +')" onmousedown="myclick_lhs('+i+')"  >'+ localName + '</a><br>'+localaddress+'</div></div>';				
			sbm += '<div id="sb_b_'+i+'" class="sidebarmarkerbuselement_'+tyd+'"><a href="javascript:myclick('+i+',' + localLng + ',' + localLat +')" onmousedown="myclick_lhs('+i+')"  >'+ localName + '</a><br>'+localaddress+'</div></div>';				
			sidebar_htmls.push(sbm);
//alert('<div id="sb_'+i+'" class="sidebar_marker_element" onmouseover="lhs_mouseover('+i+')" onmouseout="lhs_mouseout('+i+')">'+ex1+'<div id="sb_wf_'+i+'" class="sidebar_marker_wf_element'+idx+'" ></div></span><span class="zoomTip" title="'+tdesc[userlang][tyd] +'"><div class="leg'+tyd+'"></div></span><div id="sb_b_'+i+'" class="sidebarmarkerbuselement_'+tyd+'" '+ex+'><a href="javascript:myclick('+i+',' + localLng + ',' + localLat +')" onmousedown="myclick_lhs('+i+')"  >'+ localName + '</a><br>'+localaddress+'</div></div>');
		}
		markertotype[i] = ty;
		markertocert[i] = true;
		markertostatus[i] = idx;
		if (idx == 2) {markertocert[i] = false;}
		//alert("set:"+i+":"+markertotype[i]);
	}
	
	if (localCatid == 38){ 
		var cnt = info.getAttribute("no");        
		var cname = localName.toLowerCase();
		cname = cname.replace(/&nbsp;/g,'');
		var ex1 = 'style="background-image:url(images/flags/'+cname+'_small.png)"';		
		var dz = info.getAttribute("dz");        
		if (dz == null || dz == 0 || dz == '' ){dz = 7;	}
		sidebar_htmls.push('<div id="sb_'+i+'" class="sidebar_marker_element" onmouseover="lhs_mouseover('+i+')" onmouseout="lhs_mouseout('+i+')"><div id="sb_wf_'+i+'" class="sb_country" '+ex1+'></div><div id="sb_b_'+i+'" class="sb_cntry_name"><a href="javascript:centerzoom('+localLng+','+localLat+','+dz+')" onmousedown="centerzoom('+localLng+','+localLat+','+dz+')"  >'+ localName + '</a></div><div class="sb_hs_cnt">' + cnt + ' Hotspots</div></div>');										
		markertocert[i] = true;
		showmarkertype[2000] = true;
	}

    var catIcon = parseInt(getCatIcon(localCatid));    
//alert("1:"+catIcon+" idx:"+idx);
	if (idx == 0){catIcon = 104;}
	if (idx == 2){catIcon = 103;}
	if (idx == 3){catIcon = 105;}
//alert("2:"+catIcon);
    var point = new GLatLng(parseFloat(localLat),parseFloat(localLng));
	var today = new Date;	
	var campaignactive = false;
	if ( (localenddate != "") && (localenddate) ){
		//alert("localenddate:"+localenddate);
		var firstIndex = localenddate.indexOf ("-");
		var lastIndex = localenddate.lastIndexOf ("-");
		year1 = localenddate.substring (0, firstIndex);
		//month1 = parseInt(localenddate.substring (firstIndex+1, lastIndex));
		month1 = localenddate.substring (firstIndex+1, lastIndex);
		date1 = localenddate.substring (lastIndex+1, localenddate.length);
		//alert(date1+":"+month1+":"+year1);
		var theenddate = new Date;
		theenddate.setDate(date1); 
		theenddate.setMonth(month1-1); 
		theenddate.setFullYear(year1); 
		//alert(today+":"+theenddate);
		if (theenddate > today){
			campaignactive = true;
		}
	}
	
	//alert(localenddate + ":" + campaignactive);	
	var blnshowmarker = false;
	if ( ( (!onemarker)&&(thisbusmarker==0)) || ((!onemarker)&&(localCatid==37)) || ( (onemarker)&&((thisbusmarker==localId)) )){
		blnshowmarker = true;
	}
	if (localCatid == 33){
		blnshowmarker = false;	//map center	
	} 
	
	if (blnshowmarker){
		//alert(localCatid);	
		if(localDrag == 1) {
			//JM
//alert("thisbusmarker:" + thisbusmarker+" : localId:"+localId);
			if ((configbusmarker)&&(thisbusmarker==localId)){	//can only move own marker //todo: admin config		
			    var marker = new GMarker(point,{icon:baseIcon[catIcon], draggable: true});
			    //var marker = new GMarker(point,{icon:baseIcon[1], draggable: true});
			}else{
				if (localCatid == 38){//country
					//var cntryname = GXml.value(info.getElementsByTagName("n")[0]);
					var cntryname = info.getAttribute("n");
					//alert(cntryname);
					//alert ('Icon name:'+cntryIcon[cntryname].image);
					var marker = new GMarker(point,{icon:cntryIcon[cntryname]});
					countrys[cidx] = marker;
					cidx = cidx+1;
					//alert("len:"+countrys.length+ " cidx:"+cidx);
				}else{
					//var marker = new GMarker(point,{icon:baseIcon[6]});			
					//var marker = new GMarker(point,{icon:baseIcon[1]});			
					var marker = new GMarker(point,{icon:baseIcon[catIcon]});			
					//alert(catIcon);
				}
			}		
		} else {
		    var marker = new GMarker(point,{icon:baseIcon[catIcon]});
		}		
		marker2sidebarhtml[markers.length] = sidebar_htmls.length-1;		
		//sidebarhtml2marker[sidebar_htmls.length-1] = markers.length;
		//this marker will be added to markers array ... so will have index of (markers.length)
		//we've already added sidebar html to sidebar_htmls array, so it has index (sidebar_htmls.length - 1)
		
	    //GEvent.addListener(marker,"dragstart",function(){
	    //	//alert(this);
	    //	try{
		//		//tooltipMouseout();
		//		;
		//	}catch(err){;}
	    //});

	    GEvent.addListener(marker,"dragend",function(){
	    	//alert(this);
	    	var point = this.getPoint();
	    	document.getElementById("thelat").value = point.y;
	    	document.getElementById("thelng").value = point.x;
	    	try{
	    		document.getElementById("lat_txt").innerHTML = point.y;
	    		document.getElementById("lng_txt").innerHTML = point.x;
			}catch(err){;}
	    	//and store the return URL we want to come back to (current URL)
	    	//document.getElementById("retmapurl").value = unescape(location.href);
	    	//and make the second step (the submit button) visible
	    	//document.getElementById("divsometimeshidden").style.visibility="visible";
	    });
	}
	
	if ( (configbusmarker && thisbusmarker == 0)  || ( !blnnewmarker && blnmarkerking && blnmarkeraddon ) ){
	    GEvent.addListener(map,"click",function(overlay,point){
	    	try{
	    		document.getElementById("thelat").value = point.y;
	    		document.getElementById("thelng").value = point.x;
	    		document.getElementById("lat_txt").innerHTML = point.y;
	    		document.getElementById("lng_txt").innerHTML = point.x;
			}catch(err){;}
	    	//if (thisbusmarker == 0){
	    	if ((configbusmarker) && (thisbusmarker == 0)){
	    		//adding a new marker for this business
			    var marker = new GMarker(point,{icon:baseIcon[catIcon], draggable: true});
			    map.addOverlay(marker);
			    marker.enableDragging();
			    GEvent.addListener(marker,"dragend",function(){
			    	var point = this.getPoint();
			    	document.getElementById("thelat").value = point.y;
			    	document.getElementById("thelng").value = point.x;
			    	document.getElementById("lat_txt").innerHTML = point.y;
			    	document.getElementById("lng_txt").innerHTML = point.x;
			    	//and store the return URL we want to come back to (current URL)
			    	//document.getElementById("retmapurl").value = unescape(location.href);
			    	//and make the second step (the submit button) visible
			    	//document.getElementById("divsometimeshidden").style.visibility="visible";
			    });
		        //business name
		        thisbusname = document.getElementById("companyname").value
		        marker.tooltip = '<div class="tooltip">'+thisbusname+'</div>';
				//if (!blntooltipcreated){
					//initTooltip(1);
					//initTooltipA(1,localId);
					
				//	blntooltipcreated = true;
				//}
				//showTooltip(marker);
				//showTooltipA(marker,localId);
		        GEvent.addListener(marker,"mouseover", function() {
		            showTooltip(markers[i]);
		        });        
			    thisbusmarker = -1;
	    	}else if ((!blnnewmarker)&&(blnmarkerking)&&(blnmarkeraddon)){
			    newmarker = new GMarker(point,{icon:baseIcon[catIcon], draggable: true});
			    map.addOverlay(newmarker);
			    newmarker.enableDragging();
			    GEvent.addListener(newmarker,"dragend",function(){
			    	var point = this.getPoint();
			    	document.getElementById("thelat").value = point.y;
			    	document.getElementById("thelng").value = point.x;
			    	//document.getElementById("lat_txt").innerHTML = point.y;
			    	//document.getElementById("lng_txt").innerHTML = point.x;
			    	//and store the return URL we want to come back to (current URL)
			    	//document.getElementById("retmapurl").value = unescape(location.href);
			    	//and make the second step (the submit button) visible
			    	//document.getElementById("divsometimeshidden").style.visibility="visible";
			    });
		        //business name
		        newmarker.tooltip = '<div class="tooltip">New Marker</div>';
				//if (!blntooltipcreated){
					initTooltip(1);
				//	blntooltipcreated = true;
				//}	
				showTooltip(newmarker);
		        GEvent.addListener(newmarker,"mouseover", function() {
			            showTooltip(newmarker);
		        });        
				GEvent.addListener(newmarker, "click", function() {
					openaddmarker(newmarker);
				});
			    blnnewmarker = true;
			}
	    	////and store the return URL we want to come back to (current URL)
	    	//document.getElementById("retmapurl").value = unescape(location.href);
	    	////and make the second step (the submit button) visible
	    	//document.getElementById("divsometimeshidden").style.visibility="visible";
	    });
	}
	 if (blnshowmarker){    
	    if(tooltipShow != 0 ) {
	        //marker.tooltip = '<div class="tooltip">'+localName+'</div>';
	        if (localCatid==34){//hotspot
			    marker.tooltip = '<div class="tooltip">'+localName+'</div>';
			    //marker.tooltip = '<div class="tooltip"><div style="width:40px; height:20px;background-color:orange" class="leg16">'+localName+'<div></div>';
			    //alert(marker.tooltip);
	        } else if (localId == thisbusmarker){
		        try{
		        	thisbusname = document.getElementById("companyname").value
			    	marker.tooltip = '<div class="tooltip">'+thisbusname+'</div>';
			    }catch(err){
			        marker.tooltip = '<div class="tooltip">'+localName+'</div>';	    
			    }
		    }else{
		        //marker.tooltip = '<div class="tooltip">'+localName+'</div>';	    
		        marker.tooltip = '<div class="tooltip">'+localOffer+'</div>';	    
			}
			//JM .. always show by default
			//if (!blntooltipcreated){
	//a 			initTooltip(1);
	//a1 don't
				initTooltipA(1,localId);
			//	blntooltipcreated = true;
			//}
			//showTooltip(marker);
	
	//don't show the tooltip unless it's mousedover
	// 		showTooltipA(marker,localId);
	
			//JM


	if (iphone == false){
	        GEvent.addListener(marker,"mouseover", function() {
				//alert("mouseover i:"+i);
	            filtershow(false);
				try{
	            	showTooltip(markers[i]);
				}catch(err){;}
				if (currentselectedlhs > -1){
					try{
						document.getElementById("sb_"+currentselectedlhs).className = 'sidebar_marker_element';
					}catch(err){;}
				}				
				try{
					document.getElementById("sb_"+i).className = 'sidebar_marker_element_selected';
					currentselectedlhs = i;
					//alert("offsetTop:"+document.getElementById("sb_"+i).offsetTop+":offsetParent:"+document.getElementById("sb_"+i).offsetParent);
					//alert(document.getElementById("google_maps_sidebar").scrollTop);
					var thepos = findPos(document.getElementById("sb_"+i));
					var theposp = findPos(document.getElementById("google_maps_sidebar"));
					//alert(thepos[1]+":"+theposp[1]);
					//alert("i:"+i+":offsetParent:"+document.getElementById("sb_"+i).offsetParent);
					//document.getElementById("google_maps_sidebar").scrollTop = document.getElementById("sb_"+i).offsetTop;
					document.getElementById("google_maps_sidebar").scrollTop = thepos[1]-theposp[1];
				}catch(err){;}

				//alert(document.getElementById("google_maps_sidebar").scrollTop);
	        });        
	
	        GEvent.addListener(map,"mouseover", function() {
				//alert("in map mouseover");
				filtershow(false);
	        });
    }

	//b        GEvent.addListener(marker,"mouseout", function() {
	//b             tooltip.style.visibility="hidden"
	//b        });

			if (localCatid == 38){ 
		        GEvent.addListener(marker,"click", function() {
					centerzoom(localLng,localLat,7); 
		        });
		        GEvent.addListener(marker,"dblclick", function() {
					centerzoom(localLng,localLat,7); 
		        });
			}
			if (localCatid == 44){ 
		        GEvent.addListener(marker,"click", function() {
					centerzoom(localLng,localLat,13); 
		        });
		        GEvent.addListener(marker,"dblclick", function() {
					centerzoom(localLng,localLat,13); 
		        });
			}
			if (map.getZoom() >=7 && map.getZoom() <= 9 ){
		        GEvent.addListener(marker,"dblclick", function() {
					centerzoom(localLng,localLat,13);
		        });
			}
	    }
	    
	    if(tooltipShow != 0 ) {
	        //marker.tooltip = '<div class="tooltip">'+localName+'</div>';
			if (localCatid == 38){//country
				//var cntryname = GXml.value(info.getElementsByTagName("n")[0]);
				var cntryname = info.getAttribute("n");
				var num = info.getAttribute("no");
		    	marker.tooltip = '<div class="tooltip">'+cntryname+ '<br>' + num + ' Hotspots</div>';
	        //} else if (localCatid==34){//hotspot
			} else if  (localCatid == 44){//city
				var cityname = info.getAttribute("n");
				var num = info.getAttribute("no");
		    	marker.tooltip = '<div class="tooltip">'+cityname+ '<br>' + num + ' Hotspots</div>';	        
			} else if  (localCatid == 45){//continent
				var cityname = info.getAttribute("n");
				var num = info.getAttribute("no");
		    	marker.tooltip = '<div class="tooltip">'+cityname+ '<br>' + num + ' Hotspots</div>';	        
	        } else if (localCatid==34 || localCatid==41){//hotspot
			    var catIcon = parseInt(getCatIcon(localCatid));
				var ex = '';
				var div2 = '';
				//if (ty == 1000){
				var typb = ty;
				if (ty > 100){
					//tyb = info.getAttribute("b");        		
					//if (typlogo[tyb] != ""){
					if (typlogo[ty] != ""){
						//ex = 'style="background-image:url('+typlogo[tyb]+')"';
						ex = 'style="background-image:url('+typlogo[ty]+')"';
						//div2 = '<div class="tt'+tyb+'"></div>';
						typb = 1000;
					//}else{
						//ty = typb;        		
					}
				}
				//marker.tooltip = '<div class="tooltip"><div class="tt'+ty+'" '+ex+'></div>'+div2+'<div>' +localName+'</div></div>';
				marker.tooltip = '<div class="tooltip"><div class="tt'+typb+'" '+ex+'></div>'+div2+'<div>' +localName+'</div></div>';
				//alert(marker.tooltip)			    ;
	        } else if (localId == thisbusmarker){
		        try{
		        	thisbusname = document.getElementById("companyname").value
			    	marker.tooltip = '<div class="tooltip">'+thisbusname+'</div>';
			    }catch(err){
			        marker.tooltip = '<div class="tooltip">'+localName+'</div>';	    
			    }
		    }else{
		        //marker.tooltip = '<div class="tooltip">'+localName+'</div>';	    
		        marker.tooltip = '<div class="tooltip">'+localOffer+'</div>';	    
			}
	
			//JM .. always show by default
			//if (!blntooltipcreated){
	//a 			initTooltip(1);
	//a1 don't
	//			initTooltipA(1,localId);
			//	blntooltipcreated = true;
			//}
			//showTooltip(marker);
	//		showTooltipA(marker,localId);
			//JM
	
	        //c GEvent.addListener(marker,"mouseover", function() {
	        //c      //showTooltip(markers[i]);
	        //c      showTooltip(marker);
	        //c });        
	        //c GEvent.addListener(marker,"mouseout", function() {
	        //c      tooltip.style.visibility="hidden"
	        //c });
	    }
	
		if (!configbusmarker){
		    GEvent.addListener(marker, "click", function() {
				//alert(i);
				if(safariCompat == 1) {
					infoWindowsHtml[i] = infoHtml(info);
				} else {
					//alert(xmlHttp.responseXML.xml);
					//alert(xmlHttp.responseText);
					//alert(GXml.parse(xmlHttp.responseText));
					//infoWindowsHtml[i] = xsltProcess(info, xmlHttp.responseXML);
					infoWindowsHtml[i] = xsltProcess(info, GXml.parse(xmlHttp.responseText) );	//responseXML not working on www server anymore !!!!
				}
				try{
					nowopenwindow = markers[i].getLatLng()
		       	}catch(err){;}
				marker.openInfoWindowHtml(infoWindowsHtml[i]);
				try{
					if (currentselectedlhs > -1){
						document.getElementById("sb_"+currentselectedlhs).className = 'sidebar_marker_element';
					}
					//document.getElementById("sb_"+(i-1)).className = 'sidebar_marker_selected';
					document.getElementById("sb_"+i).className = 'sidebar_marker_element_selected';
					//document.getElementById("google_maps_sidebar").scrollTop = document.getElementById("sb_"+i).offsetTop;
					var thepos = findPos(document.getElementById("sb_"+i));
					var theposp = findPos(document.getElementById("google_maps_sidebar"));
					document.getElementById("google_maps_sidebar").scrollTop = thepos[1]-theposp[1];
				}catch(err){;}
				//currentselectedlhs = i-1;
				currentselectedlhs = i;
		    });	
		}
	///JM ... use marker manager instead
	//    map.addOverlay(marker);
	//JM
	    if(localDrag == 1) marker.enableDragging();
	    prevcat = localCatid;
	 } 
    return marker;
 }

 // This shows the tooltip when the mouse hovers over a marker or a sidebar link.
 function showTooltip(marker) {
   	tooltip.innerHTML = marker.tooltip;
//   	alert(marker.tooltip);
	var point=map.getCurrentMapType().getProjection().fromLatLngToPixel(map.fromDivPixelToLatLng(new GPoint(0,0),true),map.getZoom());
	var offset=map.getCurrentMapType().getProjection().fromLatLngToPixel(marker.getPoint(),map.getZoom());
	var anchor=marker.getIcon().iconAnchor;
	var width=marker.getIcon().iconSize.width;
	var height=tooltip.clientHeight;
	var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(offset.x - point.x - anchor.x + (1.2*width), offset.y - point.y -anchor.y)); 
	pos.apply(tooltip);
	tooltip.style.visibility="visible";
    // Code From PdMarkers www.pixeldevelopment.com/pdmarker.asp
    var b = 75;
	var c = b / 100;
	if (tooltip)
	{
		if(typeof(tooltip.style.filter)=='string'){tooltip.style.filter='alpha(opacity:'+b+')';}
		if(typeof(tooltip.style.KHTMLOpacity)=='string'){tooltip.style.KHTMLOpacity=c;}
		if(typeof(tooltip.style.MozOpacity)=='string'){tooltip.style.MozOpacity=c;}
		if(typeof(tooltip.style.opacity)=='string'){tooltip.style.opacity=c;}
	}
	// end of PdMarkers code 
 }
 
 //JM seperate tootip DIV for each marker
 function showTooltipA(marker,markerid) {
	markerid=parseInt(markerid);
//alert(tooltipA[markerid]);
   	tooltipA[markerid].innerHTML = marker.tooltip;
//        alert("show"+tooltipA[markerid]);
//alert("show:"+marker.tooltip);

	var point=map.getCurrentMapType().getProjection().fromLatLngToPixel(map.fromDivPixelToLatLng(new GPoint(0,0),true),map.getZoom());
	var offset=map.getCurrentMapType().getProjection().fromLatLngToPixel(marker.getPoint(),map.getZoom());
	var anchor=marker.getIcon().iconAnchor;
	var width=marker.getIcon().iconSize.width;
	var height=tooltipA[markerid].clientHeight;
	var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(offset.x - point.x - anchor.x + (1.2*width), offset.y - point.y -anchor.y)); 
	pos.apply(tooltipA[markerid]);
	tooltipA[markerid].style.visibility="visible";
	//tooltipA[markerid].style.zIndex = -10000;
    // Code From PdMarkers www.pixeldevelopment.com/pdmarker.asp
    var b = 75;
	var c = b / 100;
	if (tooltipA[markerid])
	{
		if(typeof(tooltipA[markerid].style.filter)=='string'){tooltipA[markerid].style.filter='alpha(opacity:'+b+')';}
		if(typeof(tooltipA[markerid].style.KHTMLOpacity)=='string'){tooltipA[markerid].style.KHTMLOpacity=c;}
		if(typeof(tooltipA[markerid].style.MozOpacity)=='string'){tooltipA[markerid].style.MozOpacity=c;}
		if(typeof(tooltipA[markerid].style.opacity)=='string'){tooltipA[markerid].style.opacity=c;}
	}
	// end of PdMarkers code 
	//alert(tooltipA[markerid].style.zIndex);
 }
 
 
 // This function is used to place certain markers based on category id.
 function checkCat(catLookup,carray) {
    if(carray.length != 0) {
        for (i=0;i < carray.length;i++) {
            if(carray[i] == catLookup) {
                return true;
                break;
            }
        }
        return false;
    } else {
         return true;
    }
 }
 
 // This function is used to place certain markers based on marker id.
 function checkPoint(pointLookup,pointArray) {
    if(pointArray.length != 0) {
		for (i=0;i < pointArray.length;i++) {
			if(pointArray[i] == pointLookup) {
				return true;
				break;
			}
		}
		return false;
    } else {
		return true;
	}
 }
 
 // This function gets the gicon associated with each category
 function getCatIcon(singleCat) {
    for(var i=0; i < xmlCats.length; i++) {
        var catId = xmlCats[i].getAttribute("id");
        if(catId == singleCat) {
            if(xmlCats[i].getAttribute("gicon")) {
                var gicon = xmlCats[i].getAttribute("gicon");
                return gicon;
                break;
            }
        }
    }
    return 0;
 }
 
 //  This function to adjusts the positioning of the overview map (minimap)
 function positionOverview(x,y) {
     omap = document.getElementById("map_overview");
     //Place in a div container outside of the map
     var place=document.getElementById("overview_map_holder");
     omap.style.position = "relative";
     omap.style.left = "0px";
     omap.style.top = "0px";
     place.appendChild(omap);        

     // GControlPosition to place the overview map within the map.
     // Currently doesn't work in Internet Explorer
     //var pos = new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(0,0));
     //pos.apply(document.getElementById("map_overview"));
     //map.getContainer().appendChild(document.getElementById("map_overview"));
        
     // == restyling ==
     omap.firstChild.style.border = "1px solid gray";
     omap.firstChild.firstChild.style.left="4px";
     omap.firstChild.firstChild.style.top="4px";
     omap.firstChild.firstChild.style.width="190px";
     omap.firstChild.firstChild.style.heigh="190px";     
 }

/* Convert degress to radians */
function deg2rad(deg) {
  return deg / (180 / Math.PI);
}

/* Calculate distance between two points in meters 
   Where a and b are both Google Map GPoints
                                                    */
function point_distance(a, b) {
  var r = 6378700;
  var lat1 = a.y;
  var lat2 = b.y;
  var lon1 = a.x;
  var lon2 = b.x;
  var dist = r * Math.acos(Math.sin(deg2rad(lat1)) * Math.sin(deg2rad(lat2)) + 
			   Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * 
			   Math.cos(deg2rad(lon1 - lon2)));
  return dist;
}

/* Calculate the approximate distance to the edge of 
   the viewable map in miles. This assumes that the 
   viewable area is square-like in shape.            */


// Make the ymarkers variable universal so the removeMarkers function can access it.

function myclick2(i,lng,lat) {
	map.setCenter(new GLatLng(lat,lng));
    var html = xsltProcess(yahooInfo[i], xmlHttp.responseXML);
    ymarkers[i].openInfoWindowHtml(html);
}

 function createSearchMarker(point, info, i) {
    
    // Create a lettered icon for this point using our icon class from above
    var letter = String.fromCharCode("A".charCodeAt(0) + i);
    var icon = new GIcon(baseIcon[0]);
    icon.image = "http://www.google.com/mapfiles/marker" + letter + ".png";
    var searchTitle = info.getElementsByTagName("Title")[0].firstChild.nodeValue;
    var searchLat = info.getElementsByTagName("Latitude")[0].firstChild.nodeValue;
    var searchLng = info.getElementsByTagName("Longitude")[0].firstChild.nodeValue;
    search_html += '<li><a href="javascript:myclick2('+i+','+searchLng+','+searchLat+')">'+searchTitle+'</a></li>';
    var marker = new GMarker(point, icon);
 
     GEvent.addListener(marker, "click", function() {
       var html = xsltProcess(info, xmlHttp.responseXML);
       marker.openInfoWindowHtml(html);
     });
  return marker;
  
 }

 function removeMarkers(markerArray) {
   for (var j = 0; j < markerArray.length; j++) {
       map.removeOverlay(markerArray[j]);
   }
 }

 function localSearch(searchForm) {
  removeMarkers(ymarkers);
  var query = searchForm.query.value;
  var lat = map.getCenter().lat();
  var lng = map.getCenter().lng();
  var url = 'modules/mod_google_maps_search.xml.php?query=' + query + '&clat=' + lat + '&clng=' + lng;
  // Open the XML File
      var request = GXmlHttp.create();
	  request.open("GET", url, true);
	  request.onreadystatechange = function() {
  	   if (request.readyState == 4) {
              if (request.status != 200) {
                 alert("file not found");
                 return;
              }
    	   var xmlDoc = request.responseXML;
           if (!xmlDoc) {
              alert("Sorry there was an error with your search. Please try it again.");
           }
        yahooInfo = xmlDoc.getElementsByTagName("Result");
        search_html = "<ul>";
        search_html += "<div class=\"sidebar_category\"><u>Search Results</u></div>";
   		if (yahooInfo.length == 0) {
   		      search_html += "<li>No results</li>";
   		} else for (var j = 0; j < yahooInfo.length; j++) {
            var point = new GLatLng(parseFloat(yahooInfo[j].getElementsByTagName("Latitude")[0].firstChild.nodeValue),
                                    parseFloat(yahooInfo[j].getElementsByTagName("Longitude")[0].firstChild.nodeValue));
            ymarkers[j] = createSearchMarker(point,yahooInfo[j], j);
            map.addOverlay(ymarkers[j]);
    	}
        search_html += "</ul>";
        document.getElementById("google_maps_sidebar_search").innerHTML = search_html;
        }

      }
 request.send(null);
 }


 // var newmarkers = new Array();
 // This function creates the marker, the sidebar html, the event listeners, the tooltip, etc
 // It also puts the marker onto the map. It does it all.
 function createMarker2(info, i) {
    this.myclick3 = myclick3;
    this.info = info;
    this.i = i;
    this.id = info.getAttribute("id");
    this.type = info.getAttribute("type");
    if(this.type != 3 || cbRealname != 1) {
        // Makes sure markers aren't CB users with real names disabled.
        this.name = GXml.value(info.getElementsByTagName("name")[0]);
    } else {
        this.name = info.getAttribute("username");
    }
    this.catid = info.getAttribute("category");
    this.drag = info.getAttribute("draggable");
    this.lat = info.getAttribute("lat");
    this.lng = info.getAttribute("lng");
    this.point = new GLatLng(parseFloat(this.lat),parseFloat(this.lng));
    if(this.drag == 1) {
        this.marker = new GMarker(this.point,{icon:baseIcon[this.icon], draggable: true});
    } else {
        this.marker = new GMarker(this.point,{icon:baseIcon[this.caticon]});
    }
    
    if(tooltipShow != 0 ) {
        this.marker.tooltip = '<div class="tooltip">'+localName+'</div>';
        GEvent.addListener(this.marker,"mouseover", function() {
            showTooltip(markers[i]);
        });        
        GEvent.addListener(this.marker,"mouseout", function() {
            tooltip.style.visibility="hidden"
        });
    }
    GEvent.addListener(this.marker, "click", function() {
       if(safariCompat == 1) {
            this.infowindowhtml = infoHtml(info);
       } else {
            this.infowindowhtml = xsltProcess(info, xmlHttp.responseXML);
       }
       this.marker.openInfoWindowHtml(this.infowindowhtml);
    });
    prevcat = this.catid;

 }
 // This function gets the gicon associated with each category
 createMarker2.prototype.getCatIcon2 = function () {
    for(var i=0; i < xmlCats.length; i++) {
        var curentCat = xmlCats[i].getAttribute("id");
        if(currentCat == this.catid) {
            if(xmlCats[i].getAttribute("gicon")) {
                this.caticon = parseInt(xmlCats[i].getAttribute("gicon"));
                break;
            }
        }
    }
    this.caticon = 0;
 }
// Display the correct number of items in the sidebar.
// Also makes sure the "Next" and "Prev" links change the sidebar correctly.
function showItems2(num, place, markers) {
   current_sidebar = "<ul>";
   var num = parseInt(num);
   var catset = 0;
   for(var i=0; i < num && i + place < markers.length; i++) {
       var j = i + place;
       var sidebar_html_title = '';
       if(i == 0 || markers[j].catid != markers[j-1].catid) {
          sidebar_html_title = markers[j].catid;
       }
       var sidebar_html = sidebar_html_title + '<li class="sidebar_marker"><a href="javascript:newmarkers['+j+'].myclick3()" onmouseover="tooltipMouseover('+j+')" onmouseout="tooltipMouseout()">'+ markers[j].name + ' New Sidebar!</a></li>';
       current_sidebar += sidebar_html;
   }
   sidebar_place = parseInt(place);
   prevplace = sidebar_place - num;
   nextplace = sidebar_place + num;
   current_sidebar += '<br />';
   if(place > 0) {
       current_sidebar += "<a href=\"javascript:showItems2(sidebar_num, prevplace,newmarkers)\">Previous</a>\n";
   }
   if(nextplace < markers.length) {
       current_sidebar += "<a href=\"javascript:showItems2(sidebar_num, nextplace,newmarkers)\">Next</a>\n";
   }
   current_sidebar += "</ul>\n";
   document.getElementById("google_maps_sidebar").innerHTML = current_sidebar;
}
// This function picks up the click and opens the corresponding info window
 function myclick3() {
alert("in myclick3");
  var marker = this.marker;
  try {
    map.closeInfoWindow();
    tooltipMouseout();
  } catch(err) {}
  this.infowindowhtml = xsltProcess(this.info, xmlHttp.responseXML);
  map.setCenter(this.point);
  marker.openInfoWindowHtml(this.infowindowhtml);
 }


// createMarker2.prototype.overlay = function() {
//    map.addOverlay(this.marker);
//    if(this.drag == 1) this.marker.enableDragging();
// } 
 

 // This function downloads and processes an external XML file.
 // The function can handle markers and polylines.
 //
 // Markers are in the following format
 //<info type="1" lat="14.6" lng="25.12">
 // <name>Name</name>
 // <address>Address</address>
 // ...
 //</info>
 //
 // Polylines are in the following format
 //<info type="2">
 // <name>Name</name>
 // <misc>
 //  <point lat="14.6" lng="25.12"/>
 //  <point lat="18.9" lng="12.532"/>
 //  <point lat="20.2352" lng="22.535"/>
 //  <point lat="0.5432" lng="0.3461"/>
 // </misc>
 //</info>
function getXml(url,catsToDisplay, markersToDisplay, useSidebar) {
//1 try GDownloadUrl instead of GXmlHttp
//1    var request = GXmlHttp.create();
//1    request.open("GET", url, true);
//1    request.onreadystatechange = function() {
	if (window.opera){
		url = url  + "?" + new Date().valueOf() ;
	}
//alert("window.opera"+window.opera);
//alert("in getXml url="+url);
/*
	GDownloadUrl(url, function(data, responseCode) {
//1    alert("in on readystatechange() request.readyState="+request.readyState+" request.status="+request.status);
//alert("responseCode:"+responseCode);
//alert("responseCode:"+responseCode);
//		if (request.readyState == 4) {
		if (responseCode == 200) {
//alert("readyState == 4");
//1	        try {
//1	            var xmlDoc = request.responseXML;
//1	        } catch(err) {
//1	            var data = request.responseText;
//1	            var xmlDoc = GXml.parse(data);
//1	        }
            var xmlDoc = GXml.parse(data);
//        	fileloadedidx ++;
//	        if ( fileloadedidx < xmlUrl.length ){
//	        	alert(fileloadedidx);
//	        	getXml(xmlUrl[fileloadedidx], catDisplay, pointsArray, sidebar_exists);
//	        }else{
//	        	alert ("all done");
//	        }	        
	        //infoWindows = xmlDoc.getElementsByTagName("inf");
			//alert("# infoWindows:"+infoWindows.length);
	        xmlCats = xmlDoc.getElementsByTagName("category");
	        var catset = 0;
			var midx = 0;	//not every item will become a marker      
			var batch = [];
			var batchcountry = [];
			//JM if we're configuring this business' marker, then only show that marker
			thisbusmarker = 0;	//global
			//configbusmarker = false;	//global
			onemarker = false;	//global
			blngotit=false;
			try{
				if (url.search(/maps.xml/i) > 0){
					thisbusmarker = document.getElementById('markerid').value;
					//if (thisbusmarker > 0){	configbusmarker = true;	}
					if (thisbusmarker > 0){	onemarker = true;	}
					//alert("thisbusmarker:"+thisbusmarker);
					//markernode = xmlDoc.selectSingleNode("//inf[@id='"+thisbusmarker+"']");
					//markernode = selectSingleNode(xmlDoc,"//inf[@id='"+thisbusmarker+"']");
					//alert(markernode.getAttribute("n"));
					//alert("after");
					infoWindows = xmlDoc.selectNodes("//inf[@id='"+thisbusmarker+"']");
					blngotit=true;
					//alert(blngotit+":"+infoWindows.length);
					//alert("after 2");
				}
			}catch(err){;}	
			//if (!configbusmarker || !blngotit){
			if (!onemarker || !blngotit){
		        infoWindows = xmlDoc.getElementsByTagName("inf");
			}
			//alert(blngotit+":"+infoWindows.length);
			var currenttime = new Date();
			//var currentms = currenttime.getMilliseconds();
			var currentms = currenttime.getTime();
			for (var j = 0; j < infoWindows.length; j++) {
				// Grab variables about the type of marker.
				var pid = infoWindows[j].getAttribute("id");
				var ptype = infoWindows[j].getAttribute("t");
				var pcat = infoWindows[j].getAttribute("cat");
				//only try to display if we have a lat/lng
				//if (configbusmarker){
				if (onemarker){
					var thelat = document.getElementById('thelat').value;	//in case xml not updated yet
					var thelng = document.getElementById('thelng').value;				
				}else{
					var thelat = infoWindows[j].getAttribute("la");
					var thelng = infoWindows[j].getAttribute("ln");
				}
				var blnrendermarker = true;
				if (pcat == 33){blnrendermarker = false;}	//map center not rendered
				//if (configbusmarker && (thisbusmarker != pid)  ){blnrendermarker = false;}	//just showing one marker
				if (onemarker && (thisbusmarker != pid)  ){blnrendermarker = false;}	//just showing one marker	
				if ( (thelat != "") && (thelng != "") && blnrendermarker){
			       	if(checkCat(pcat,catsToDisplay) && checkCat(pid, markersToDisplay)) {
						// Checking to see if the info is for a polyline or a marker
						if( ptype == 2 ) {
							// Code for a polyline
							// get any line attributes
							var misc = infoWindows[j].getElementsByTagName("misc");
							var color = misc[0].getAttribute("polycolor");
							var width  = parseFloat(misc[0].getAttribute("polywidth"));
							// read each point on that line
							var points = infoWindows[j].getElementsByTagName("point");
							var pts = [];
							for (var i = 0; i < points.length; i++) {
								pts[i] = new GLatLng(parseFloat(points[i].getAttribute("lat")),
							                         parseFloat(points[i].getAttribute("lng")));
							}
							map.addOverlay(new GPolyline(pts,color,width));
						} else {
							// Code for a marker
							//var markerObj = new createMarker2(infoWindows[j],j);
							//newmarkers.push(markerObj);
							//markers[j] = createMarker(infoWindows[j],j);
							//markers[midx] = createMarker(infoWindows[j],j);

							var thismarker = createMarker(infoWindows[j],j);

							if (thismarker){
								markers[midx] = thismarker;
								//markers[midx] = createMarker(infoWindows[j],j);			           
								// This opens the info window if automatic open is set on.
								if(centerId == pid && autoOpen == 1) {
									if(safariCompat == 1) {
										var html = infoHtml(infoWindows[j]);
									} else {
										var html = xsltProcess(infoWindows[j], xmlHttp.responseXML);
									}
									//markers[j].openInfoWindowHtml(html);	       
									markers[midx].openInfoWindowHtml(html);
								}
								if (pcat == 38){
									batchcountry.push(markers[midx]);						
								}else{
									batch.push(markers[midx]);
								}				
								midx = midx + 1;					
							}
						}
					}
				}
			}
			currenttime = new Date();
			//var newms = currenttime.getMilliseconds();
			var newms = currenttime.getTime();
			//alert ("took:"+(newms - currentms)+ " ms");
			mgr = new GMarkerManager(map);
			mgr.addMarkers(batchcountry, 2,5);
			mgr.addMarkers(batch, 6);
			//add the markers to the manager
			mgr.refresh();
			//alert ("size:" + markers.length +  "   size batch:" + batch.length +  "   size batchcountry:" + batchcountry.length);        
			// Envokes the function to create the sidebar.
			if(useSidebar == 1) {
				try {
					//showItems(sidebar_num,sidebar_place);
					if (map.getZoom() > 6){
						//showsidebar(sidebar_num,sidebar_place);
						showsidebar(sidebar_num,sidebar_place,'forward');
					}
				} catch(err){}
			}
		   	fileloadedidx ++;
		   	//alert ("fileloadedidx:"+fileloadedidx+ " length:"+xmlUrl.length);
	        if ( fileloadedidx < xmlUrl.length ){
	        	//alert(fileloadedidx);
	        	if (fileloadedidx == 1){
	        		cidx=0;
	        		//startrotatinginfo();
	        		timer1 = setInterval("startrotatinginfo()",3000 );
	        	}
	        	getXml(xmlUrl[fileloadedidx], catDisplay, pointsArray, sidebar_exists);
				//if(useSidebar == 1) {
				//	try {
				//		showItems(sidebar_num,sidebar_place);
				//	} catch(err){}
				//}
	        }else{
	        	//alert ("all done");
	        }
		}

	});
*/	
	
	
//1	}
//1	request.send(null);
}

function startrotatinginfo(){
//alert (map.getZoom());
	if (map.getZoom() >= 4 && map.getZoom() <= 6){
		if (map.getBounds().contains(countrys[cidx].getLatLng())){			
			//todo if out of bounds, increment till we're in ... watch out for case where none are in... or becomes infinite loop
				showTooltip(countrys[cidx]);
			cidx = cidx + 1;
			if (cidx >= countrys.length){cidx=0;}
		}
	}else{
	
	}
}

 
 // This function opens/closes/changes the various map comtrols
 function mapOptions(type, scale, zoom) {
   // This shows or hides the map type buttons (normal, sat, hybrid).
   switch(type) {
	case 1:
		map.addControl(new GMapTypeControl());
		break;
	default:
		break;
   }
   // This switches the scale on or off.
   switch(scale) {
	case 1:
		map.addControl(new GScaleControl());
		break;
	default:
		break;
   }
   // This chooses which zoom/pan control to use. There are 3 
   // choices and the ability to hide the control all together
   switch(zoom) {
	case 1:
		//map.addControl(new GLargeMapControl());
		if ($('searchDiv')){
			var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(0,100));
		}else{
			var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(5,5));			
		}
		map.addControl(new GLargeMapControl(),pos);
		break;
	case 2:
		map.addControl(new GSmallMapControl());
		break;
	case 3:
		map.addControl(new GSmallZoomControl());
		break;
	default:
		break;
   }

 }

 // Grabs the current api version number 
 var APIkey = "";
 function getGoogleMapsVersion() {
	var i, a, b, c;
	var v = "unknown";

	if (document.getElementsByTagName)
		for(i=0; (a = document.getElementsByTagName("script")[i]); i++)
			if(a.getAttribute("src"))
			{
				b = a.getAttribute("src");
				c = b.indexOf("/mapfiles/maps");
				d = b.indexOf("http://maps.google.com/maps?file=api");
				e = b.indexOf("key=");
				if (c > 0)
					v = parseFloat(b.substring(c+14));
				if (d >= 0)
					if (e > 0)
						APIkey = b.substring(e+4);
			}
	return v;
 }
 
 // Enable a couple zoom options.
 function zoomOptions(continuous, doubleclick) {
    if(continuous == 1) {
        map.enableContinuousZoom();
    }
    if(doubleclick == 1) {
        map.enableDoubleClickZoom();
    }
 }
 
 // Controls the overview (mini) map
 function initOverview(show,width,height) {
       if(show != 0) {
             //  ======== Add a map overview ==========
             map.addControl(new GOverviewMapControl(new GSize(width,height)));
             if(show == 2) {
                  setTimeout("positionOverview(520,580)",1);
             } else if(show == 1) {
                  omap = document.getElementById("map_overview"); 
                  document.getElementById("map").appendChild(omap);
             }
       }
 }

/**
 *
 * This code is all by Nick Johnson. It is untested by me (David),
 * but people on the Google Maps API Group claim it works.
 * Below is a link the the thread where I got this code.
 * http://groups.google.com/group/Google-Maps-API/browse_frm/thread/c8d01f3be32bc26f/1398b29ca27d4da5?q=KML&rnum=1#1398b29ca27d4da5
 *
 * To use this code you are going to have to change the initMap function (or create your own).
 * If you are not comfortable with the Google Maps API, javascript, and programming in general
 * I wouldn't use this code. Do not ask me to do this for you. All that I know 
 * about this script is here. Below is what you should have in the initMap function in it's 
 * most basic form. Again, edit the initMap function AT YOUR OWN RISK.
 *
 * var map = new GMap(document.getElementById("map"));
 * map.addControl(new GSmallMapControl());
 * map.centerAndZoom(new GPoint(-122.1419, 37.4419), 4);
 * var khandler = new KMLHandler(map);
 * khandler.addFeed("test.kml");
 * Lastly, uncomment the KMLMarker.prototype = new GMarker(); line if you use this script.
 */
 
 function KMLMarker(point, name, description) {
    this.base = GMarker;
    this.base(point);

    this.name = name;
    this.description = description;

    this.onClick = function() {
        this.openInfoWindowHtml("<h1>" + this.name + "</h1>" + this.description);
    }

    GEvent.bind(this, 'click', this, this.onClick);
 }

// Uncomment the below line if you want to use KML.
// KMLMarker.prototype = new GMarker();

 function KMLNSResolver(prefix) {
    if(prefix == 'kml') return "http://earth.google.com/kml/2.0";
    return null;

 }

 //Represents a KML feed. Used internally by KMLHandler.
 function KMLFeed(map, url) {
    this.map = map;
    this.url = url;
    this.overlays = new Object();

    //Triggers whenever the map is moved or zoomed.
    //Also manually invoked when the feed is first created to initially populate
    //the feed.
    this.onMapChange = function() {
        //Trigger fetching the new map
        url = this.url;
        bounds = map.getBoundsLatLng();

        if(url.indexOf("?") == -1) {
            url = url + "?BBOX=" + bounds.minX + "," + bounds.minY +
"," + bounds.maxX + "," + bounds.maxY;
        } else {
            url = url + "&BBOX=" + bounds.minX + "," + bounds.minY +
"," + bounds.maxX + "," + bounds.maxY;
        }

        request = GXmlHttp.create();
        request.open('GET', url, true);
        request.onreadystatechange = function() {
            //Request completed?
            if(request.readyState == 4) {
                //Delete existing overlays
                for(var i in this.overlays) {
                    this.map.removeOverlay(this.overlays[i]);
                }
                this.overlays = new Object();

                //Populate with elements in the updated feed
                var doc = request.responseXML;

                placemarks = doc.documentElement.getElementsByTagName("Placemark");
                for(var i = 0; i < placemarks.length; i++) {
                    var point = placemarks[i].getElementsByTagName("Point")[0];
                    var coords = point.getElementsByTagName("coordinates")[0].childNodes[0].nodeValue;
                    coords = coords.split(",");
                    var name = placemarks[i].getElementsByTagName("name")[0].childNodes[0].nodeValue;
                    var description = placemarks[i].getElementsByTagName("description")[0].childNodes[0].nodeValue;

                    var point = new GPoint(parseFloat(coords[0]),parseFloat(coords[1]));
                    var marker = new KMLMarker(point, name,description);
                    map.addOverlay(marker);
                }

                //Free the request object
                request = undefined;
            }
        }

        request.send(null);
    }

    //Fetch the feed for the first time
    this.onMapChange();

    //Add event handlers
    GEvent.bind(map, 'moveend', this, this.onMapChange);
    GEvent.bind(map, 'zoom', this, this.onMapChange);

 }

 //A KMLHandler handles (fetching, updating) KML feeds for a map
 function KMLHandler(map) {
    this.map = map;
    this.feeds = [];

    this.addFeed = function(url) {
        //Add the feed to the feeds array
        this.feeds[url] = new KMLFeed(this.map, url);
    }

    this.removeFeed = function(url) {
        //Remove the feed from the feeds array
        this.feeds[url].destroy();
        delete this.feeds[url];
    } 
 }
 
 function initMap() {
//		alert("in initMap");
//		alert(getURLVar('address'));
//		alert(URLDecode(getURLVar('address')));

		// Checks to see if the browser is compatible with Google Maps API
		//alert("compatible:"+GBrowserIsCompatible());
		blncompat = true;
		try{
			blncompat = GBrowserIsCompatible();
		}catch(err){blncompat = false;}
		//blncompat = false;
		
		//if(GBrowserIsCompatible()) {
		if(blncompat) {
			if (!onemarker){
		  		try{
		  			//getloccnt();
					setfhs();
					initlegend();
		  			alignmaindivs();
		  		//}catch(err){alert("error1");}
		  		}catch(err){;}
		  		try{
		  			alignmaindivs();
		  		}catch(err){;}
			}
			//alert("browser is compatible");
			if (onemarker){	
				thelat = document.getElementById('thelat').value;	//in case xml not updated yet
				thelng = document.getElementById('thelng').value;				
				if (thelat != ''){centerLat = thelat;}
				if (thelng != ''){centerLng = thelng;}
			}
			i = 0;
			map = new GMap2(document.getElementById("map"));
			// Now to show all the various widgets on the map
			mapOptions(showType,showScale,whichZoom);

//alert("zoomLevel:"+zoomLevel);
			map.setCenter(new GLatLng(centerLat,centerLng),zoomLevel,whichType);   
			//JM added, now removed map.setMapType(G_HYBRID_MAP);
			zoomOptions(contZoom, doubleclickZoom);

/*
			try{
				//var sbheight = document.getElementById("map").offsetHeight;
				////alert (document.getElementById("map").offsetHeight+":"+document.getElementById("searchDiv").offsetHeight);
				//sbheight -= document.getElementById("searchDiv").offsetHeight;
				//sbheight -= 35;
				//document.getElementById("google_maps_sidebar").style.height = sbheight;
			}catch(err){;}
*/				
			try{
				thisbusmarker = document.getElementById('markerid').value;
				//alert("a thisbusmarker:"+thisbusmarker);
				//configbusmarker = true;
				onemarker = true;
			}catch(err){;}

			//alert(configbusmarker);
			//if (!configbusmarker){
			if (!onemarker){
				//Local Search tool
				//todo searchcontrol = new google.maps.LocalSearch();
				//todo map.addControl(searchcontrol);
				//this is used for lhs search module
				geocoder = new GClientGeocoder();
			}
			//alert("tooltipShow:"+ tooltipShow);
			initTooltip(tooltipShow);

			//	if (configbusmarker){
			//		try{
			//			thislat = document.getElementById('lat').value;
			//			thislng = document.getElementById('lng').value;
			//			alert(thislat + ":" + thislng);
			//			//configbusmarker = true;
			//		}catch(err){;}
			//	}else{
			// This gets the marker data and plots the points to the map
			//JM getXml(xmlUrl, catDisplay, pointsArray, sidebar_exists);
			//alert(xmlUrl[fileloadedidx]);
			if (!onemarker){
				//getXml(xmlUrl[fileloadedidx], catDisplay, pointsArray, sidebar_exists);
				//getareamarkers();
				mgr = new MarkerManager(map);				
			}else{
				thisbusmarker = document.getElementById('markerid').value;
				ishotspot = document.getElementById('ishotspot').value;
				thecatid = 34;
				st = 2;
				try{
					thecatid = document.getElementById('catid').value;
				}catch(err){;}
				try{
					st = document.getElementById('status').value;
				}catch(err){;}
				try{
					cn = document.getElementById('companyname').value;
					cn = cn.replace(/&/,'&amp;');	
					ca = document.getElementById('companystreet').value;
					cc = document.getElementById('companycity').value;
					cs = document.getElementById('companystate').value;
					co = document.getElementById('companycountry').value;
					cz = document.getElementById('companyzip').value;
					cp = document.getElementById('companyphone').value;
					ce = document.getElementById('companyemail').value;
					cw = document.getElementById('companywebsite').value;
					if (ishotspot && co == 'Romania'){
						map.setMapType(G_SATELLITE_TYPE);
					}
				}catch(err){;}
				var cat = 99;
				//if (ishotspot){cat = 34;}
				if (ishotspot){cat = thecatid;}
				var sxml = '';
				sxml = '<xml><category id="34" gicon="100" /><category id="41" gicon="4" />';
				sxml = sxml + '<inf id="'+thisbusmarker+'" la="'+centerLat+'" ln="'+centerLng+'" cat="' + cat + '" d="1" t="1" ';
				sxml = sxml + ' n="'+cn+'"' + ' a="'+ca+'"' + ' c="'+cc+'"' + ' s="'+cs+'"' + ' z="'+cz+'"' + ' co="'+co+'"' + ' p="'+cp+'"' + ' hp=""'  + ' st="'+st+'"';
//				sxml = sxml + '  ' + ' c="'+cc+'"' + ' s="'+cs+'"' + ' z="'+cz+'"' + ' co="'+co+'"' + ' p="'+cp+'"' + ' hp=""'  + ' st="'+st+'"';
				sxml = sxml + '>';
				try{
					sxml = sxml + document.getElementById('campaignsxml').value; 
				}catch(err){;}
				sxml = sxml + '</inf></xml>';
				//alert(sxml);
				var xmlDoc = GXml.parse(sxml);
				//markerinfo = xmlDoc.selectSingleNode("//inf[@id='"+thisbusmarker+"']");
				markerinfos = xmlDoc.selectNodes("//inf[@id='"+thisbusmarker+"']");
		        xmlCats = xmlDoc.getElementsByTagName("category");
				//var thismarker = createMarker(markerinfo,1);
				var thismarker = createMarker(markerinfos[0],1);
				//alert("markerinfo id:" + markerinfo.getAttribute("id") );
				var batch = [];
				batch.push(thismarker);
				//mgr = new GMarkerManager(map);				
				mgr = new MarkerManager(map);				
				//mgr.addMarkers(batch, 6);
				mgr.addMarkers(batch, 6);

//alert("markercount 6:"+mgr.getMarkerCount(6));
				//add the markers to the manager
				mgr.refresh();
			}
			// If tooltips are enabled then this sets up the tooltips
			//jm   initTooltip(tooltipShow);
			// If the overview map is enabled then it is envoked here.
			initOverview(overviewShow,overviewWidth,overviewHeight);


			//	}

			if (getURLVar('address') != ''){
				//showAddress(getURLVar('address'));
				showAddress(URLDecode(getURLVar('address')));
			}

			//whenever maps loads (i.e. it changes) call the sidebar 
		    //GEvent.addListener(map,"load",function(overlay,point){
			try{
				//GEvent.addListener(map,"click",function(overlay,point){
			    if (!onemarker){
				    GEvent.addListener(map,"moveend",function(){
						//alert("in moveend markers length:"+markers.length);
				    	try{
				    		if(tooltipShow != 0 ) tooltip.style.visibility="hidden";
							if (markers.length > 0){
				    			//alert("about to call showsidebar");
				    			showsidebar(sidebar_num, 0);
				    			//alert("about to call showhidemarkers");
				    			showhidemarkers();			
								//alert("about to call initlegend from moveend");
								initlegend();
							}
							//document.getElementById("google_maps_sidebar").scrollTop = document.getElementById("sb_"+currentselectedlhs).offsetTop;
						    var thepos = findPos(document.getElementById("sb_"+currentselectedlhs));
						    var theposp = findPos(document.getElementById("google_maps_sidebar"));
						    document.getElementById("google_maps_sidebar").scrollTop = thepos[1]-theposp[1];	
			   				//document.getElementById("testDiv").innerHTML += ",i";						
			   				document.getElementById("sb_"+currentselectedlhs).className = 'sidebar_marker_element_selected';		   				
						}catch(err){;}
						//see if we need new markers
						getareamarkers();
				    });
				    //GEvent.addListener(map,"zoomend",function(){
					//	alert("in zoomend markers length:"+markers.length);
				    //});
				    GEvent.addListener(map,"mouseover",function(){
					//	//alert("in map mouseover");
						filtershow(false);
				    });
			    }
			    
		        if (onemarker){
				    GEvent.addListener(map,"moveend",function(){
						//sometimes mgr loses track of it if marker has been moved - force a refresh of the mgr
						mgr = new MarkerManager(map);				
						mgr.addMarkers(batch, 6);
				 		mgr.refresh();				 		
				    });
			    }			    
			    
			}catch(err){alert("4444");}
			setlhslinks();
		} else {
			//alert("Your browser is not compatible with the Google Maps API");
			//document.getElementById("map").style.visibility = 'hidden';
			//document.getElementById("map").style.height = '0px';
			//document.getElementById("miscDiv").innerHTML = '<b>Address:</b>';
			var thelat;
			var thelng;
			try{
				if (document.getElementById("markerid").value > 0){
					onemarker = true;
				}
			}catch(err){;}
			if (onemarker){	
				thelat = document.getElementById('thelat').value;	//in case xml not updated yet
				thelng = document.getElementById('thelng').value;				
			}
			var st = 'http://maps.google.com/staticmap?zoom=15&key='+apikey+'&maptype=mobile&size=242x250';
			st += '&center='+thelat+','+thelng;
			st += '&markers='+thelat+','+thelng+',green';
			//alert(st);
			//document.getElementById("map").innerHTML = '<img border="0" src="http://maps.google.com/staticmap?center=40.714728,-73.998672&zoom=14&size=200x250&"></img>';
			document.getElementById("map").innerHTML = '<img border="0" src="'+st+'"></img>';
			//alert(document.getElementById("map").innerHTML);
		}
	}
 
 function getsearchmarkeridx(){
 	return -50;
 }
 
 function showAddress(address) {
      if (geocoder) {
        geocoder.getLatLng(
          address,
          function(point) {
            if (!point) {
              alert(address + " not found");
            } else {
           	  if (address.toLowerCase().indexOf('romania') > -1){
           	  	map.setMapType(G_SATELLITE_TYPE);
           	  }
              map.setCenter(point, 13);
              //var marker = new GMarker(point,baseIcon[8],{zIndexProcess:getsearchmarkeridx});
              var marker = new GMarker(point,{icon:baseIcon[8],zIndexProcess:getsearchmarkeridx});
              map.addOverlay(marker);
              //alert(GOverlay.getZIndex(marker.getPoint().lat()));
              //marker.openInfoWindowHtml(address);
              getareamarkers();
            }
          }
        );
      }
 }
 
 function clearmarkers(){

	//alert("in clearmarkers");	 	
 	markers = [];
 	//sidebar_htmls = [];
 	
 	batch = [];
	batchcont = [];
	batchcountry = [];
	batchcity = [];
 }
  
// function getareamarkers(url){
 function getareamarkers(){
//alert("in getareamarkers"+map.getZoom());
	//get markers required for current map area 	
 	//check if we need to call ... by looking at bounds
	var currentbounds = map.getBounds();	
	var sw = currentbounds.getSouthWest();
	var ne = currentbounds.getNorthEast();
	//if (!oldzoom){oldzoom = map.getZoom();}

	if (map.getZoom() >= 10){newzlevel = 1;}
	if (map.getZoom() >= 7 && map.getZoom() <= 9){newzlevel = 2;}
	if (map.getZoom() >= 4 && map.getZoom() <= 6){newzlevel = 3;}
	if (map.getZoom() >= 1 && map.getZoom() <= 3){newzlevel = 4;}

	if (!zlevel){
		markerbounds = null;
	}else if (zlevel != newzlevel){
		markerbounds = null;
	}

//	if (oldzoom <= 3 && map.getZoom() >= 4){
//		markerbounds = null;
//		//alert("reset markerbounds0");
//	}
//	if (oldzoom <= 6 && map.getZoom() >= 7){
//		markerbounds = null;
//		//alert("reset markerbounds1");
//	}
//	if (oldzoom <= 9 && map.getZoom() >= 10){
//		markerbounds = null;
//		//alert("reset markerbounds2");
//	}
//	if (oldzoom >= 10 && map.getZoom() < 10){
//		markerbounds = null;
//		//alert("reset markerbounds3");
//	}	

	oldzoom = map.getZoom();
	zlevel = newzlevel;

	var blngetnew = false;
	if (!markerbounds){
		blngetnew = true;
		clearmarkers();	
	}else{	
		if ( !markerbounds.contains(sw) || !markerbounds.contains(ne) ){
			blngetnew = true; 
		}
	}
	//alert("blngetnew:"+blngetnew);
	if (blngetnew){
		//markers not covered in last bound we got
		var bigsw = new GLatLng(sw.lat() - 0.1, sw.lng() - 0.1);	//6 degrees
		var bigne = new GLatLng(ne.lat() + 0.1, ne.lng() + 0.1);	//6 degrees
		markerbounds = new GLatLngBounds(bigsw,bigne);
		//store bounds we have markers for
		//var thepos = 'swlat='+sw.lat()+'&swlng='+sw.lng()+'&nelat='+ne.lat()+'&nelng='+ne.lng();
		//alert(map.getZoom());
		if (map.getZoom() >= 8){
			var thepos = 'swlat='+bigsw.lat()+'&swlng='+bigsw.lng()+'&nelat='+bigne.lat()+'&nelng='+bigne.lng();
			//alert(thepos);
		}else{
			if (ne.lng() < sw.lng() ){
				var nelng = 180;
				var swlng = -180;
			}else{
				nelng = ne.lng();				
				swlng = sw.lng();
			}
			//var thepos = 'swlat='+sw.lat()+'&swlng='+sw.lng()+'&nelat='+ne.lat()+'&nelng='+ne.lng();			
			var thepos = 'swlat='+sw.lat()+'&swlng='+swlng+'&nelat='+ne.lat()+'&nelng='+nelng;			
		}
		var url = 'index.php?option=com_google_maps&task=areaxml&'+thepos+'&zoom='+map.getZoom();
		url = url  + "&tmp=" + new Date().valueOf() ;
		
		//alert(url)	  ;
		$('legendDiv').style.display = "none";
		$('legendheadingspaceDiv').style.display = "none";
		
	 	document.getElementById("loadingDiv").innerHTML = '<table width="100%"><tr valign="middle"><td class="loadingmarkers">&nbsp;&nbsp;Loading Hotspots ... </td><td><img src="images/agifs/load1.gif"></img></td></tr></table>';
	 	document.getElementById("loadingDiv").className = 'loadingmarkers';
	 	document.getElementById("loadingDiv").style.top = "-500px";
	 	document.getElementById("loadingDiv").style.left = "50px";
		document.getElementById("loadingDiv").style.display = "block";
	 	
	 	sidebar_htmls = [];
	 	sidebar_place = 0;
	 	
	 	GDownloadUrl(url, function(data, responseCode) {
			if (responseCode == 200) {
				//markers = [];
	            var xmlDoc = GXml.parse(data);
	            
	            if (xmlDoc.xml == null){
					var serializer = new XMLSerializer();
					var xml = serializer.serializeToString(xmlDoc);
					//alert(xml);
				}else{
	            	//alert(xmlDoc.xml);
				}
	            
	            //alert(xmlDoc.xml);
		  		try{
		  			getloccnt(xmlDoc);
				//	initlegend();
		  		//}catch(err){alert("error1");}
		  		}catch(err){;}
		        xmlCats = xmlDoc.getElementsByTagName("category");
		        var catset = 0;
				var midx = 0;	//not every item will become a marker      
				markers = [];
				//alert("GDownloadUrl len b4:"+markers.length);
				//var batch = [];
				//var batchcountry = [];
				//var batchcity = [];
				//var batchcont = [];
				batch = [];
				batchcountry = [];
				batchcity = [];
				batchcont = [];
				//JM if we're configuring this business' marker, then only show that marker
				thisbusmarker = 0;	//global
				//configbusmarker = false;	//global
				onemarker = false;	//global
				blngotit=false;
				try{
					if (url.search(/maps.xml/i) > 0){
						thisbusmarker = document.getElementById('markerid').value;
						//if (thisbusmarker > 0){	configbusmarker = true;	}
						if (thisbusmarker > 0){	onemarker = true;	}
						//alert("thisbusmarker:"+thisbusmarker);
						//markernode = xmlDoc.selectSingleNode("//inf[@id='"+thisbusmarker+"']");
						//markernode = selectSingleNode(xmlDoc,"//inf[@id='"+thisbusmarker+"']");
						//alert(markernode.getAttribute("n"));
						//alert("after");
						infoWindows = xmlDoc.selectNodes("//inf[@id='"+thisbusmarker+"']");
						blngotit=true;
						//alert(blngotit+":"+infoWindows.length);
						//alert("after 2");
					}
				}catch(err){;}	
				//if (!configbusmarker || !blngotit){
				if (!onemarker || !blngotit){
			        infoWindows = xmlDoc.getElementsByTagName("inf");
				}
				//alert(blngotit+":"+infoWindows.length);
				var currenttime = new Date();
				//var currentms = currenttime.getMilliseconds();
				var currentms = currenttime.getTime();
				for (var j = 0; j < infoWindows.length; j++) {
					// Grab variables about the type of marker.
					var pid = infoWindows[j].getAttribute("id");
					var ptype = infoWindows[j].getAttribute("t");
					var pcat = infoWindows[j].getAttribute("cat");
					//only try to display if we have a lat/lng
					//if (configbusmarker){
					if (onemarker){
						var thelat = document.getElementById('thelat').value;	//in case xml not updated yet
						var thelng = document.getElementById('thelng').value;				
					}else{
						var thelat = infoWindows[j].getAttribute("la");
						var thelng = infoWindows[j].getAttribute("ln");
					}
					var blnrendermarker = true;
					if (pcat == 33){blnrendermarker = false;}	//map center not rendered
					//if (configbusmarker && (thisbusmarker != pid)  ){blnrendermarker = false;}	//just showing one marker
					if (onemarker && (thisbusmarker != pid)  ){blnrendermarker = false;}	//just showing one marker	
					if ( (thelat != "") && (thelng != "") && blnrendermarker){
				       	//if(checkCat(pcat,catsToDisplay) && checkCat(pid, markersToDisplay)) {
						if(checkCat(pcat,catDisplay) && checkCat(pid, pointsArray)) {
							// Checking to see if the info is for a polyline or a marker
							if( ptype == 2 ) {
								// Code for a polyline
								// get any line attributes
								var misc = infoWindows[j].getElementsByTagName("misc");
								var color = misc[0].getAttribute("polycolor");
								var width  = parseFloat(misc[0].getAttribute("polywidth"));
								// read each point on that line
								var points = infoWindows[j].getElementsByTagName("point");
								var pts = [];
								for (var i = 0; i < points.length; i++) {
									pts[i] = new GLatLng(parseFloat(points[i].getAttribute("lat")),
								                         parseFloat(points[i].getAttribute("lng")));
								}
								map.addOverlay(new GPolyline(pts,color,width));
							} else {
								// Code for a marker
								//var markerObj = new createMarker2(infoWindows[j],j);
								//newmarkers.push(markerObj);
								//markers[j] = createMarker(infoWindows[j],j);
								//markers[midx] = createMarker(infoWindows[j],j);
								var thismarker = createMarker(infoWindows[j],j);
								if (thismarker){
								    //GEvent.addListener(thismarker,"visibilitychanged",function(){
									//	alert("in visibilitychanged");
								    //});
									markers[midx] = thismarker;
									//markers[midx] = createMarker(infoWindows[j],j);			           
									// This opens the info window if automatic open is set on.
									if(centerId == pid && autoOpen == 1) {
										if(safariCompat == 1) {
											var html = infoHtml(infoWindows[j]);
										} else {
											var html = xsltProcess(infoWindows[j], xmlHttp.responseXML);
										}
										//markers[j].openInfoWindowHtml(html);	       
										markers[midx].openInfoWindowHtml(html);
									}
									if (pcat == 38){
										batchcountry.push(markers[midx]);						
									}else if (pcat == 44){
										batchcity.push(markers[midx]);
									}else if (pcat == 45){
										batchcont.push(markers[midx]);
									}else{
										batch.push(markers[midx]);
									}				
									midx = midx + 1;					
								}
							}
						}
					}
				}
				currenttime = new Date();
				//var newms = currenttime.getMilliseconds();
				var newms = currenttime.getTime();
				//alert ("took:"+(newms - currentms)+ " ms");
				//mgr = new GMarkerManager(map);
//a				mgr = new MarkerManager(map);
//a				mgr.addMarkers(batchcont, 1,3);
//a				mgr.addMarkers(batchcountry, 4,6);
//a				mgr.addMarkers(batchcity, 7,9);
//a				mgr.addMarkers(batch, 10);
				//add the markers to the manager
//a				mgr.refresh();
				//alert ("size:" + markers.length +  "   size batch:" + batch.length +  "   size batchcountry:" + batchcountry.length);        
				// Envokes the function to create the sidebar.
				//if(useSidebar == 1) {
				try{
		  			getloccnt(xmlDoc);
		  		}catch(err){alert("error1a");}
				if(sidebar_exists == 1) {
					try {
						//showItems(sidebar_num,sidebar_place);
						//if (map.getZoom() > 6){
							//showsidebar(sidebar_num,sidebar_place);
							showsidebar(sidebar_num,sidebar_place,'forward');
						//}
					} catch(err){}
				}
				//problem if no sidebar .... as typcnt loaded in showsidebar
				try{
		  			//getloccnt(xmlDoc);
					initlegend();
		  		//}catch(err){alert("error1");}
		  		}catch(err){;}
				//if (map.getZoom() >= 4 && map.getZoom() <= 6){
				//	cidx = 0;
				//	//timer1 = setInterval("startrotatinginfo()",3000 );
				//}else{
				//	try{
				//		clearInterval(timer1);
				//	}catch(err){;}
				//}			
				
				document.getElementById("loadingDiv").style.display = "none";
				$('legendDiv').style.display = "block";
				//if (map.getZoom() >= 7){
				if (map.getZoom() > 9){
					$('legendheadingspaceDiv').style.display = "block";
				}
				//alert("GDownloadUrl after:"+markers.length);
				showhidemarkers();
			}
		});
 	
 	}
// 	showhidemarkers(); 	
 	
 }
 
 function openaddmarker(thismarker){

	var point = thismarker.getPoint();

 	shtml = '<div><form action="index.php?option=com_google_maps&Itemid=' + _GET['Itemid'] + '&center=' + _GET['center'] + '&zoom=' + _GET['zoom'] + '" method="post" name="userform" >Question: <input type=text id=newquestion name=newquestion></input><br>';
	shtml = shtml + 'Answer: <input type=text id=newanswer name=newanswer></input><br>';
 	shtml = shtml + '<input type=hidden id=newquestionsubmitted name=newquestionsubmitted value="yes"></input>';
 	shtml = shtml + '<input type=hidden id=newlat name=newlat value="' + point.y + '"></input>';
 	shtml = shtml + '<input type=hidden id=newlng name=newlng value="' + point.x + '"></input>';
 	shtml = shtml + '<input type=submit id=go name=go value="submit"></input></form></div>';
 	thismarker.openInfoWindowHtml(shtml);
 }


function getURLVar(urlVarName) {
   var urlHalves = String(document.location).toLowerCase().split('?');
   var urlVarValue = '';
   if(urlHalves[1]){
      var urlVars = urlHalves[1].split('&');
      for(var i=0; i<=(urlVars.length); i++){
         if(urlVars[i]){
            var urlVarPair = urlVars[i].split('=');
            if (urlVarPair[0] && urlVarPair[0] == urlVarName.toLowerCase()) {
               urlVarValue = urlVarPair[1];
            }
         }
      }
   }
   return urlVarValue;
}

/*
if( document.implementation.hasFeature("XPat... "3.0") )
{
	XMLDocument.prototype.selectNodes = function(cXPathString, xNode)
	{
		if( !xNode ) { xNode = this; }
		var oNSResolver = this.createNSResolver(this.documentEleme...
		var aItems = this.evaluate(cXPathString, xNode, oNSResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null)
		var aResult = [];
		for( var i = 0; i < aItems.snapshotLength; i++) {
			aResult[i] = aItems.snapshotItem(i);
		}
		return aResult;
	}
	XMLDocument.prototype.selectSingleNod... = function(cXPathString, xNode) {
		if( !xNode ) { xNode = this; }

		var xItems = this.selectNodes(cXPathString, xNode);
		if( xItems.length > 0 )	{
			return xItems[0];
		}else{
			return null;
		}
	}

	Element.prototype.selectNodes = function(cXPathString) {
		if(this.ownerDocument.selectNodes){
			return this.ownerDocument.selectNodes(cXPathStr... this);
		}else{throw "For XML Elements Only";}
	}

	Element.prototype.selectSingleNode = function(cXPathString) {
		if(this.ownerDocument.selectSingleNo...
		{
		return this.ownerDocument.selectSingleNode(cXPa... this);
		}
		else{throw "For XML Elements Only";}
	}
}
*/

/*
if (!window.ActiveXObject) {
	Element.prototype.selectNodes = function(sXPath) {
		var oEvaluator = new XPathEvaluator();
		var oResult = oEvaluator.evaluate(sXPath, this, null, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null);
		var aNodes = new Array();
		if (oResult != null) {
			var oElement = oResult.iterateNext();
			while(oElement) {
				aNodes.push(oElement);
				oElement = oResult.iterateNext();
			}
		}
		return aNodes;
	}

	Element.prototype.selectSingleNode = function(sXPath) {
		alert("in prototype");
		var oEvaluator = new XPathEvaluator();
		// FIRST_ORDERED_NODE_TYPE returns the first match to the xpath.
		var oResult = oEvaluator.evaluate(sXPath, this, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
		if (oResult != null) {
			return oResult.singleNodeValue;
		} else {
			return null;
		}              
	}
}
*/

/*
function selectSingleNode(xmlDoc, elementPath){
		alert("in fn");
 
    if(window.ActiveXObject)
    {
        return xmlDoc.selectSingleNode(elementPath);
    }
    else
    {
       var xpe = new XPathEvaluator();
       var nsResolver = xpe.createNSResolver( xmlDoc.ownerDocument == null ? xmlDoc.documentElement : xmlDoc.ownerDocument.documentElement);
       var results = xpe.evaluate(elementPath,xmlDoc,nsResolver,XPathResult.FIRST_ORDERED_NODE_TYPE, null);
       return results.singleNodeValue; 
    }
}
*/


// check for XPath implementation 

//alert("xpathimplementation:"+document.implementation.hasFeature("XPath", "3.0"));


if( document.implementation.hasFeature("XPath", "3.0") ) 
{ 
try{

	// prototying the XMLDocument 
	XMLDocument.prototype.selectNodes = function(cXPathString, xNode) 
	{ 
	//alert("in prototype doc ");
		if( !xNode ) { xNode = this; }
		var oNSResolver = this.createNSResolver(this.documentElement) 
		var aItems = this.evaluate(cXPathString, xNode, oNSResolver,
		XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null) 
		var aResult = [];
		for( var i = 0; i < aItems.snapshotLength; i++) 
		{ 
			aResult[i] = aItems.snapshotItem(i);
		} 
		return aResult;
	} 
	// prototying the Element 
	Element.prototype.selectNodes = function(cXPathString) 
	{ 
	//alert("in prototype element ");
		if(this.ownerDocument.selectNodes) 
		{ 
			return this.ownerDocument.selectNodes(cXPathString, this);
		} 
		else{throw "For XML Elements Only";} 
	} 
}catch(err){;}


} 

function URLDecode( encoded ){
   var HEXCHARS = "0123456789ABCDEFabcdef"; 
   var plaintext = "";
   var i = 0;
   while (i < encoded.length) {
       var ch = encoded.charAt(i);
	   if (ch == "+") {
	       plaintext += " ";
		   i++;
	   } else if (ch == "%") {
			if (i < (encoded.length-2) 
					&& HEXCHARS.indexOf(encoded.charAt(i+1)) != -1 
					&& HEXCHARS.indexOf(encoded.charAt(i+2)) != -1 ) {
				plaintext += unescape( encoded.substr(i,3) );
				i += 3;
			} else {
				//alert( 'Bad escape combination near ...' + encoded.substr(i) );
				plaintext += "%[ERROR]";
				i++;
			}
		} else {
		   plaintext += ch;
		   i++;
		}
	}
    return plaintext;
}