//La classe dérive de la classe Followmap et implante les méthodes nécessaires
// à l'usage des maps virtualEarth de Microsoft

MSMap.prototype = new Followmap();
MSMap.prototype.constructor = MSMap;
MSMap.prototype.baseClass = Followmap.prototype.constructor;
MSMap.prototype.loadMap = MSloadMap;
MSMap.prototype.DrawShape = MSDrawShape;
MSMap.prototype.centermap = MScentermap;
MSMap.prototype.remove = MSremove;
MSMap.prototype.ClearAll = MSClearAll;
MSMap.prototype.CenterOneCompet = MSCenterOneCompet;
MSMap.prototype.dotoggledisplay = MSdotoggledisplay;
MSMap.prototype.displayCheckpoints = MSdisplayTopPoints;
MSMap.prototype.erasePoints = MSErasepoints;
MSMap.prototype.dessineParcours = MSdessineParcours;
MSMap.prototype.traceCompet = MStraceCompet;
MSMap.prototype.erasetrace = MSerasetrace;
MSMap.prototype.redrawtrace = MSredrawtrace;
MSMap.prototype.onmousemove = onMouseMove;
MSMap.prototype.Clearmap = DoClearmap;

// Le constructeur
function MSMap(divname)
{
    this.baseClass(divname);
    this.vemap = null;
    this.interestPointsLayer = null;
    this.parcourslayer = null;
    this.positionslayer = null;
    this.tjrsvisiblelayer = null;
    this.shapesCollection = new Array(); // Tableau associatif de VEShape
}
//---------------------------------------------------------
// les fonctions propres à la classe
//---------------------------------------------------------
function DoClearmap()
{
    this.vemap.DetachEvent("onmousemove",this.onmousemove);
    this.vemap.DeleteControl(this.PositionControl);
}
//---------------------------------------------------------
function MSloadMap(style)
{
    this.vemap = new VEMap(this.divname);
    var mapforevent = this.vemap; // pour que le gestionnaire d'event ait la vemap

    this.interestPointsLayer = new VEShapeLayer();
    this.parcourslayer = new VEShapeLayer();
    this.positionslayer = new VEShapeLayer();
    this.tjrsvisiblelayer = new VEShapeLayer();
    
    this.vemap.LoadMap(new VELatLong(this.startLat,this.startLon),8, VEMapStyle.Road, false, VEMapMode.Mode2D, false, 1);
    this.vemap.AddShapeLayer(this.interestPointsLayer);
    this.vemap.AddShapeLayer(this.parcourslayer);
    this.vemap.AddShapeLayer(this.positionslayer);
    this.vemap.AddShapeLayer(this.tjrsvisiblelayer);
    
    this.tjrsvisiblelayer.Show();
    
    if(unitKm == true)
        this.vemap.SetScaleBarDistanceUnit(VEDistanceUnit.Kilometers);
    else
        this.vemap.SetScaleBarDistanceUnit(VEDistanceUnit.Miles);
        
    switch(style) {
        case "R" :this.vemap.SetMapStyle(VEMapStyle.Road);break;
        case "A" :this.vemap.SetMapStyle(VEMapStyle.Aerial);break;
        case "H" :this.vemap.SetMapStyle(VEMapStyle.Hybrid);break;
    }
    
    // pour enregistrer le changement de style
    this.vemap.AttachEvent("onchangemapstyle", onchangemapstyle);
        
    this.onmouseover = function(e) {
        if (e.elementID != null)
        {
            var shape = mapforevent.GetShapeByID(e.elementID);
            displayEventInfos(shape);
        }
    };

    // Passage sur un shape concurrent
   this.vemap.AttachEvent("onmouseover",this.onmouseover);
    
   // Affichage de la position courante
   this.vemap.AttachEvent("onmousemove",this.onmousemove);
   this.PositionControl = CreatePositionsControl(this.vemap);
   this.vemap.AddControl(this.PositionControl);
}
//---------------------------------------------------------
function CreatePositionsControl(map)
{
    var container = document.createElement("div");
    
    var id = document.createAttribute("id");
    id.nodeValue = "lLPositions";
    container.setAttributeNode(id);
        
    container.style.top = "10px";
    container.style.left = "400px";
    
    return container;
}
//---------------------------------------------------------
function displayEventInfos(shape)
{
    if (shape == null)
        return;
        
    if (shape.Type == "Polyline")
    {
       // shape.SetDescription(shape.Title);
    }
    else
    {
        var notes = shape.Notes;
        var pos = notes.indexOf("value=");
        if (pos != -1)
        {
            var alpha = notes.substr(pos+6,3);
            displayInfosFromPosis(posis[alpha]);
        }
    }
}
//---------------------------------------------------------
function onMouseMove(e)
{
    if (kindmap == "VE")
    {
        var x = e.mapX;
        var y = e.mapY;
        var pixel = new VEPixel(x, y);
        var lat = map.vemap.PixelToLatLong(pixel).Latitude
        var lng = map.vemap.PixelToLatLong(pixel).Longitude;

        var latLng = document.getElementById("lLPositions");
        latLng.innerText = gettextPositions(lat,lng);
    }
}
//---------------------------------------------------------
function onchangemapstyle(e)
{
    var style = e.mapStyle; // retour : a h r ou o
    
    switch(style)
    {
        case "R" : writeCookie(kindmap,"R");break;
        case "A" : writeCookie(kindmap,"A");break;
        case "H" : writeCookie(kindmap,"H");break;
    }
}
//---------------------------------------------------------
function MSredrawtrace(alpha)
{
    var posi = posis[alpha];
    var r = posi.r();
    var g = posi.g();
    var b = posi.b();

    var color = new VEColor(r,g,b,1.0);
    posi.polyline.SetLineColor(color);
}
//---------------------------------------------------------
function MSdisplayTopPoints(tps,context)
{
    var layer = null;
    var label = '';
    
    if (context == 'OPT')
    {
        layer = this.interestPointsLayer;
    }
    else
    {
        layer = this.tjrsvisiblelayer;
   }
   
    var iconSrc;
    for (var i = 0;i<tps.length;i++)
    {
        var point = new VELatLong(tps[i].lat,tps[i].longi);
        var points = new Array(point);
        var ashape = new VEShape(VEShapeType.Pushpin,points);
        label = tps[i].nom;
        var spanval = "<span style='color:black;position:relative;left:10px;top:10px;'>";
        switch (tps[i].kind)
        {
            case 10 : iconSrc = "green.png";break; // DSS
            case 11 : iconSrc = "start.ico";break; //START
            case 12 : iconSrc = "red.png";break; // Stop Chk ou ASS
            case 13 : iconSrc = "yellow.png";break; // Pit ou WP
            case 14 : iconSrc = "roadx.png";break; // Road X
            case 15 : iconSrc = "black.png";break; // CP
            case 21 : iconSrc = "finish.ico";break; //FINISH
            default:iconSrc = tps[i].imgName;break;
        }

        ashape.SetCustomIcon(spanval + "<img src='images/" + iconSrc + "'/></span>");
        ashape.SetTitle(tps[i].nom);
        layer.AddShape(ashape);
    //    this.vemap.SetMapView(layer.GetBoundingRectangle());
     }
}
//---------------------------------------------------------
function MSdessineParcours(route)
{
    var secteur = "";
    var points = new Array();
    var specialPoints = new Array();
    var color1 = new VEColor(0,50,255,1);
    var color2 = new VEColor(255,0,0,1);
    var color;
    
    this.parcourslayer.DeleteAllShapes();
    
    if (route.length > 0)
    {
        if (route[0].secteur==1)
            color = color1;
        else
            color = color2;
    }
    
    for (var i = 0;i<route.length;i++)
    {
        var point = new VELatLong(route[i].lat,route[i].longi);
        // On gère le changement de secteur
        if (route[i].secteur != secteur)     // début d'une nouvelle étape
        {

            if (points.length > 1)  // un tracé existe déjà, le dessiner
            {
                var line = new VEShape(VEShapeType.Polyline,points);
                line.HideIcon();
                line.SetLineColor(color);
                this.parcourslayer.AddShape(line);
                points = new Array();
            }
          secteur = route[i].secteur;
            if (secteur==1)
                color = color1;
            else
                color = color2;
        }
        
        points.push(point);
       if (route[i].kind > 1)
        {
            var shape = BuildSpecialShape(route[i],point);
            specialPoints.push(shape);
        }
        
        
    } // fin de boucle sur tous les points

    // Pour tracer l'étape en cours
    if (points.length > 0)
    {
        var line = new VEShape(VEShapeType.Polyline,points);
        line.HideIcon();
        line.SetLineColor(color);
        this.parcourslayer.AddShape(line);
        this.vemap.SetMapView(points);
    }
    
//   // On trace les points spéciaux
    for (var j=0; j< specialPoints.length;j++)
    {
        this.parcourslayer.AddShape(specialPoints[j]);
    }
}
//---------------------------------------------------------
function MSErasepoints(kind)
{
    if (kind == "ROUTE")
    {
        this.parcourslayer.DeleteAllShapes();
        Array.clear(route);
        route = null;
    }
    else if (kind == 'TOP')
    {
        this.interestPointsLayer.DeleteAllShapes();
        Array.clear(tps);
        tps = null;
   }
}
//---------------------------------------------------------
function BuildSpecialShape(gpt,point)
{
    var shape = new VEShape(VEShapeType.Pushpin,point);
    // Construire le pushpin selon la valeur de kind
    var kind = gpt.kind;
    
    return shape;
}//---------------------------------------------------------
function MSDrawShape(isReplay,alpha,nom,nom2,team,kind,id,lat,lng,speed,dt)
{
    var iconStr = "<img src='images/balise.png'/>" +
                  "<span style='background-color:Yellow;font-family:Arial; font-size:x-small;" +
                    "color:Black;position:relative;top:-30px;left:-30px'>" +
                    id + "</span>";
    var details = "Car # : " + id  + "<br/>Driver : " + nom + "<br/>Co driver : " + nom2 + "<br/>Team : " + team + "<br/>Type : " + kind + "<br/>Speed : " + speed;
    if (isReplay)
    {
        var hms = getHMS(dt);
        details += "<br/>Elapsed time : " + hms;
    }
    else
        details +=  "<br/>Date : " + dt;
    var title = nom + " " + id; 
    var point = new VELatLong(lat,lng);
    var points = new Array(point);
    var ashape = new VEShape(VEShapeType.Pushpin,points);
    ashape.SetCustomIcon(iconStr);
    ashape.SetTitle(title);
    ashape.SetDescription(details);
    this.positionslayer.AddShape(ashape);
    this.shapesCollection[alpha] = ashape;
}
//-----------------------------------------------------------
function MScentermap()
{
    var pointCollection = new Array();
    var count = 0;
    var id;
    
    // on compte le nombre de membres - les tableaux associatifs ne connaissent pas length
    for (id in this.shapesCollection) 
    {
        count ++;
    }
    
    if (count == 0)
    {
        return;
    }
    else if (count == 1)
    {
        this.CenterOneCompet(id);
    }
    else
    {/*
        for (shape in this.shapesCollection)
        {
            var velatlong = this.shapesCollection[shape].GetPoints()[0];    // 1 seul élément ds le tableau
            pointCollection.push(velatlong);
        }
        this.vemap.SetMapView(pointCollection);
        */
    }
    
    var maxzoom = 13;
    if (this.vemap.GetZoomLevel() > maxzoom)
        this.vemap.SetZoomLevel(maxzoom);
}
//-----------------------------------------------------------
function MSremove(id)
{
    var shape = this.shapesCollection[id];
    if (shape != undefined)
    {
        this.positionslayer.DeleteShape(shape);
        delete this.shapesCollection[id];
    }
}
//-----------------------------------------------------------
function MSClearAll()
{
    this.positionslayer.DeleteAllShapes();
}
//-----------------------------------------------------------
function MSCenterOneCompet(alpha)
{
    if (this.shapesCollection != null)
    {
        if (this.shapesCollection[alpha] != null)
        {
            var velatlong = this.shapesCollection[alpha].GetPoints()[0];
            if (velatlong != null)
                this.vemap.IncludePointInView(velatlong);
        }
    }
}
//-----------------------------------------------------------
function MSdotoggledisplay(cb)
{
    var layer;
    switch(cb.id)
    {
        case "dispCompets":layer = this.positionslayer;break;
        case "dispParcours":layer = this.parcourslayer;break;
        case "dispCheckpoints":layer = this.interestPointsLayer;break;
    }
    if (cb.checked)
    {
        layer.Show();
        this.vemap.SetMapView(layer.GetBoundingRectangle());
    }
    else
        layer.Hide();
}
//-----------------------------------------------------------
function MStraceCompet(posi,autozoom)
{
    var latlon;
    var pts = new Array();
    if (posi.points.length == 0)    // rien à dessiner
        return;
        
    for(var i =0; i <posi.points.length;i++)
    {
        var pt = posi.points[i];
        latlon = new VELatLong(pt.lat,pt.lng);
        pts.push(latlon);
    }
    
    if (posi.points.length == 1)
        pts.push(latlon);
        
    posi.polyline = new VEShape(VEShapeType.Polyline,pts);
    posi.polyline.HideIcon();
    if (posi.color != null)
    {
        var r = posi.r();
        var g = posi.g();
        var b = posi.b();

        var color = new VEColor(r,g,b,1.0);
        posi.polyline.SetLineColor(color);
    }
   
   // Description à n'afficher qu'avec hover
    //var details = "<iframe src='equipes/" + id + ".html'/><input type='hidden' value=" + alpha + "/>";
    var title = posi.nom + " " + posi.numId; 
    posi.polyline.SetTitle(title);
   // ashape.SetDescription(details);

    this.positionslayer.AddShape(posi.polyline);
    if (autozoom) {
        this.vemap.SetMapView(this.positionslayer.GetBoundingRectangle());
    }
}
//-----------------------------------------------------------
function MSerasetrace(posi) {
    if ((posi != null) && (posi.polyline != null)) {
        this.positionslayer.DeleteShape(posi.polyline);
        posi.polyline = null;
    }
}
if (typeof(Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();