
//trackId needed.

function appendTxt(text){
  document.getElementById("messageBox").value=document.getElementById("messageBox").value + "\n" + text;
}

ItiElement.prototype.age = 0;
ItiElement.prototype.poi = null;

ItiElement.prototype.firstCreateMarker = function(nextId){
    this.updateMarker();
}

ItiElement.prototype.updateMarker = function(){
    if(this.poi !=null && this.mark == null){
        var pi = getPoiIcon();
        var mark = new GMarker(this.gLatLng,  {draggable: false, icon : pi, bouncy : false, clickable : true});
        GEvent.addListener(mark, "click", this.pointClicked.bind(this));
        this.mark = mark;                                           
        map.addOverlay(this.mark);
    }
}

ItiElement.prototype.pointClicked = function() {
    currentPoi = this;
    displayPoi();
}






///////////////


function reloadB(){
    currentPoi = null;
    fastPanning=false;
    cleanReload();
}

function load() {
  var query=this.location.search.substring(1);
   
  var pos = query.indexOf("center=");
  var nxt = query.indexOf("&",pos+1);
  if(nxt== -1) nxt = query.length;
  var opt = query.substring(pos,nxt);

  var startZoom=5;
  pos = query.indexOf("zoom=");
  nxt = query.indexOf("&",pos+1);
  if(nxt== -1) nxt = query.length;
  if(pos != -1){  
     startZoom = parseInt(query.substring(pos+5,nxt));      
  }
  
  var mapType=0;
  pos = query.indexOf("mapType=");
  nxt = query.indexOf("&",pos+1);
  if(nxt== -1) nxt = query.length;
  if(pos != -1){  
     mapType = parseInt(query.substring(pos+8,nxt));      
  }
  
  appendTxt("load");  
  
  sideText();
  if(map == null){
        if (GBrowserIsCompatible()) {
          map = new GMap2(document.getElementById("map"));
          map.addControl(new GSmallMapControl());
          map.addControl(new GMapTypeControl());
          map.addControl(new GScaleControl());
          var type = G_NORMAL_MAP;
          switch(mapType) {
              case 1:
                 type = G_SATELLITE_MAP;
                 break;
              case 2:
                 type = G_HYBRID_MAP;
                 break;
          }
          setMapCenter(startZoom);
          map.setMapType(type);
  
          GEvent.addListener(map, "moveend", function() {
              mapMoved();
          });
        }
  }
  appendTxt("getting polygons");  
  getPolygons();
  appendTxt("endload");  
}

function setMapCenter(startZoom){
          map.setCenter(new GLatLng(46.51233422257656, 6.6378021240234375), startZoom);
}

var fastPanning = false;
function mapMoved(){
    appendTxt("map moved");
    if(!fastPanning){
        getPolygons();
    }
}


   
var startTime;
var formerZoomLevel = -1;


function displayPoi(){
   appendTxt("display poi : " + currentPoi.point.id + " inFrame : " + inFrame);
   if(currentPoi.poi.type == 0){
       currentPoi.mark.openInfoWindowHtml(currentPoi.poi.content);
       if(inFrame){
           window.open("about:blank",poi_target);
       } else {
           document.getElementById("poiInfo").innerHTML=""; 
       }
   } else {
       map.closeInfoWindow();
       if(inFrame){
           if(currentPoi.poi.type != 1){
               window.open(currentPoi.poi.content,poi_target);
           } else {
               window.open("http://www.petiteviree.com/googmap/getPoiContent.php?trackId=" + trackId + "&pointId=" + currentPoi.point.id,poi_target);
           }
       } else {
           var poiInfo = document.getElementById("poiInfo");
           currentPoi.poi.writeContentInDiv(poiInfo);
       }
   }
}

var lastPanOut;

function openGE(){
    window.open("sendKml.php?trackId="+trackId);;
}

function nextPoi(reload,defaultTargetZoom){
    var currentPointIdInChain = -1;
    var currentChainId = 0;
    if(currentPoi != null) {
        currentPointIdInChain = currentPoi.getIdInChain();
        currentChainId = currentPoi.chainId;
    }
    appendTxt("next poi " + currentPointIdInChain);
	for(var i = currentPointIdInChain + 1 ;i<chains[currentChainId].elements.length;i++){
	    if(chains[currentChainId].elements[i].poi != null){

                appendTxt("Moving : " + currentPointIdInChain + " to " + i);
		currentPoi = chains[currentChainId].elements[i]; 
                var g1 = currentPoi.gLatLng;
                var g2 = map.getCenter();
                var p1 = map.getCurrentMapType().getProjection().fromLatLngToPixel(g1,map.getZoom());
                var p2 = map.getCurrentMapType().getProjection().fromLatLngToPixel(g2,map.getZoom());
                appendTxt("size : " + (p2.x - p1.x) + " " + (p2.y - p1.y));
                var size = new GSize(p2.x - p1.x,p2.y - p1.y);
                map.panBy(size);

                var targetZoom = currentPoi.poi.zoom;
                if(targetZoom == 0){
                   targetZoom = defaultTargetZoom;
                }
                if(targetZoom == null){
                   targetZoom = map.getZoom();
                }
                lastPanOut = GEvent.addListener(map, "moveend", function() {
                     displayPoi();
                     GEvent.removeListener(lastPanOut);
                     setTimeout(function(){zoomingIn(map.getZoom(),targetZoom);},1000);
                   });
		
                return;
	    }
	}
    if(!reload){
      appendTxt("end and no reload.");
    } else {
      //if we are here : no next POI in map...
      var url = "nextPoiXml.php?trackId="+ trackId +"&pointId=" + currentPoi.point.id;
      fastPanning = true;
      appendTxt("going to next poi.. \n" + url);
      var cid = currentChainId;
      xmlRequest(url, function(request) { gotNextPoi(request, cid); });
    }  
}

var startTime;

function gotNextPoi(request,cid){
  if(request.readyState==4) {
   appendTxt("track to nxt poi loaded : " + ((new Date()).getTime() - startTime));
   var xml = request.responseXML;
   var zm=xml.getElementsByTagName("zoom"); //xml.documentElement
   if(zm==null ||zm.length == 0) {
      fastPanning = false;
      alert("last point reached");
      currentPoi = null;
      return;
   }
   appendTxt("parsed : " + (startTime - (new Date()).getTime()));
   var zoom = parseInt(zm[0].getAttribute("value"));
   appendTxt("zoom : " + zoom + " rz: " + zLevels[zoom][1] + " c:" + map.getZoom());
   var points = xml.getElementsByTagName("point");
   var poiEl =  xml.getElementsByTagName("poi");

   var pois = new Array();
   for (var pi = 0; pi < poiEl.length ; pi++) {
       var ptid = poiEl[pi].getAttribute("point_id");
       pois[ptid] = new Poi(poiEl[pi]);
   }

   var added = insertPointsIntoChain(points,cid,pois);
   appendTxt("added : " + added);
   var curZoom = map.getZoom();
   zoomingOut(curZoom,curZoom,zLevels[zoom][1]);  
  }
}

function zoomingOut(orgZoom,curZoom,targetZoom){
   if(curZoom > targetZoom) {
  //    curZoom--;
      curZoom-= 2;
      map.setZoom(curZoom);   
      setTimeout(function() {zoomingOut(orgZoom,curZoom,targetZoom);},1000);
   } else {
      nextPoi(false,orgZoom);
   }
}
function zoomingIn(curZoom,targetZoom){
   if(curZoom < targetZoom) {
  //    curZoom++; 
      curZoom += 2;
      map.setZoom(curZoom);   
      setTimeout(function() {zoomingIn(curZoom,targetZoom);},1000);
   } else {
      fastPanning = false;
      getPolygons();
   }
}


var currentPoi = null;
var insertionMode = false;

function loadXml(data,zLevel){

  var ldd = (new Date()).getTime() - startTime;
  var xml = data;
  var polys = xml.getElementsByTagName("polygon");
  appendTxt("load:" +  ldd + " parse:" + ((new Date()).getTime()- startTime) + " polys:" + polys.length);

  if(polys.length == 0 ) {
     if(xml.getElementsByTagName("track")[0].getAttribute("empty") != null){
         alert("No points in track " + trackId);
         return;
     }
  }

  insertPolygonsIntoChains(polys,zLevel,formerZoomLevel);

  formerZoomLevel = zLevel;
  
  appendTxt("Done : " + (startTime - (new Date()).getTime()));

  ageing();
  
}

function ok_xml(request){
 if(request.readyState==4) {
  appendTxt("req ok");
  appendTxt("-t:" + request.responseText);
  appendTxt("-x:" + request.responseXML);
 }
}

function ageing(){
       for(var j = 0; j < chains.length;j++){
             var chain = chains[j];
             var removing = false;
             for(var i = 0 ; i < chain.elements.length;i++){
                 chain.elements[i].age++;
                 if(chain.elements[i].age > 4){
                     if(chain.elements[i].mark != null) {
                            GEvent.clearInstanceListeners(chain.elements[i].mark);                          
                            map.removeOverlay(chain.elements[i].mark);
                     }
                     if(chain.elements[i].lineToPrevious != null)
                            map.removeOverlay(chain.elements[i].lineToPrevious);                                
                     chain.elements.splice(i,1);
                     i--;                       
                      
                     removing = true;

                 } else {
                     if(removing && i != 0){
                            //splitting chain
                            var nElements = chain.elements.splice(i,chain.elements.length);
                            chain.setExtremePointsId();
                            var c2 = new Chain();
                            c2.elements=nElements;
                            c2.setExtremePointsId();
                            chains.splice(j+1,0,c2);
                            updatePointsChainId(j+1);
                           
                      }
                      removing = false;
                 }
           }
             

           if(chain.elements.length == 0) {
                //Removing chain.
                appendTxt("removing chain in zoom out");
                chains.splice(j,1);
                updatePointsChainId(j);                        
                j--;
           } else {
                //TODO check the handling of cases where there .point == null 
                if(chain.elements[0].point != null){
                     chain.firstPointId = chain.elements[0].point.id;
                } else {
                     chain.firstPointId = -1;                        
                }
                chain.setExtremePointsId();
           }
     }
       
}
function sideText(){}

