/*
arguments that can be forcedly set:
 mapinit = 1;
        spotsr = 20;
        glife = 15;
        shlotw = 0;
        fid = 0;
        fargs = 'cdx=PY1NB';
        shsetup = 1;

*/

//var fid = $.getURLParam("f");
//var mr = $.getURLParam("r");
//var mxr = 15; //maxrows
var tr = 0; 
//var tablename = 'spots';
//var nospot_ = 0;
//var fargs = 'd=1';	
var i18n_str = Array();
var tr_row = 0;
var lastspots = 0;
var spotsr = 0;
var spotsformat;
var spf_css;
var spotsinterval = 20000;
//these are set by options tab, and their values come from cookies
var lang;
var shmap;
var glife = 0;
var gpath;
var gmark;
var shlotw = 2;
var shsetup;
var de;
//var g_de = [];
//var g_dx = [];
//var g_line = [];
var map;
var mapinit = 0;
var fargs = 'd=1';
var dxIcon;
var deIcon;
var ns = 0;
//
//
//check this!!!!
var spots = Array();


var geo_data = Array();
var fid = 0;
var g_b = Array();
g_b[3] = ['ffe000', '160m'];
g_b[7] = ['093F00', '80m'];
g_b[12] = ['ffa500', '40m'];
g_b[17] = ['ff0000', '30m'];
g_b[22] = ['800080', '20m'];
g_b[27] = ['0000ff', '17m'];
g_b[32] = ['ff00ff', '15m'];
g_b[37] = ['00ffff', '12m'];
g_b[42] = ['aaaaaa', '10m'];
g_b[50] = ['ffc0cb', '6m'];
g_b[62] = ['92FF7F', '2m'];
g_b[0] = ['000000', '&nbsp;'];


function startup(){
	if ( shsetup != 1 )
		setTimeout('$("div#setup").hide("slow")', 1500);	
	$('div#sendspot').hide();
	$('div#callsrch').hide();
	$('div#lastfil').hide();
	$("div#mapopt").hide();

	/*---------------------------------------------------------------------------*/
	//set_cookie ('screenres', (window.screen.width + 'x' + window.screen.height), 0);
	/*---------------------------------------------------------------------------*/
	//check rows values
	if ( spotsr == 0 ) {
	 	spotsr = get_cookie('spotsri'); 
		if ( spotsr == undefined ) 
			spotsr = 15;
	}
	
	//load value into select
	$('table#spots form.rows select').find('option[value=' + spotsr + ']').attr( { selected: 'selected' } );
	
	//check if user changed num of rows
	$('table#spots form.rows select').change(function () {
		check_rows('spots', 'spot', 'i');		
	});

	/*---------------------------------------------------------------------------*/
	//check rows values
	
	/*---------------------------------------------------------------------------*/
	//if mapinit = 1 or higher, the map will be forced on
	if ( mapinit < 1 && ( get_cookie( 'shmap' ) == 0 || !get_cookie( 'shmap' ) ) )  { 
		$("div#mapwrapper").hide('fast');
		$("div#setup div.mapspots").hide('fast');
		shmap = 0;
	} else {
		shmap = 1;
		showmap();
	} 	

	$("span#setupopt").click(function () {
		$("div#setup").slideToggle();
	});
	
	/*---------------------------------------------------------------------------*/
	//spots mode
	spotsformat = get_cookie('splm');
	if ( spotsformat == undefined ) 
		spotsformat = '0';
	
	$('form.spotsfopt select').find('option[value=' + spotsformat  + ']').attr( { selected: 'selected' } );


	if ( spotsformat > 0 ) spots_format(spotsformat);	
	
	$('form.spotsfopt select').change(function () {
		spotsformat = $('form.spotsfopt select').val();
		set_cookie ( 'splm', spotsformat, '9999' );
		spots_format( spotsformat );	
	});
	/*---------------------------------------------------------------------------*/
	//spotsmodeuage
	//debug ('sandbox');
	//lang = get_cookie('lang');
	if ( lang == undefined ) 
		lang = 'en';
	
	$('form.langopt select').find('option[value=' + lang  + ']').attr( { selected: 'selected' } );
	
	$('form.langopt select').change(function () {
			lang = $('form.langopt select').val();
				set_cookie ( 'lang', lang, '9999' );
			location.reload();	
	});
	/*---------------------------------------------------------------------------*/
	$('form.mapopt').find(':radio[value=' + shmap + ']').attr( { checked: 'checked' } );
	
	$('form.mapopt input').change(function () {
		shmap = $('form.mapopt input:checked').val();
		if ( shmap == 0 ) { 
			clear_map_data();
			$("div#mapwrapper").hide('slow');
			$("div#setup div.mapspots").hide('slow');
			set_cookie ( 'shmap', 0, '9999' );
		} else {	
			$("div#mapwrapper").show('slow');
			$("div#setup div.mapspots").show('slow');
			showmap();
			set_cookie ( 'shmap', 1, '9999' );
		}
	});

	/*---------------------------------------------------------------------------*/
	//load value into select
	if ( shlotw == 2 ) {
		shlotw = get_cookie('shlotw');
		if ( shlotw == undefined ) 
			shlotw = 0;
	}
	$('form.lotwopt').find(':radio[value=' + shlotw + ']').attr( { checked: 'checked' } );
	
	$('form.lotwopt input').change(function () {
		shlotw = $('form.lotwopt input:checked').val();
		set_cookie ( 'shlotw', $('form.lotwopt input:checked').val(), '9999' );
	});

	/*---------------------------------------------------------------------------*/
	//user wants to send out spots
	$("span.clicktosend").click(function () {
      		if ( $("div#sendspot:hidden") ) { 
			$('div#sendspot').load("post.php")
		}
		$("div#sendspot").slideToggle();
	});
	/*---------------------------------------------------------------------------*/
        //user wants to search for spots
	$("span#tgsrch").click(function () {
                $("div#callsrch").slideToggle();
        });
	/*---------------------------------------------------------------------------*/
	//we have a message to the user	
	if ( $('div#msg') ) 
		setTimeout( function() { $('div#msg').slideUp('slow') }, 45000 );
	/*---------------------------------------------------------------------------*/
	//check spots life on map
	if ( glife == 0 ) {
		glife = get_cookie('gl');
		if ( glife == undefined ) 
			glife = 0;
	}
	//load value into select
	$('form.glife select').find('option[value=' + glife + ']').attr( { selected: 'selected' } );
	
	$('select[name=glife]').change(function () {
		map.clearOverlays();
		glife = $('form.glife select').val();
		set_cookie( 'gl', glife, '9999');
	});
	/*---------------------------------------------------------------------------*/
	//check spots path on map
	gpath = get_cookie('gp');
	if ( gpath == undefined ) 
		gpath = 0; //straight
	//load value into select
	$('form.gpath').find(':radio[value=' + gpath + ']').attr( { checked: 'checked' } );

	$('form.gpath input').change(function () {
		map.clearOverlays();
		gpath = $('form.gpath input:checked').val();
		set_cookie( 'gp', gpath, '9999');
	});
	/*---------------------------------------------------------------------------*/
	//user wants to see his last filters
	$("span#tglf").click(function () {
		if ( $('#lastfil').text().length <= 1) { 
			$('#lastfil').load('/spots/lastfil.php');
		}
		$("div#lastfil").slideToggle();
	});
	/*---------------------------------------------------------------------------*/
}

function gen_map_legend() {
	var t = '&nbsp;';
	for ( key in g_b ) {
		t += '  <font color=\'#' + g_b[key][0] +  '\'>' + g_b[key][1] + '</font> /';
	}
	t = t.replace( /.$/g, "" );
	return t;
}



function process_xml_spots(xml, tableid) {
	//alert (tableid);
	var table = $('table').find( tableid ).empty().end();
	var df = 0;
		
	//get the filter name
	$(xml).find( 'fname' ).each( function(){
		//$('table#' + tableid + ' th.' + tableid + 'title span.' + tableid + 'title').empty().append( $(this).text() );
		$('table#' + tableid + ' td.loading').remove();
	});

	if ( eval( 'last' + tableid ) == 0 ) {
		//debug ( 'spots first run');
		//check if we have no spots for this filter
		$(xml).find('nd').each( function() {
			if ( ns == 0 ) {
				tr_row++;
				var tr = document.createElement('tr');
				$(tr).append( '<td class="nospot" colspan="7">' + $(this).text() + '</td>' ) ;
				$(tr).addClass('nospot'); 
				$('table#' + tableid + ' tr.header').after(tr);
				ns = 1;
				$(tr).addClass( myzebra(tr_row) );
				tr = null;
			}
		});
		
	}
	
	$(xml).find('rs').each(function(id){
		//debug ('we got an rs line at xml');
		var tr = document.createElement('tr');
		var row;
		var spot;
		var id;
		var l = ''; //lotw
		tr_row++;
		var g_dx_;
		var b; var g_line_;
		var geo;
	
		row = $("rs",xml).get(id);
		
		$('id',row).each(function(){
			id = 'x'+$(this).text();
			lastspots = $(this).text();
			//add this item to the spot array
			eval(tableid)[id] = Math.round(new Date().getTime()/1000.0);
			//debug ( 'id has been set to: ' + id );
			//debug ( 'lastspots has been set to: ' + lastspots );
		});
		
	
		$('de',row).each(function(){
			$(tr).append( '<td class="de"><a rel="fb" target="_blank" class="callsign" href="/qrz/' 
				+ $(this).text() +
				'" title="' + 
			 	$('A' + $(this).text().replace(/[^a-zA-Z0-9]/, '') , xml).text()
				+ '">' 
				+ $(this).text() + '</a></td>' );
		
			//REMOVEif this point is not in the geo array, include it
			//if this point is in the array, remove the old one, and put the new one
			if ( $( "#mapwrapper" ).is(':visible')  && $(row).find('b').text().length > 0 ) {
			//	g_de[ $(this).text() ] = [ 
				g_de_ = [ 
					$(xml).find( 'B' + $(this).text().replace(/[^a-zA-Z0-9]/, '') + ' a').text(), 
					$(xml).find( 'B' + $(this).text().replace(/[^a-zA-Z0-9]/, '') + ' o').text()
					];
			}
			de = $(this).text();
		});
		
		$('dx',row).each(function(){
			$(tr).append( '<td class="dx"><a rel="fb" target="_blank" class="callsign" href="/qrz/' 
				+ $(this).text() +
				'" title="' + 
			 	$('A' + $(this).text().replace(/[^a-zA-Z0-9]/, '') , xml).text()
				+ '">' 
				+ $(this).text() + '</a></td>' );
	
			//REMOVEif this point is not in the geo array, include it
			//if this point is in the array, remove the old one, and put the new one
			if ( $( "#mapwrapper" ).is(':visible')  && $(row).find('b').text().length > 0 ) {
				//g_dx[ $(this).text() ] = [ 
				g_dx_ = [ 
					$(xml).find( 'B' + $(this).text().replace(/[^a-zA-Z0-9]/, '') + ' a').text(), 
					$(xml).find( 'B' + $(this).text().replace(/[^a-zA-Z0-9]/, '') + ' o').text()
					];

				//if we dont have band information coming from spot, set it to blank value 
				b = $(row).find('b').text();
				if ( ! g_b [ b ] ) { 
					b = 0;
				}
				geo = [ g_de_, g_dx_, b, de, $(this).text() ];
 
			}

			de = null;
		});
		
		$('qrg',row).each(function(){
			$(tr).append( '<td class="qrg">' + $(this).text() + '</td>' );
		});
			
		$('t',row).each(function(){
			if ( $(this).text() == 1 ) { 
				//$(tr).append( '<td class="obs">' + $(this).text() + '</td>' );
				//$(tr).append( '<td class="obs">' + html_entity_encode( $(this).text() ) + '</td>' );
				$(tr).append( '<td class="obs">' + html_entity_encode( 'CQ' ) + '</td>' );
			} else {
				$(tr).append( '<td class="obs">' + html_entity_encode( 'DX' ) + '</td>' );
			}
		});
		
		$('db',row).each(function(){
			var db;
			if ( $(this).text() == 0 ) { db = '--'; } else { db = $(this).text() + ' dB'; } 
			$(tr).append( '<td class="db"><span>' + db + '</span></td>' );
			spot += " " + $(this).text();
		});
		
		$('wpm',row).each(function(){
			var wpm;
			wpm = 10;
			if ( $(this).text() == 0 ) { wpm = '--'; } else { wpm = $(this).text() + ' wpm'; } 
			$(tr).append( '<td class="wpm"><span>' + wpm + '</span></td>' );
			spot += " " + $(this).text();
		});
	

		
		$('obs',row).each(function(){
			//$(tr).append( '<td class="obs">' + id + '--' + html_entity_encode( $(this).text() ) + '</td>' );
			$(tr).append( '<td class="obs">' + html_entity_encode( $(this).text() ) + '</td>' );
		});
		var l = ''; //lotw
		
		$('utc',row).each(function(){
			//$(tr).append( '<td class="utc">' + $(this).text().replace(/\s/g, '&nbsp;') + ' (' + tr_row + ')<span class="age"></span></td>' );
			$(tr).append( '<td class="utc"><a href="#">' + $(this).text().replace(/\s/g, '&nbsp;') + '</a> <span class="age"></span></td>' );
		});

		$('df',row).each(function(){
			//update the spots array for this difference
			eval(tableid)[id] = Math.round(new Date().getTime()/1000.0) - $(this).text();
			df = 1;
		});
		$(tr).attr( { id: id } );
		$(tr).addClass( 'spot' );
		$(tr).addClass( 'spots' );
		$(tr).addClass( myzebra(tr_row) );
		//$('a[rel*=fb]', tr ).facebox().Tooltip({track:true,showURL:false,showBody: "*****"});
		$('a[rel*=fb]', tr ).Tooltip({track:true,showURL:false,showBody: "*****"});
		//$('span[rel*=fb]', tr ).facebox().Tooltip({track:true,showURL:false,showBody: "*****"});

		//debug('g_de_:' + g_de_);
		//debug('g_dx_:' + g_dx_);
		//debug('g_line_:' + g_line_);
		
		//debug ( 'geo:'+ geo); 
		insert_row(tableid, 'spot', tr, geo);
		tr = null;
	
		$('table#' + tableid + ' tr.spots:first').hide().fadeIn(500);

		row = null;
		id = null;
		spot = null;
	});

		//get the i18n strings
		$(xml).find('str').each( function() {
			$('table#' + tableid + ' td.loading').remove();
			$(this).find('*').each( function() {
				i18n_str[this.tagName] = $(this).text();
			});
		});

		//check if we have msg..
		$(xml).find('msg').each( function() {
			if ( $('table#' + tableid + ' tr.msg').length >= 1  )
				return;

			tr_row++;
			var tr = document.createElement('tr');
			$(tr).append( '<td colspan="5">' + $(this).text() + '</td>' ) ;
			//$(tr).addClass('spot'); 
			$(tr).addClass( 'spots' );
			$(tr).addClass('msg'); 
			$(tr).addClass( myzebra(tr_row) );
				
			insert_row(tableid, 'spots', tr);
			tr = null;

			$('table#' + tableid + ' tr.spot:first').hide().fadeIn(500);
		});
	
		//check if we have ads..
		/*
		$(xml).find('ads').each( function() {

			//debug ( $('table#' + tableid + ' tr.spot:first').attr("class") );
 
			if ( $('table#' + tableid + ' tr.ads').length >= 1 || $('table#' + tableid + ' tr.spot:first').attr("class").match(/\sa$/)  ) {
				return;
			}
				tr_row++;
				
				//MUST BE PLACED in <tr class=a>
				var tr = document.createElement('tr');
				var zoneid = $('ads zid', xml).text();
				var height = $('ads h', xml).text();
				var width = $('ads w', xml).text();
				var ads = "<iframe frameborder='0' scrolling='no' id='aadd89bb' name='aadd89bb' src='http://ads.dxwatch.com/www/delivery/afr.php?refresh=180&amp;n=aadd89bb&amp;zoneid=" + zoneid + "&amp;target=_blank&amp;cb=1234567' width='" + width +  "' height='" + height + "'></iframe>"; 
				$(tr).append( '<td colspan="5">' + ads + '</td>' ) ;
				$(tr).addClass('ads'); 
				$(tr).addClass( 'spots' );
				//$(tr).addClass('spot'); 
				$(tr).addClass( myzebra(tr_row) );

				insert_row(tableid, 'spots', tr);
				
				tr = null; ads = null; zoneid = null; height = null; width = null;
				//debug( since_last_ad + '/' + mr +'/'+ $('table#' + tableid + ' tr').length, 'replace');
		});	
		*/
		$(tr).hover(
			function(){
				$(this).append($("<span> ***</span>"));
			},
			function(){
				$(this).removeClass('hover')
			}
		);
		
	//debug('df:'+df);
	//if ( $( "#mapwrapper" ).is(':visible') ) 
	//	insert_marker();
	calc_age_spots(tableid);
}
/*
$.fn.zebra = function() {
	$('tbody tr:visible',this)
		.filter(':odd').removeClass('b').addClass('a')
		.end()
		.filter(':even').removeClass('a').addClass('b');
	return this;
}
*/
function myzebra(i) {
	if ( i % 2 == 0 ) {
		return 'a';
	} else {
		return 'b';
	}       
}

function debug(str_, action) {
	if ( action == 'replace' )
		$('div#debug').empty();
 	
	$('div#debug').prepend(str_ + '<br><br>');
}

function html_entity_encode(str) {
  str=str.replace(/</g,"&lt;").replace(/>/g,"&gt;");
  return str;
}


function check_rows(tableid, class_, suffix) {
	var len = $('table#' + tableid + ' tr.' + class_).length;
	var rows = $('table#' + tableid + ' form.rows select').val() ;

	window[tableid + 'r'] = rows;

	//lets store this setting in user's browser
	set_cookie( tableid + 'r' + suffix, rows, '9999');

/*
	if ( len > rows ) { 
		var i=0;
		var diff = len - rows; 
		for ( i = 0; i <= diff; i++ ) {
			$('table#' + tableid + ' tr:last').remove();
		}

	} else if ( len < rows ) {
*/
	//we must clean our map..
	clear_map_data();
	
		if ( tableid.match( /spots/ ) ) {
			get_xml_spots ( tableid, 1 );
		}

		$('table#' + tableid + ' tr.' + class_ ).remove();
//	}
	//debug (  $('table#' + tableid + ' tr.spot' ).length );


}

function insert_row(tablename, class_, tr, geo) {
	//debug( tablename + '.' + class_ + ' ins>> mr: ' + eval(tablename+'r') + ' len: ' + $('	table#' + tablename + ' tr.'+ class_).length);	

	// do we need to remove anything?	
	if ( $('table#' + tablename + ' tr.' + class_).length + 1  > eval(tablename+'r') ) {
		try { 
			//delete spots[id]
			delete ( eval(tablename) [ $('table#' + tablename + ' tr.' + class_ + ':last').attr('id') ] ) 
		} catch(err){ return null; };

		if ( $('table#' + tablename + ' tr.' + class_ + ':last').attr("class").match(/spot/) ) {
			
			if ( $( "#mapwrapper" ).is(':visible') && 
	typeof geo_data[ $('table#' + tablename + ' tr.' + class_ + ':last').attr("id")  ] != "undefined" ) {
			//try {
			map.removeOverlay(geo_data[ $('table#' + tablename + ' tr.' + class_ + ':last').attr("id") ][0]);
			map.removeOverlay(geo_data[ $('table#' + tablename + ' tr.' + class_ + ':last').attr("id") ][1]);
			map.removeOverlay(geo_data[ $('table#' + tablename + ' tr.' + class_ + ':last').attr("id") ][2]);
			//} catch(err) { return null; };
			}
		
		}
		//finally we remove the last line from the table
		$('table#' + tablename + ' tr.' + class_ + ':last').remove();
	}

	//ok, I can add the row now		
	$('table#' + tablename + ' tr.header:last').after(tr);
	
	//do I need to map it?
	//if ( typeof geo != "undefined" ) {
	if ( $( "#mapwrapper" ).is(':visible') && typeof geo != "undefined" ) {
		geo_data[ $(tr).attr("id") ] = insert_geo_data ( geo );
	} 
}

function calc_age_spots(tablename) {
	//debug(tablename);
	for (id in spots) {
	var age = '0';
		age = calc_age( spots[id] );
		
		if ( age == 'void' ) {
			$('table#' + tablename + ' tr#' + id + '.spot td.utc a').attr( { title: 
				i18n_str["new"] } );

			//$('table#' + tablename + ' tr#' + id + '.spot td.utc span.age').empty().append( i18n_str["new"] );

		} else {
			$('table#' + tablename + ' tr#' + id + '.spot td.utc a').attr( { title: 
				i18n_str["ago"].replace(/\@\@\@/g, age)
			} );
			
			//$('table#' + tablename + ' tr#' + id + '.spot td.utc span.age').empty().append( i18n_str["ago"].replace(/\@\@\@/g, age) );
				
		}
	}
	$('table#' + tablename + ' tr[id].spot td.utc a').Tooltip({track:true,showURL:false});
}

function calc_age ( spotlocalcreated ) {
	var now = Math.round(new Date().getTime()/1000.0);
	var seconds = now - spotlocalcreated;

	var minutes = (( seconds / 60 ) % 60 ) | 0;
	var hours = (( seconds / 3600 ) % 24 ) | 0; 	
	var days = ( seconds / 86400 ) | 0; 	

	if ( ( minutes == '0' || minutes == '1' )  && hours == '0' && days == '0' )
		return 'void';

	minutes = ' ' + minutes + ' ' + i18n_str['mms'] + ',';
	
	if ( hours == 1 ) {
		hours = ' ' + hours + ' ' + i18n_str['hh'] + ',';
	} else if ( hours > 1 ) {
		hours = ' ' + hours + ' ' + i18n_str['hhs'] + ',';
		minutes = ' ';
	} else if ( hours == 0 ) {
		hours = ' ';
	}

	if ( days == 1 ) { 
		days = ' ' + days + ' ' + i18n_str['dd'] + ',';
	} else if ( days > 1 ) { 
		days = ' ' + days + ' ' + i18n_str['dds'] + ',';
		hours = ' ';
	} else if ( days == 0 ) {
		days = ' ';
	}	

	age = (days + hours + minutes);
	//age = age.slice(0, -1);
	age = age.replace ( /,.*$/, ''  );
	return age;
}

function lookup() {
	var call = document.forms[0].c.value;
	window.open('/qrz/' + call);
	return false;
}

function postspot(action) {
	$.post("post.php", {
		a: action,
		dx: $('input.dx').val(),
		qrg: $('input.qrg').val(),
		obss: $('input.obss').val(),
		obsa: $('input.obsa').val()
	}, function(html) {
		$("div#sendspot").empty().append( html );
	}); 
	return false;
}

function set_cookie(cookieName,cookieValue,nDays) {
	var today = new Date();
	var expire = new Date();
	if (nDays==null || nDays==0) nDays=1;
	expire.setTime(today.getTime() + 3600000*24*nDays);
	document.cookie = cookieName+"="+escape(cookieValue)
		+ ";expires="+expire.toGMTString();
}
function get_cookie ( cookie_name ) {
	var results = document.cookie.match ( '(^|;) ?' + cookie_name + '=([^;]*)(;|$)' );

	if ( results )
		return ( unescape ( results[2] ) );
	else
		return null;
}


function showmap() {
	if ( mapinit == 1 ) return;
	
	$('#maplegend').append(
		'<b>' + gen_map_legend() + '</b>'
	);

	dxIcon = new GIcon(G_DEFAULT_ICON, "/img/gmap/dx.png");
	dxIcon.shadow = null;
	dxIcon.iconSize = new GSize(6, 6);
	dxIcon.iconAnchor = new GPoint(3,3);

	deIcon = new GIcon(G_DEFAULT_ICON, "/img/gmap/de.png");
	deIcon.shadow = null;
	deIcon.iconSize = new GSize(6, 6);
	deIcon.iconAnchor = new GPoint(3,3);

      	if (GBrowserIsCompatible()) {
        	map = new GMap2(document.getElementById("map"));
        	map.setCenter(new GLatLng(8,0), 1);
		map.addControl(new GLargeMapControl());
		map.addControl(new GMapTypeControl()); 
	        //map.addControl(new GOverviewMapControl(new GSize(200,200)));
		mapinit = 1;
	}
}

function clear_map_data() {
	for ( key in geo_data ) {
		map.removeOverlay(geo_data[ key ][0]);
		map.removeOverlay(geo_data[ key ][1]);
		map.removeOverlay(geo_data[ key ][2]);
	} 
	geo_data = Array();
}

function insert_geo_data( geo_data ) {
		//debug('g_dx:'+key+'='+g_dx[key]);
		var dx_marker = new GMarker( new GLatLng( geo_data[1][0], geo_data[1][1] ) , { icon:dxIcon, title:'DX: ' + geo_data[4]} );
	        // The new marker "mouseover" listener        
		map.removeOverlay(dx_marker); 
		map.addOverlay(dx_marker);
		

		var de_marker = new GMarker( new GLatLng( geo_data[0][0], geo_data[0][1] ) , { icon:deIcon, title:'DX: ' + geo_data[3]} );
	        // The new marker "mouseover" listener        
		map.removeOverlay(de_marker); 
		map.addOverlay(de_marker);

		var points = [ new GLatLng( geo_data[0][0], geo_data[0][1] ), 
				new GLatLng( geo_data[1][0], geo_data[1][1] ) ];
		
		var b = geo_data[2] ;	
	
		//this wont draw geodesic lines
		var polylineEncoder = new PolylineEncoder();
		var polyline = polylineEncoder.dpEncodeToGPolyline(points, '#' + g_b[b][0] , 1, 1 );		
		
		map.removeOverlay( polyline ); 
		map.addOverlay( polyline );
		
		//setTimeout((function(polyline) { return function() { map.removeOverlay(polyline) }; })(polyline), glife * 1000);
		if ( glife > 0 ) {
			setTimeout((function(dx_marker) { return function() { map.removeOverlay(dx_marker) }; })(dx_marker), glife * 1000);
			setTimeout((function(de_marker) { return function() { map.removeOverlay(de_marker) }; })(de_marker), glife * 1000);
			setTimeout((function(polyline) { return function() { map.removeOverlay(polyline) }; })(polyline), glife * 1000);
		}
		return Array(de_marker, dx_marker, polyline);
}
function insert_marker() {
	for (key in g_dx) {
		//debug('g_dx:'+key+'='+g_dx[key]);
		var marker = new GMarker( new GLatLng( g_dx[key][0], g_dx[key][1] ) , { icon:dxIcon, title:'DX: ' + key} );
	        // The new marker "mouseover" listener        
		map.removeOverlay(marker); 
		map.addOverlay(marker);
		setTimeout((function(marker) { return function() { map.removeOverlay(marker) }; })(marker), glife * 1000);
	}

	for (key in g_de) {
		//debug('g_de:'+key+'='+g_de[key]);
		var marker = new GMarker( new GLatLng( g_de[key][0], g_de[key][1] ) , { icon:deIcon, title:'DE: ' + key} );
	        // The new marker "mouseover" listener        
		map.removeOverlay(marker); 
		map.addOverlay(marker);
		setTimeout((function(marker) { return function() { map.removeOverlay(marker) }; })(marker), glife * 1000);
	}

	for (key in g_line) {
		//continue;
		//debug('gpath='+gpath + '///g_line:'+key+'='+g_line[key]);
		var points = [ new GLatLng( g_line[key][0][0], g_line[key][0][1] ), 
				new GLatLng( g_line[key][1][0], g_line[key][1][1] ) ];
		/*
		if ( gpath == 1 ) {
			var polyOptions = { geodesic:true };
		} else {
			var polyOptions = { geodesic:false };
		}
		*/	

		//firefox 3 hangs out when loading geodesic, disabling it
		//if (/Firefox[\/\s](\d+\.\d+)|Safari/.test(navigator.userAgent)){
		//	var polyOptions = { geodesic:false };
		//}

		//var polyline = new GPolyline( points, '#' + g_line[key][2], 1, 1, polyOptions );

		//this wont draw geodesic lines
		var polylineEncoder = new PolylineEncoder();
		var polyline = polylineEncoder.dpEncodeToGPolyline(points, '#' + g_line[key][2], 1, 1 );		
		
		map.removeOverlay( polyline ); 
		map.addOverlay( polyline );
		
		setTimeout((function(polyline) { return function() { map.removeOverlay(polyline) }; })(polyline), glife * 1000);
	}

	g_line = [];
	g_de = [];
	g_dx = [];
}

function get_xml_spots ( tableid, reset ) {
	/*if (!reset) reset = "0";	
	
	if ( reset == 1 ) {
		lastspots = 0;
	} else {
		lastspots = spots.length -1;
		if ( lastspots < 0 ) lastspots = 0;
		
		if ( lastspots == 0 ) { 
			if ( typeof fid == "undefined" ){
				//debug( 'x'+ fid);
				fid = 1;
			//} else {
			//	debug( 'y'+ fid);
			}
		}
	}
	*/
	var ng = '';
	var l = '';
	//if ( $( "#mapwrapper" ).is(':hidden') )
	if ( shmap == 0 )
		ng = '&ng=1';	 
	if ( shlotw == 1 )
		l = '&l=1';	 

  	var url = '/xml/sk.php?s=' + lastspots + '&r=' + eval( tableid + 'r' ) + '&' + fargs + ng + l;
  	//var url = 's.php?s=' + lastspots + '&r=' + spotsr + '&d=1' + fid + ng;
	//debug('fid:' + fid + '<br>fargs: ' + fargs + '<br>url:' + url);

	$.ajax({
		url: url,
		type: 'GET',
		dataType: 'xml',
		timeout: spotsinterval - 1000,
		success: function(xml){
			process_xml_spots ( xml, tableid );
		}
	});
}


function spots_format( spotsformat ) {
//0 = current
//1 = classic
	//revert back to original
	if ( spotsformat == 0 ) {
		spf_css.attr('disabled', true);
		//$('link[href="/css/spf_classic.css"]').attr('disabled', true);
	} else {
		//spf_css = $('<link/>').attr({ 'rel': 'stylesheet', 'href':'/css/spf_classic.css'}).appendTo('head');
		//$('<link>').attr({ 'rel': 'stylesheet', 'type':'text/css', 'href':'/css/spf_classic.css'}).appendTo('head');
		//spf_css = $('head').append('<link rel="stylesheet" href="css/spf_classic.css" type="text/css" />');
		spf_css = $('<link rel="stylesheet" href="/css/spf_classic.css" type="text/css" />').appendTo('head');
	}
	return;
}
function update_data(div, data) {
        $("div#" + div).load(data);
}

