//<![CDATA[
var copyOSM = new GCopyrightCollection("<a href='http://www.openstreetmap.org/'>OpenStreetMap</a>");
copyOSM.addCopyright(new GCopyright(1, new GLatLngBounds(new GLatLng(-90,-180), new GLatLng(90,180)), 0, " "));
var tiles1     = new GTileLayer(copyOSM, 1, 17, {tileUrlTemplate: 'http://tile.openstreetmap.org/{Z}/{X}/{Y}.png'});
var tiles2 = new GTileLayer(copyOSM, 1, 17, {tileUrlTemplate: 'http://kartat.02.fi/tiles/maps/fi_FI/{Z}/{X}/{Y}.png'});
var tiles3 = new GTileLayer(copyOSM, 1, 17, {tileUrlTemplate: 'http://kartat.02.fi/tiles/topographic/fi_FI/{Z}/{X}/{Y}.png'});
var mappi1 = new GMapType([tiles1],     G_NORMAL_MAP.getProjection(), "OSM");
var mappi2 = new GMapType([tiles2], G_NORMAL_MAP.getProjection(), "020202m");
var mappi3 = new GMapType([tiles3], G_NORMAL_MAP.getProjection(), "020202t");
var map = new GMap2(document.getElementById("map"), { mapTypes: [mappi1],size: new GSize(400,300) });
map.setUIToDefault();
map.setMapType(G_NORMAL_MAP);
map.setCenter( new GLatLng(38,-97), 3);


Cmarkers = [];
Clabels = [];
Cname = [];

Umarkers = [];
Ulabels = [];
Uname = [];

Mmarkers = [];
Mlabels = [];

Rmarkers = [];
Rlabels = [];
Rlines = [];

Rline = '';

Mediamarkers = [];
Medialabels = [];

marker = [];
label = [];
kahva = [];
ajoaika = [];
mediapoint = [];
mediafiles = [];

var ikkunal=0;
var ajo=0;
var routedrive = 0;
var driveline = 0;
var pistetta = '';
var driveon=0;
var stopmedia = 0;

var polyline;
var routepoints=0;
var drawroute=0;
var uptimer=0;
var status = "running";
var reload='3000';
var lastmsg='0';
var ohjetila='0';
var lukitus='0';
var ohitalukko = '0';
var lastup = 0;
var lastzoom = 0;
var aktiivivalinta = 0;
var sisaan = '';
var iidee=0;
var startti=0;

var siivoa=0;
var siivoa2=0;

var f_user='';
var f_follow = 0;

var chattilaskin = 0;
var liukuva="";
var viimchatviesti = 1;

var ulistshow=0;

var route='0';

var ikon = 'iko1';
iko1 = new GIcon(G_DEFAULT_ICON, "/images/pallo.gif");
iko1.shadow='';
iko1.iconSize = new GSize(10,10); 
iko1.iconAnchor = new GPoint(5,5); 


GEvent.addListener(map, "zoomend", function() { 
  var zoom = map.getZoom();
  if (zoom>10 ||(lastzoom >10 && zoom < 11)){
    MakeRefreshWait(1000,0);
  }
});

GEvent.addListener(map, "dragend", function() { 
  var zoom = map.getZoom();
  if (zoom>10){
    MakeRefreshWait(2000,0);
  }
});

readmaterial(0);


window.setTimeout(function(){refreshMap(map,'1')},100);


// =========================================================================================
// REFRESH MAP
// =========================================================================================
function refreshMap(map,mode){

  var now = new Date();
  var hours = now.getHours();
  var minutes = now.getMinutes();
  var seconds = now.getSeconds();
  if (minutes < 10){
    var aikana = hours + ":0" + minutes;
  }else {
    var aikana = hours + ":" + minutes;
  }
  tulosta ('kello','innerHTML',aikana);
 
  if (routedrive==1 && driveon==1){
    // skip refresh
  } else {
  serveri(1);

  var aika = parseInt(new Date().getTime().toString().substring(0, 10));
  var urli = "http://live.geocaching.com/last.txt?random=" +aika;
  var data2 = '';

  GDownloadUrl(urli, function(data2, responseCode) {
    if(responseCode == 200) {
      data2 = parseFloat(data2);
      if (data2 < lastup && mode == '1'){
	if (mode==1){
	  window.setTimeout(function(){ refreshMap(map,1)},reload);
	}
	serveri(0);
      } else {

	Stamp = new Date(); gh = Stamp.getHours(); gm=  Stamp.getMinutes(); gs=Stamp.getSeconds();
	if (gm < 10){gm = '0' + gm;}
	if (gs < 10){gs = '0' + gs;}
	var arvo = gh + ':' + gm + ':' + gs + ' '+reload/1000 + ' sec.';
	
	if (status == "stopped"){
	  window.setTimeout(function(){ refreshMap(map,1)},reload);
	  return;
	}
	
	var lat = map.getCenter().lat();
	var lon = map.getCenter().lng();
	var zoom = map.getZoom();
	var noshow1=1;
	var noshow2=1;
	var noshow3=1;
	var noshow4=1;
	var noshow5=1;
	if (document.lomake.noshow1.checked==true){noshow1=0;}
	if (document.lomake.noshow2.checked==true){noshow2=0;}
	if (document.lomake.noshow3.checked==true){noshow3=0;}
	if (document.lomake.noshow4.checked==true){noshow4=0;}
	if (document.lomake.noshow5.checked==true){noshow5=0;}
	var valinta = noshow1 + '|' + noshow2 + '|' + noshow3 + '|' + noshow4 + '|' + noshow5;
	var aktiivi = document.lomake.active.selectedIndex;
	var f_userco='';


	if (f_user != ''){
	  f_userco=escape(f_user);
	  f_user_old = f_user;	  
	}
	



	var lauseke = "?lng=&zoom=" + zoom + "&route=" + route + "&latin=" + lat + "&lonin=" + lon + "&active="+aktiivi+ "&valinta="+valinta + "&random=" +Math.random() + "&f_user="+f_userco + "&f_follow="+f_follow + "&mode="+mode + "&mark_show_list=&mista=&mihin=";
	
	lastup = parseInt(new Date().getTime().toString().substring(0, 10));

		

	var request = GXmlHttp.create();
	request.open("GET", "/xml.php"+lauseke, true);
	request.onreadystatechange = function() {

	  if (request.readyState == 4) {
	    
	    serveri(0);
	    
	    var xmlDoc = request.responseXML;
	    var markers = xmlDoc.documentElement.getElementsByTagName("marker");
	    
	    // REMOVE CACHES
	    if ((lastzoom >10 && zoom < 11) || siivoa2==1){
	      siivoa2=0;
	      while (Clabels.length) {
		map.removeOverlay(Clabels[0]);
		map.removeOverlay(Cmarkers[0]);
		Clabels.shift();
		Cmarkers.shift();
	      }
	      while (Cname.length) {
		var apu = Cname[0];
		marker[apu]='';
		Cname.shift();
	      }
	    }

	    // REMOVE USERS / SET 
	    if (minutes == 10 || minutes == 25 || minutes == 40 || minutes == 55){
	      if (seconds < 45){
		siivoa = 1;
	      }
	    }
	    


	    // REMOVE USERS
	    if (aktiivivalinta != aktiivi || mode==2 || siivoa==1){
	      siivoa=0;
	      // refresh users
	      while (Ulabels.length) {
		map.removeOverlay(Ulabels[0]);
		map.removeOverlay(Umarkers[0]);
		Ulabels.shift();
		Umarkers.shift();
	      }
	      while (Uname.length) {
		var apu = Uname[0];
		marker[apu]='';
		Uname.shift();
	      }
	    }

	    // REMOVE MARKED (FLAGS)	    
	    var remove=0;
	    if (remove=='1'){
	      if (mode == 2){
		while (Mlabels.length) {
		  map.removeOverlay(Mlabels[0]);
		  map.removeOverlay(Mmarkers[0]);
		  Mlabels.shift();
		  Mmarkers.shift();
		}
	      }
	    }
	    

	    lastzoom = zoom;
	    aktiivivalinta = aktiivi;
	    
	    for (var i = 0; i < markers.length; i++) {
	      
	      var point = new GLatLng(parseFloat(markers[i].getAttribute("lat")),parseFloat(markers[i].getAttribute("lng")));
	      var tyyppi = markers[i].getAttribute("tyyppi");
	      var tieto = markers[i].getAttribute("tieto");
	      var arvo = markers[i].getAttribute("arvo");


	      // OHJAUS BEGIN
	      if (tyyppi=='OHJAUS'){

		if(tieto=="ROUTEPOINTS"){
                  routepoints=arvo;
                }
				
		if(tieto=="RELOAD"){
		  reload=arvo;
		}
		
		if (tieto == "ALARM"){
		  var data = arvo.split('@@@');
		  if (data[0] != lastmsg){
		    alert(data[1]);
		    lastmsg = data[0];
		  }
		}
		
		if(tieto=="FAKTA"){
		  var moniko =  arvo;
		  tulosta ('datainfo','innerHTML',moniko);
		}

		if (tieto=="USERLISTA"){
		  tulosta ('userlista','innerHTML',arvo);
		}
		
		if (tieto=="CHAT"){
		  tulosta ('chatti','innerHTML',arvo);
		}

		if (tieto=="CHATLATEST"){
		  var data = arvo.split('@@@');
		  if (viimchatviesti < 1){
		    viimchatviesti = data[0];
		    clearTimeout(liukuva);
		  }else if (data[0] > viimchatviesti){
		    clearTimeout(liukuva);
		    viimchatviesti=data[0];
		    chattilaskin=400;
		    tulosta ('newchat','innerHTML',data[1]);
		    Chatliuku(map);
		  }
		}
		
	      }
	      // OHJAUS END	      

	      // MARK BEGIN
	      if (tyyppi=='MARK'){
		
		var data = arvo.split('@@@');


		
		var f_user2=f_user.toLowerCase();
		var tieto2=tieto.toLowerCase();
		if (f_follow == '1' &&  f_user2 == tieto2 && mode=='2'){

		  map.setCenter(point,13);
		  tulosta ('message','innerHTML',data[6]);

		} else if (data[8] == mode){

		  map.setCenter(point,13);
		  map.setCenter(point);
		  tulosta ('message','innerHTML',data[6]);

		} else if (f_follow == '1' && f_user2 == tieto2){

		  map.setCenter(point);
		  tulosta ('message','innerHTML',data[6]);
		}
		addMarker(point,tyyppi,tieto,arvo);
	      }
	      // MARK END	      


	    }
	  }
	}
	
	if (mode==1){
	  window.setTimeout(function(){ refreshMap(map,1)},reload);
	}
	
        if (route==1){
          route=0;
          MakeDrawRouteWait(map);
        }
	
	request.send(null);
	
      }
    }
  });
  }  
}

// =========================================================================================
// ADD AND/OR UPDATE MARKER
// =========================================================================================
function addMarker(point,tyyppi,tieto,arvo){

  var data = arvo.split('@@@');

  var ikon = 'iko';
  ikon = new GIcon(G_DEFAULT_ICON, "/images/empty.gif");
  ikon.shadow='';
  ikon.iconSize = new GSize(data[1],data[2]); 
  ikon.iconAnchor = new GPoint(data[3],data[4]);
  ikon.imageMap = [
		   0,0,0,100,100,100,100,0
  ];

  var mikon = 'iko';
  mikon = new GIcon(G_DEFAULT_ICON, "/images/lippu_r.gif");
  mikon.shadow='';
  mikon.iconSize = new GSize(data[1],data[2]); 
  mikon.iconAnchor = new GPoint(data[3],data[4]);


  var routeicon = 'iko';
  routeicon = new GIcon(G_DEFAULT_ICON, "/images/routepoint.gif");
  routeicon.shadow='';
  routeicon.iconSize = new GSize(data[1],data[2]);
  routeicon.iconAnchor = new GPoint(data[3],data[4]);


  // READ MARKER ID (IF POSSIBLE)
  if (data[10] && data[10] != '0'){
    var nimike = data[10];
  }else {
    nimike = data[8];
  }
  
  if (nimike < 0){
    nimike = 'x';
  }

  if (marker[nimike] && nimike != 'x'){

    // MOVE MARKER START (MARKER EXISTS)
    var p1 =marker[nimike].getPoint().lat();
    var p2 =marker[nimike].getPoint().lng();
    var p3 = point.lat().toFixed(6);
    var p4 = point.lng().toFixed(6);
    if (p1 != p3 || p2 != p4){
      marker[nimike].setPoint(point);
      label[nimike].setPoint(point);
    }
    label[nimike].setContents(data[5]);
    GEvent.removeListener(kahva[nimike]);
    kahva[nimike] = GEvent.addListener(marker[nimike], "mouseover", function() {
      tulosta ('message','innerHTML',data[6]);
    });
    // MOVE MARKER END
    
  } else {

    // CREATE MARKER (MARKER NOT EXISTS)

    label[nimike]=new ELabel(point, data[5], null, new GSize(-5,7), data[0], 1);
    map.addOverlay(label[nimike]);
    
    if (data[7] == 0) {
      
      // CACHE (value '0')
      marker[nimike] = new GMarker(point,ikon);
      map.addOverlay(marker[nimike]);
      
      kahva[nimike] = GEvent.addListener(marker[nimike], "mouseover", function() {
	tulosta ('message','innerHTML',data[6]);
      });
      
      Cmarkers.push(marker[nimike]);
      Clabels.push(label[nimike]);
      Cname.push(nimike);      
      

    } else if (data[7] == 1){
      
      //USER
      marker[nimike] = new GMarker(point,ikon);
      map.addOverlay(marker[nimike]);

      kahva[nimike] = GEvent.addListener(marker[nimike], "mouseover", function() {
	tulosta ('message','innerHTML',data[6]);
      });

      // merkki

      
      Umarkers.push(marker[nimike]);
      Ulabels.push(label[nimike]);
      Uname.push(nimike);
      
    } else  if (data[7] == 2){

      // MOVABLE MARKERS
      marker[nimike] = new GMarker(point,{icon: mikon, draggable: true});
      marker[nimike].icon=ikon;
      GEvent.addListener(marker[nimike], "mouseover", function() {
	if (lukitus == 0){
	  tulosta ('message','innerHTML',data[6]);
	  var lue =marker[nimike].getPoint();
	  var latLngStr6 = lue.y.toFixed(6);
	  var lonLngStr6 = lue.x.toFixed(6);
	  var apu1= 'lat' + data[9];
	  tulosta(apu1,'value',latLngStr6);
	  var apu2= 'lon' + data[9];
	  tulosta(apu2,'value',lonLngStr6);
	}
      });
      GEvent.addListener(marker[nimike], "click", function() {
	lukitus = 1;
	markerpicture(marker[nimike],1);
	savecancelmode(data[9],1);
      });
      GEvent.addListener(marker[nimike], "dragstart", function() {
	//	lukitus = 1;
	//	markerpicture(marker[nimike],1);
	//	var apu1= 'save' + data[9];
	//	eval('document.getElementById("'+apu1+'").style.visibility="visible"');
	//	var apu1= 'canc' + data[9];
	//eval('document.getElementById("'+apu1+'").style.visibility="visible"');
	//savecancelmode(data[9],1);
      });
      GEvent.addListener(marker[nimike], "dragend", function() {
	ohitalukko=1;
	var lue =marker[nimike].getPoint();
	var latLngStr6 = lue.y.toFixed(6);
	var lonLngStr6 = lue.x.toFixed(6);
	var apu1= 'lat' + data[9];
	tulosta(apu1,'value',latLngStr6);
	var apu2= 'lon' + data[9];
	tulosta(apu2,'value',lonLngStr6);
	ohitalukko=0;
      });
      map.addOverlay(marker[nimike]);
      Mmarkers.push(marker[nimike]);
      Mlabels.push(label[nimike]);
      
      
    } else  if (data[7] == 3){

      // MEDIAMARKERS
      marker[nimike] = new GMarker(point,ikon);
      Mediamarkers.push(marker[nimike]);
      Medialabels.push(label[nimike]); 
      map.addOverlay(marker[nimike]);

      kahva[nimike] = GEvent.addListener(marker[nimike], "mouseover", function() {
	tulosta ('message','innerHTML',data[6]);
      });


    } else  if (data[7] == 4){

      // ROUTEPOINT
      marker[nimike] = new GMarker(point,routeicon);
      map.addOverlay(marker[nimike]);

      kahva[nimike] = GEvent.addListener(marker[nimike], "mouseover", function() {
	tulosta ('message','innerHTML',data[6]);
      });

      Rmarkers.push(marker[nimike]);
      Rlabels.push(label[nimike]);

   } 
  
  }
  // CREATE MARKER END
  
}


// =========================================================================================
// MOVABLE MARKER
// =========================================================================================
function markerpicture(marker,mode){
    for (i=0; i < Mmarkers.length; i++){
      if (mode==1){
      Mmarkers[i].setImage("/images/lippu_g.gif");
      } else {
      Mmarkers[i].setImage("/images/lippu_r.gif");
      } 
    }
    if (mode != 2){
      marker.setImage("/images/lippu_y.gif");
    }
}

// =========================================================================================
// READ USER MATERIAL FROM XML 
// =========================================================================================
function readmaterial(kenen){
  var urli = '/xml.php?material='+kenen;
  var request = GXmlHttp.create();
  request.open("GET", urli, true);
  request.onreadystatechange = function() {
    if (request.readyState == 4) {
      var xmlDoc = request.responseXML;
      var markers = xmlDoc.documentElement.getElementsByTagName("marker");
      for (var i = 0; i < markers.length; i++) {
	var tieto = markers[i].getAttribute("tieto");
	var arvo = markers[i].getAttribute("arvo");
	if (tieto == "QIK"){
	  tulosta ('qik','innerHTML',arvo);
	} else if (tieto == "PIC"){
	  tulosta ('lastpic','innerHTML',arvo);
	} else if (tieto == "MEDIA"){
	  tulosta ('media','innerHTML',arvo);
	} else if (tieto == "MEDIAHEAD"){
	  tulosta ('mediahead','innerHTML',arvo);
	} else if (tieto == "LOGS"){
	  tulosta ('loggaus','innerHTML',arvo);
	}
      }
    }
  }

  request.send(null);	
}
  
// =========================================================================================                    
// SET DRAW ROUTE WAIT TIMER
// =========================================================================================                    
function MakeDrawRouteWait(map){
  clearTimeout(drawroute);
  drawroute= window.setTimeout(function(){DrawRouteWait(map)},100);
}

// =========================================================================================                    
// DRAW ROUTE WAIT TIMER (MAKE DELAY UNTIL ROUTEPOINTS IS OK)
// =========================================================================================                    
function DrawRouteWait(map){
  clearTimeout(drawroute);
  if (Rmarkers.length == routepoints && routepoints > 0){
    renderLine(map);
  } else {
    drawroute= window.setTimeout(function(){DrawRouteWait(map)},100);
  }
}

// =========================================================================================
// SET REFRESH MAP FUNCTION TIMER
// =========================================================================================
function MakeRefreshWait(odotus,mode){
  clearTimeout(uptimer);
  uptimer= window.setTimeout(function(){RefreshWait(mode)},odotus);
}

// =========================================================================================
// REFRESH MAP FUNCTION TIMER
// =========================================================================================
function RefreshWait(mode){
  refreshMap(map,mode);
  clearTimeout(uptimer);
}


// =========================================================================================                    
// NEW CHAT MESSAGE INFO WINDOW TIMER
// =========================================================================================                    
 function Chatliuku(map){
   
   clearTimeout(liukuva);
  
   chattilaskin = chattilaskin - 10;

   var apulaskin1=chattilaskin;
   if (apulaskin1>100){
     apulaskin1=100;
   }
   var apulaskin2=apulaskin1 / 100;  
  
   if(document.layers){
     eval('document.layers["newchat"].filters.alpha.opacity="'+apulaskin1+'";');
   } else if(document.all){
     eval('document.all.newchat.style.opacity="'+apulaskin2+'";');
     eval('document.all.newchat.filters.alpha.opacity="'+apulaskin1+'";');
   } else if (!document.all && document.getElementById){
     eval('document.getElementById("newchat").style.opacity="'+apulaskin2+'";');
   }

   if (chattilaskin > 0){
     liukuva = window.setTimeout(function(){Chatliuku(map)},100);
   }
}


// =========================================================================================                    
// RENDER LINE FROM RMARKERS
// =========================================================================================                    
function renderLine(map){

  for (i=0; i < Rmarkers.length; i++){
    Rlines.push(Rmarkers[i].getPoint());
  }
  Rline = new GPolyline(Rlines,"#0000FF", 1, 1);
  map.addOverlay(Rline);
}


// =========================================================================================
// SEARCH USER
// =========================================================================================
function userhaku (mika){
  refreshMap(map,mika);
}


// =========================================================================================
// START USER FOLLOW
// =========================================================================================  
function startfollow (sisaan){
  map.closeInfoWindow();
  var urli = '/message.php?getsid='+sisaan;
  GDownloadUrl(urli, function(data, responseCode) {
    if(responseCode == 200) {
      tulosta ('followname','innerHTML','Följer nu: ' + data + ' <font face=\'verdana\' size=2>[<a href=\'\' onclick=\'javascript:stopfollow(); return false;\'>Sluta följ</a>]');
      f_user=data;
      f_follow=1;
    }
  });
  MakeRefreshWait(10,2);
  siivoa = 1;
}

// =========================================================================================
// STOP USER FOLLOW
// =========================================================================================  
function stopfollow (){
  map.closeInfoWindow();
  tulosta ('followname','innerHTML','Följer inte');
  f_user='';
  f_follow=0;
  MakeRefreshWait(10,2);
}


// =========================================================================================
// SEND MESSAGE TO USER / START WRITING (READ USER NAME)
// =========================================================================================
function sendmsg(iidee){
  
  var urli = '/message.php?getsid='+iidee;
  GDownloadUrl(urli, function(data, responseCode) {
    if(responseCode == 200) {
      tulosta ('usertoname','innerHTML',data)
	}
  });
  tulosta ('msgrcv','value',iidee);
  document.getElementById("boxmess").style.visibility="visible";
  
}

// =========================================================================================
// SEND MESSAGE TO USER / DO IT
// =========================================================================================
function talteen(){

  var kenelle = document.getElementById("msgrcv").value;
  //  var viesti =  document.getElementById("writemsg").value;  
  var viestia =  document.getElementById("writemsg").value;
  document.getElementById("boxmess").style.visibility="hidden";
  var urli = '/message.php?whosid='+kenelle+'&msg=' +viestia;
  tulosta ('writemsg','value','');
  GDownloadUrl(urli, function(data, responseCode) {
  });
  alert ('meddelande sänt');

}

// =========================================================================================
// SEND MESSAGE TO USER / CANCEL
// =========================================================================================
function cancelmsg(){

  tulosta ('writemsg','value','');
  document.getElementById("boxmess").style.visibility="hidden";

}

// =========================================================================================
// SEND MESSAGE TO WWW-MAP
// =========================================================================================
function sendwww(){

  var viestia =  document.getElementById("sano").value;
  viestia = escape(viestia);
  var urli = '/saywww.php?msg=' +viestia;
  tulosta ('writemsg','value','');
  GDownloadUrl(urli, function(data, responseCode) {
  });
  tulosta ('sano','value','');
  MakeRefreshWait(100,0);
}

// =========================================================================================
// SHOW AND HIDE HELP (NOT USED?)
// =========================================================================================
function ohjeistus (mika){
  if (ohjetila == 0){
    ohjetila = 1;
    tulosta ('ohjeet','value','Gömd');
    document.getElementById("ohjebox").style.visibility="visible";
  } else {
    ohjetila = 0;
    tulosta ('ohjeet','value','Kartinformation');
    document.getElementById("ohjebox").style.visibility="hidden";
  }
}

// =========================================================================================
// SHOW AND HIDE HELP (NOT USED?)
// =========================================================================================
function ulistcontrol (){
  
  if (ulistshow == 0){
    ulistshow=1;
    tulosta ('ulistactrl','innerHTML','<a href=\'\' onclick=\'javascript:ulistcontrol();return false;\'><img src=\'/images/list_close.gif\' border=0></a>');
    tulosta ('userlista','style.visibility','visible');
  } else {
    ulistshow=0;
    tulosta ('ulistactrl','innerHTML','<a href=\'\' onclick=\'javascript:ulistcontrol();return false;\'><img src=\'/images/list_open.gif\' border=0></a>');
    tulosta ('userlista','style.visibility','hidden');
  }
  
}



// =========================================================================================
// ZOOM MAP / STEET & CITY -BUTTONS
// =========================================================================================
function zoommap(arvo){

  if (arvo == 1){
    map.setZoom(13);
  } 
  if (arvo==2){
    map.setZoom(10);
  }

}

// =========================================================================================
// SAVE MOVABLE MARKERS
// =========================================================================================
function reittipistetalletus(numero,mode){

  if (mode==1){
    var apu1= 'lat' + numero;
    var apu2= 'lon' + numero;
    var apu3='kuvaus' + numero;
    var latarvo = eval('document.getElementById("'+apu1+'").value');
    var lonarvo = eval('document.getElementById("'+apu2+'").value');
    var kuvarvo = eval('document.getElementById("'+apu3+'").value');

    //  document.getElementById("boxmess").style.visibility="hidden";
    var urli = '/xml.php?action=saveowncoord&latin='+latarvo+'&lonin='+lonarvo+'&kuvaus='+kuvarvo+'&savid='+numero;
    
    GDownloadUrl(urli, function(data, responseCode) {
    });
  } 
  savecancelmode(numero,0);
  markerpicture(0,2);
  lukitus=0;
  window.setTimeout(function(){refreshMap(map,'2')},100);

};



// =========================================================================================
// SHOW MAP -SELECTION CHANGED
// =========================================================================================
function noshowchange(){

  if (document.lomake.noshow4.checked==true){
    tulosta ('usere','style.visibility','visible');
  } else {
    tulosta ('usere','style.visibility','hidden');
  }
  if (document.lomake.noshow5.checked==true){
    tulosta ('cachee','style.visibility','visible');
  } else {
    tulosta ('cachee','style.visibility','hidden');
  }

  siivoa=1;
  siivoa2=1;
  MakeRefreshWait(1000,0);
}


// =========================================================================================
// MOVABLE MARKERS - PART WHAT DO SOMETHING...
// =========================================================================================
function savecancelmode(numero,mode){
  var apu1= 'save' + numero;
  var apu2= 'canc' + numero;
  var apu3= 'lat' + numero;
  var apu4= 'lon' + numero;
  var apu5= 'kuvaus' + numero;

  if (mode==0){

    eval('document.getElementById("'+apu1+'").style.visibility="hidden"');
    eval('document.getElementById("'+apu2+'").style.visibility="hidden"');    
    eval('document.getElementById("'+apu3+'").disabled=1');    
    eval('document.getElementById("'+apu4+'").disabled=1');    
    eval('document.getElementById("'+apu5+'").disabled=1');    
 
  } else {

    eval('document.getElementById("'+apu1+'").style.visibility="visible"');
    eval('document.getElementById("'+apu2+'").style.visibility="visible"');    
    eval('document.getElementById("'+apu3+'").disabled=0');    
    eval('document.getElementById("'+apu4+'").disabled=0');    
    eval('document.getElementById("'+apu5+'").disabled=0');    

  }

}    


// =========================================================================================
// EXTRA ROUTE / DRAW
// =========================================================================================
function piirrareitti(iidee){
  map.closeInfoWindow();
  tyhjaareitti();
  var aika = parseInt(new Date().getTime().toString().substring(0, 10));
  var urli = '/xml.php?random='+aika+'&routeid='+iidee+"&action=noinfo%2C1%2Cczoom%2C3";
  var request = GXmlHttp.create();
  request.open("GET", urli, true);
  request.onreadystatechange = function() {
    if (request.readyState == 4) {
      var xmlDoc = request.responseXML;
      var markers = xmlDoc.documentElement.getElementsByTagName("marker");
      for (var i = 0; i < markers.length; i++) {
	var point = new GLatLng(parseFloat(markers[i].getAttribute("lat")),parseFloat(markers[i].getAttribute("lng")));
	var tyyppi = markers[i].getAttribute("tyyppi");
	var tieto = markers[i].getAttribute("tieto");
	var arvo = markers[i].getAttribute("arvo");
	if (tieto == "ROUTE"){
	  //	  var polyOptions = {geodesic:true};
	  eval('polyline = new GPolyline(['+arvo+'], "#000030", 3);');
	  map.addOverlay(polyline);
	  var value = polyline.getLength();
	  value = value / 1000;
	  value = Math.round(value*10)/10;
	  var message = value + " km";
	  tulosta('routedata','innerHTML',message);
	  if (driveline){
	    clearTimeout(driveline);
	  }
	  if (routedrive == 1){
	    ajo=9999999;
	    driveline= window.setTimeout(function(){drive(polyline)},20);
	  }
	  document.getElementById("routedatax").style.visibility="visible";
	} else if (tieto == "ROUTEAJAT"){
	  ajoaika = arvo.split('@@@');
	} else if (tieto == "MEDIAFILE"){
	  mediapoint = arvo.split('@@@');
	} else if (tieto == "MEDIAOUT"){
	  mediafiles = arvo.split('@@@');
	} else {
	  addMarker(point,tyyppi,tieto,arvo);
	}
      }
    }    
  }    
  request.send(null);
}  

// =========================================================================================
// EXTRA ROUTE / REMOVE
// =========================================================================================
function tyhjaareitti(){
  if (driveline){
    clearTimeout(driveline);
  }
  if (pistetta){
    map.removeOverlay(pistetta);
  }
  if (polyline){
    map.removeOverlay(polyline);
  }
  while (Medialabels.length) {
    map.removeOverlay(Medialabels[0]);
    map.removeOverlay(Mediamarkers[0]);
    Medialabels.shift();
    Mediamarkers.shift();
  }
  document.getElementById("routedatax").style.visibility="hidden";
  document.getElementById("routectrl").style.visibility="hidden";
}


// =========================================================================================
// DRIVE ROUTE
// =========================================================================================
function drive(polyline){
  var alkuko=0;
  if (ajo == 9999999){
    ajo =  polyline.getVertexCount();
    ajo=ajo-1;
    map.setZoom(13);
    alkuko=1;
    document.getElementById("routectrl").style.visibility="visible";
    driveon=1;
  }
  eval('var p1 = polyline.getVertex('+ajo+').lat();');
  eval('var p2 = polyline.getVertex('+ajo+').lng();');
  map.setCenter( new GLatLng(p1,p2));
  tulosta ('ajokello','innerHTML',ajoaika[ajo]);
  if (alkuko == 1){

    pistetta = new GMarker(new GLatLng(p1,p2),iko1);
    map.addOverlay(pistetta);
  } else {
    pistetta.setPoint(new GLatLng(p1,p2));

  }
  if (ajo == 0){
    if (driveon==1){
      clearTimeout(driveline);
      routedrive=0;
      window.setTimeout(function(){refreshMap(map,'1')},100);
    }
  } else {
    clearTimeout(driveline);
    if (driveon == 1){
      if (mediapoint[ajo] == 1 && stopmedia == 1){
	driveon=0;
	var ulos=mediafiles[ajo] + '<br><a href="" onclick="javascript:continueplay(); return false;">Continue</a>';
	pistetta.openInfoWindowHtml(ulos);
	ikkunal = GEvent.addListener(map.getInfoWindow(), "closeclick", function() {
	  continueplay();
	});
      } else {
	ajo = ajo - 1;
	driveline= window.setTimeout(function(){drive(polyline)},200);
      }
    }
  }
}

// =========================================================================================
// DRIVE ROUTE / CONTINUE PLAY (SET VARIABLES AND TIMER)
// =========================================================================================  
function continueplay(){
  if (ikkunal){
    GEvent.removeListener(ikkunal);
  }
  map.closeInfoWindow();
  driveon=1;
  ajo=ajo-1;
  driveline=window.setTimeout(function(){drive(polyline)},10);
}

// =========================================================================================
// DRIVE ROUTE / CONTROL BUTTONS
// =========================================================================================  
function routecontrol(toimi){

  if (toimi==1){  // prev10
    ajo=ajo+10;
  } else if (toimi==2){ // prev1
    ajo=ajo+1;
  } else if (toimi==3){ // next1
    ajo=ajo-1;
  } else if (toimi==4){ //next10
    ajo=ajo-10;
  } else if (toimi==10){ // stop
    if (driveline){
      clearTimeout(driveline);
    }
    driveon=0;
  } else if (toimi==11){ // play
    driveon=1;
  }

  if (toimi<10){
    driveon=0;
  }

  if (toimi != '10'){
    if (ajo<0){
      ajo=0;
    }
    var  maksi =  polyline.getVertexCount() -1;
    if (ajo > maksi){
      ajo=maksi;
    }    
    driveline=window.setTimeout(function(){drive(polyline)},10);
  }
}



// =========================================================================================
// PRINT VALUE TO GIVEN DIV
// =========================================================================================
function tulosta (kentta,modez,what){
  
  if (lukitus == 0 || ohitalukko == 1){
    if(document.layers){
      eval('document.layers["'+kentta+'"].'+modez+'="'+what+'";');
    } else if(document.all){
      eval('document.all.'+kentta+'.'+modez+'="'+what+'";');
    } else if (!document.all && document.getElementById){
      eval('document.getElementById("'+kentta+'").'+modez+'="'+what+'";');
    }  
  }

}


// =========================================================================================
// CONTROL SERVER INDICATOR
// =========================================================================================
function serveri(tila){

  if (tila == 0){
    document.getElementById("loading").src='/images/empty.gif';
  } else {
    document.getElementById("loading").src='/images/loading2.gif';
  }

}



//]]>


