// InitJS.js
// Contient le code javascript pour gérer le comportement de Ajax Map de PTV
//
// 22 avril 2008
// <%= Session("VariableName")%>
map = null;
ajaxmapURL="http://94.23.35.132/ajaxmaps-2.5.6/";

mapPlanif = null;
mapRapport = null;
bFirst = true;
heightImageSynop=100;
poiLayer = null;
zoneLayer = null;
floaterLayer = null;
var iNbStepEnvoye;
var iNbStepRecu;

var displayElement;
var units;
var points = new Array();
var xmappoints = new Array();
var iPlanif;
var iRapportNbLocation;
var xmappointsPlanif;
var xmapsteps;
var iPOIPlanif;
var xmappointsRapport;
var PTS;
var iRapportPointSelected;
var iNbRapportLocation;
var iNbRequestSent;
var iNbRequestReceived;
var geoUnits = new Array();
var locations = new Array();
var typepois = new Array();
var zones = new Array();
var pois = new Array();
var idCircle;
var lastRapportHisto;
var indexMenuToDisplay=-1;
var map;

    var idcenter;
    var idrayon;
    var centerX;
    var centerY;
    var ipPoints;

    
window.onload=pageLoad;
window.onresize=pageResize;
onresize=pageResize;

var CPH="ctl00$ContentPlaceHolder1$";
var CPH_="ctl00_ContentPlaceHolder1_";

var MASTER_PREFIX="ctl00_";
//ctl00_ContentPlaceHolder1_IB_NavTop
//ctl00_ContentPlaceHolder1_panSearchAddress
var menu_selected; //=0;
var menu_names = new Array("menuitem1", "menuitem2","menuitem3","menuitem4",
                           "menuitem5","menuitem6","menuitem7","menuitem8","menuitem9");
var menu_URLNormal = new Array(
                        "App_Themes/default/Images/menu_item1_n.png",
                        "App_Themes/default/Images/menu_item2_n.png",
                        "App_Themes/default/Images/menu_item3_n.png",
                        "App_Themes/default/Images/menu_item4_n.png",
                        "App_Themes/default/Images/menu_item5_n.png",
                        "App_Themes/default/Images/menu_item6_n.png",
                        "App_Themes/default/Images/menu_item7_n.png",
                        "App_Themes/default/Images/menu_item8_n.png",
                        "App_Themes/default/Images/menu_item9_n.png");

var menu_URLOver = new Array(
                        "App_Themes/default/Images/menu_item1_s.png",
                        "App_Themes/default/Images/menu_item2_s.png",
                        "App_Themes/default/Images/menu_item3_s.png",
                        "App_Themes/default/Images/menu_item4_s.png",
                        "App_Themes/default/Images/menu_item5_s.png",
                        "App_Themes/default/Images/menu_item6_s.png",
                        "App_Themes/default/Images/menu_item7_s.png",
                        "App_Themes/default/Images/menu_item8_s.png",
                        "App_Themes/default/Images/menu_item9_s.png");

var menu_URLSelect = new Array(
                        "App_Themes/default/Images/menu_item1_s.png",
                        "App_Themes/default/Images/menu_item2_s.png",
                        "App_Themes/default/Images/menu_item3_s.png",
                        "App_Themes/default/Images/menu_item4_s.png",
                        "App_Themes/default/Images/menu_item5_s.png",
                        "App_Themes/default/Images/menu_item6_s.png",
                        "App_Themes/default/Images/menu_item7_s.png",
                        "App_Themes/default/Images/menu_item8_s.png",
                        "App_Themes/default/Images/menu_item9_s.png");
var url_base = ""; //"http://www.galilesat.com/";
var icons_red = new Array(
                        url_base + "App_Themes/default/Images/voiture_r3.png",
                        url_base + "App_Themes/default/Images/fourgon_r3.png",
                        url_base + "App_Themes/default/Images/camion_r3.png",
                        url_base + "App_Themes/default/Images/ambulance_r3.png",
                        url_base + "App_Themes/default/Images/benne_r3.png",
                        url_base + "App_Themes/default/Images/toupie_r3.png",
                        url_base + "App_Themes/default/Images/camion2_r3.png",
                        url_base + "App_Themes/default/Images/bus_r3.png",
                        url_base + "App_Themes/default/Images/taxi_r3.png",
                        url_base + "App_Themes/default/Images/personne_r3.png",
                        url_base + "App_Themes/default/Images/utilitaire_r3.png",
                        url_base + "App_Themes/default/Images/moto_r3.png",
                        url_base + "App_Themes/default/Images/pelleteuse_r3.png",
                        url_base + "App_Themes/default/Images/fauteuil_roulant_r3.png",
                        url_base + "App_Themes/default/Images/personal_tracker_r3.png");
var icons_green = new Array(
                        "App_Themes/default/Images/voiture_v3.png",
                        "App_Themes/default/Images/fourgon_v3.png",
                        "App_Themes/default/Images/camion_v3.png",
                        "App_Themes/default/Images/ambulance_v3.png",
                        "App_Themes/default/Images/benne_v3.png",
                        "App_Themes/default/Images/toupie_v3.png",
                        "App_Themes/default/Images/camion2_v3.png",
                        "App_Themes/default/Images/bus_v3.png",
                        "App_Themes/default/Images/taxi_v3.png",
                        "App_Themes/default/Images/personne_v3.png",
                        "App_Themes/default/Images/utilitaire_v3.png",
                        "App_Themes/default/Images/moto_v3.png",
                        "App_Themes/default/Images/pelleteuse_v3.png",
                        "App_Themes/default/Images/fauteuil_roulant_v3.png",
                        "App_Themes/default/Images/personal_tracker_v3.png");
var icons_grey = new Array(
                        "App_Themes/default/Images/voiture_g3.png",
                        "App_Themes/default/Images/fourgon_g3.png",
                        "App_Themes/default/Images/camion_g3.png",
                        "App_Themes/default/Images/ambulance_g3.png",
                        "App_Themes/default/Images/benne_g3.png",
                        "App_Themes/default/Images/toupie_g3.png",
                        "App_Themes/default/Images/camion2_g3.png",
                        "App_Themes/default/Images/bus_g3.png",
                        "App_Themes/default/Images/taxi_g3.png",
                        "App_Themes/default/Images/personne_g3.png",
                        "App_Themes/default/Images/utilitaire_g3.png",
                        "App_Themes/default/Images/moto_g3.png",
                        "App_Themes/default/Images/pelleteuse_g3.png",
                        "App_Themes/default/Images/fauteuil_roulant_g3.png",
                        "App_Themes/default/Images/personal_tracker_g3.png");



//
// *********************************************************************************
//  Gestion de la cartographie AjaxMap
//
// *********************************************************************************

function rmsGeoPoint(x, y, state, name, descr)
{
    this.x = x;
    this.y = y;
    this.state = state;
    this.name = name;
    this.descr = descr;
}

function rmsTourPoint(x, y, name, sTour, iStep)
{
    this.x = x;
    this.y = y;
    this.name = name;
    this.stour = sTour;
    this.istep = iStep;
}

function rmsPointRapport(x, y, dt, state, speed, idt, iDuration, sAddress, xgeo, ygeo)
{
    this.x = x;
    this.y = y;
    this.xgeo=xgeo;
    this.ygeo=ygeo;
    this.dt = dt;
    this.state = state;
    this.speed = speed;
    this.idt=idt;
    this.iPOI=-1;
    this.iDuration = iDuration;
    this.sAddress = sAddress;
}

function include(fileName)
{
    document.write("<script type='text/javascript' src='" + fileName + "'></script>" );
}

include("POI.js");

function rmsGeoUnit(unitid, x, y, dt, state, type, sdescr){
    this.unitid = unitid;
    this.x = x;
    this.y = y;
    this.dt = dt;
    this.state = state;
    this.type = type;
    this.sdescr = sdescr;
}

function xmappoint(x, y){
    this.x = x;
    this.y = y;
}


function GetVehiUnitId(indexVehi){
    var _unitid = document.getElementById("ctl00_ContentPlaceHolder1_wuc_iv" + indexVehi + "_HF_unitid");
    if (_unitid == null) 
    {
        return -1;
    }
    else 
    {
        return _unitid.value;
    }
}

function getTypePoi(TypeId){
    for(var i=0;i<typespoi.length;i++)
    {  
        if (typespoi[i].iTypeId == TypeId)
        {
            return typespoi[i];
        }
    }
}

function getZone(ZoneId){
    for(var i=0;i<zones.length;i++)
    {  
        if (zones[i].iId == ZoneId)
        {
            return zones[i];
        }
    }
}

function setGeoUnits() {
    var nbVehi = document.getElementById(CPH_+"HF_NbVehi"); 
    if (nbVehi != null)
    {
        var iMax = parseInt(nbVehi.value);
        for(var i=0;i<iMax;i++)
        {  
            var _unitid = document.getElementById("ctl00_ContentPlaceHolder1_wuc_iv" + i + "_HF_unitid");
            var _x = document.getElementById("ctl00_ContentPlaceHolder1_wuc_iv" + i + "_HF_x");
            var _y = document.getElementById("ctl00_ContentPlaceHolder1_wuc_iv" + i + "_HF_y");
            var _dt = document.getElementById("ctl00_ContentPlaceHolder1_wuc_iv" + i + "_HF_dt");
            var _state = document.getElementById("ctl00_ContentPlaceHolder1_wuc_iv" + i + "_HF_state");
            var _type = document.getElementById("ctl00_ContentPlaceHolder1_wuc_iv" + i + "_HF_type");
            var _descr = document.getElementById("ctl00_ContentPlaceHolder1_wuc_iv" + i + "_HF_descr");
            if (_unitid != null) 
            {
                geoUnits[i] = new rmsGeoUnit(parseInt(_unitid.value), 
                                             parseInt(_x.value), 
                                             parseInt(_y.value), 
                                             parseFloat(_dt.value), 
                                             parseInt(_state.value), 
                                             parseInt(_type.value),
                                             _descr.value);
            }
        }
    }
}

function updateMap_Old(){
    var selMenu=document.getElementById(MASTER_PREFIX + "HF_select_menu");
    if (parseInt(selMenu.value) < 3)
    {
        WS_GetMap.GetActiveTimerCarto(OnGetActiveTimerCartoSucceeded, OnGetActiveTimerCartoFailed);
    }
}

function updateMap(){
    WS_GetUnits.GetSessionValue("SELECT_MENU", updateMapSucceeded, OnMethodError);
}

function updateMapSucceeded(result){
    var selMenu=result;
    if (parseInt(result) < 3)
    {
        WS_GetMap.GetActiveTimerCarto(OnGetActiveTimerCartoSucceeded, OnGetActiveTimerCartoFailed);
    }
}


function OnGetActiveTimerCartoFailed()
{
}

function OnGetActiveTimerCartoSucceeded(result) {
    if (result == true){
        if(!bFirst) {
            refreshLocations();
        }
    }
}              

function AfficheMessage(message)
{
    alert(message);
}

function setToolbarTooltips(genericMap) {
    var btnCspace;
    if (genericMap != null)
    {
        var overviewLayer = genericMap.getLayer("overview");
        overviewLayer.setAreaBottom(20);
        overviewLayer.setAreaWidth(0.2);
        overviewLayer.setAreaTop(null);
        overviewLayer.setEnabled(true);
        
        var toolbar = genericMap.getLayer('toolbar');
        toolbar.setButtonOpacityOut(0.5); // default 0.35
        toolbar.setButtonOpacityOver(0.95); // default 0.6

        toolbar.setButtonTooltip("zoom-in",   "Zoom +");       
        toolbar.setButtonImage("zoom-in", ajaxmapURL + "altcontrols/plus.png");        
        toolbar.setButtonTooltip("zoom-out",  "Zoom -");
        toolbar.setButtonImage("zoom-out", ajaxmapURL + "altcontrols/moins.png");
       
        toolbar.setButtonTooltip("move-mode", "Bascule en mode deplacement");
        toolbar.setButtonImage("move-mode", ajaxmapURL + "altcontrols/deplacement.png");
       
        toolbar.setButtonTooltip("zoom-mode", "Bascule en mode zoom");
        toolbar.setButtonImage("zoom-mode", ajaxmapURL + "altcontrols/loupe.png");
       
        toolbar.setButtonTooltip("overview",  "Affiche ou masque la petite carte");
        toolbar.setButtonImage("overview", ajaxmapURL + "altcontrols/agrandir2.png");
        toolbar.removeElement("reset");
        toolbar.setButtonTooltip("history-back",  "Affiche la vue precedente");
        toolbar.setButtonImage("history-back", ajaxmapURL + "altcontrols/fleche_gauche.png");
        toolbar.setButtonTooltip("history-forward",  "Affiche la vue suivante");
        toolbar.setButtonImage("history-forward", ajaxmapURL + "altcontrols/fleche_droite.png");
        toolbar.removeElement("map-view");
        toolbar.removeElement("hybrid-view");
        toolbar.removeElement("aerial-view");
        
        toolbar.setButtonTooltip("measurement",  "Mesure la distance");
        
        btnCspace=toolbar.addElement({imgUrl:"",width:4,height:16});
        var xmain=document.getElementById("carto");
        if (xmain != null) // si écran principal
        {
            var btnCenterAll=toolbar.addElement(
                {imgUrl:ajaxmapURL + "altcontrols/centrer.png",
                 width:16,
                 height:16,
                 tooltip:"Centre sur la flotte",
                 id:"btnCenterAll",
                 clickHandler:function(){CenterMap("btnCenterAll", 0, 0, true);}
                 });        
            btnCspace=toolbar.addElement({imgUrl:"",width:4,height:16});
        }
            var btnCenterAddress=toolbar.addElement(
                {imgUrl:ajaxmapURL + "altcontrols/home.png",
                 width:16,
                 height:16,
                 tooltip:"Centre sur une adresse",
                 id:"btnCenterAddress",
                 clickHandler:function(){toggle("panSA"); document.getElementById("btnCenterAddress").focus();}
                 });  
            btnCspace=toolbar.addElement({imgUrl:"",width:4,height:16});


        var btnPrintMap=toolbar.addElement(
            {imgUrl:ajaxmapURL + "altcontrols/imprimante.png",
             width:16,
             height:16,
             tooltip:"Imprime la carte",
             id:"btnPrintMap",
             clickHandler:function(){printInNewWindow();}
             }); 
        btnCspace=toolbar.addElement({imgUrl:"",width:4,height:16});
        toolbar.setButtonEnabled("btnPrintMap", false); 
    }
};
         
         
function initNav()
{
    return true;
    var iPos = navigator.userAgent.indexOf("MSIE 7.0",0);
    if (iPos==-1)
    {
        alert("Votre navigateur n'est pas compatible. Vous devez utiliser Internet Explorer 7.0.");
        return false;
    }
    else
    {
        return true;
    }
}
    
function initMap() {
    // on force une utilisation maximale de l'écran
//    return;
    /*
    
    window.moveTo(0,0);
    
    if (document.getElementById || document.all) 
    {
        window.resizeTo(screen.availWidth, screen.availHeight);
    }    */
}

function initCarto()
{ return; }

function initGoogleMap () {
    var container = document.getElementById("carto");
    map = new google.maps.Map2(container);
    map.enableContinuousZoom() ;
    map.enableScrollWheelZoom();
    map.addControl(new GLargeMapControl()) ;
    map.addControl(new GLargeMapControl()) ;
    map.addControl(new GMapTypeControl());
    
}

//
// ZONES
//
function OnMethodGetZONESucceeded(result, eventArgs) { 
    
    if (result.length >0)
    { // Il y a des zones créés pour ce compte
        // Récupération des zones
        zones = new Array();
        for(var i=0;i<result.length;i++)
        {
            zones[i] = result[i];
        }
    }
//    DisplayZones();
}  



//
//    POI
//
function OnMethodGetTypesPOISucceeded(result, eventArgs) { 
    
    if (result.length >0)
    { // Il y a des types de poi créés pour ce compte
        // Récupération des types
        typespoi = new Array();
        for(var i=0;i<result.length;i++)
        {
            typespoi[i] = result[i];
        }
        // Récupération des pois
        iNbStepEnvoye = 0;
        for(var i=0;i<typespoi.length;i++)
        {
            WS_GetUnits.GetNbPOIsFromTypeEx(typespoi[i].iTypeId, OnMethodGetNbPOIsFromTypeExSucceeded, OnMethodError);   
        }
    }
}        



function enableZONE()
{
    if (zoneLayer == null)
    {
        zoneLayer = new com.ptvag.webcomponent.map.layer.VectorLayer(map.getLayer("floaterLayer"));
        map.addLayer(zoneLayer, "zoneLayer", 0, map.getLayer("vehiLayer"));
        WS_GetUnits.GetZones(OnMethodGetZONESucceeded, OnMethodError);                
    }

    if (zoneLayer != null)
    {
        var cbDpl = document.getElementById("cbDisplayZONE");
        if (cbDpl != null)
        {
            var b = cbDpl.checked;
            zoneLayer.setEnabled(b);
            updateMap();
        }
    }
}

function initCartoRapport()
{
    if (mapRapport != null) {
        return;
    }

    var container = document.getElementById("panRapportCarto");
    mapRapport = new google.maps.Map2(container);
    mapRapport.enableContinuousZoom() ;
    mapRapport.enableScrollWheelZoom();
    mapRapport.addControl(new GLargeMapControl()) ;
    mapRapport.addControl(new GLargeMapControl()) ;
    mapRapport.addControl(new GMapTypeControl());
    container.style.display="block";
    mapRapport.setCenter(new GLatLng(46.427256,2.786865), 6);
}

function clearLocations() {
// affiche les dernières positions des véhicules sur la cartographie
        initCarto();
        if (map != null)
        {
            return;
        }

        var vector = com.ptvag.webcomponent.map.vector;
        var vectorLayer = map.getLayer("vehiLayer");
        vectorLayer.removeAllElements();
}

function OnMethodGetLocationsSucceeded(result, eventArgs) {  
    initGoogleMap();
    if (map == null) {
        alert('object Map introuvable');
        return;
    }
    if (result.length >0) {
        var j=0;
        for(var i=0;i<result.length;i++) {
            if ((result[i].dt > 1000) && // évite le cas du véhicule non géolocalisé
            (result[i].iPrivacy==0)) // vie privée
            {

                var sIcon;
                sIcon = icons_grey[result[i].type - 1]; // par défaut
                if (result[i].status==0) { sIcon = icons_red[result[i].type - 1];}
                if (result[i].status==1) { sIcon = icons_green[result[i].type - 1];}

                var blueIcon = new GIcon(G_DEFAULT_ICON);
                var size = new GSize(31, 18);
                blueIcon.iconSize = size;
                blueIcon.shadowSize = new GSize(0, 0);
                blueIcon.iconAnchor = new GPoint(15, 9);
                blueIcon.image = sIcon;
                
                var markerOptions = { icon:blueIcon };
                var texte = result[i].sName + '<br />' + result[i].sZipCode + " - " + result[i].sLocality;
                var y = (result[i].y)/100000;
                var x = (result[i].x)/100000;
                
                var marker = new GMarker(new GLatLng(y, x), markerOptions);
                marker.bindInfoWindowHtml(texte);
                map.addOverlay(marker);      

                locations[j] = marker;
                j++;

            }
        }
        if(bFirst) { 
            CenterMap("pageLoad", 0, 0, true);
        }
    }
}

function OnMethodRefreshLocationsSucceeded(result, eventArgs) {  
    if (map == null) {
        alert('object Map introuvable');
        return;
    }
    for(var i = 0; i < locations.length; i++) {
        map.removeOverlay(locations[i]);
    }
    if (result.length >0) {
        var j=0;
        for(var i=0;i<result.length;i++) {
            if ((result[i].dt > 1000) && // évite le cas du véhicule non géolocalisé
            (result[i].iPrivacy==0)) // vie privée
            {
                var sIcon;
                sIcon = icons_grey[result[i].type - 1]; // par défaut
                if (result[i].status==0) { sIcon = icons_red[result[i].type - 1];}
                if (result[i].status==1) { sIcon = icons_green[result[i].type - 1];}

                var blueIcon = new GIcon(G_DEFAULT_ICON);
                var size = new GSize(31, 18);
                blueIcon.iconSize = size;
                blueIcon.shadowSize = new GSize(0, 0);
                blueIcon.iconAnchor = new GPoint(15, 9);
                blueIcon.image = sIcon;
                
                var markerOptions = { icon:blueIcon };
                var texte = result[i].sName + '<br />' + result[i].sZipCode + " - " + result[i].sLocality;
                var y = (result[i].y)/100000;
                var x = (result[i].x)/100000;
                
                var marker = new GMarker(new GLatLng(y, x), markerOptions);
                marker.bindInfoWindowHtml(texte);
                map.addOverlay(marker);      

                locations[j] = marker;
                j++;

            }
        }
    }
}

function refreshLocations() {
    WS_GetUnits.GetUnitsAndLocations(OnMethodRefreshLocationsSucceeded, OnMethodError);
}


function checkcbPositions() {
// montre ou cache la sélection de la date de fin en fonction 
// de la checkbox Position
    var xPos = document.getElementById("cbPositions");
    var txtcarto2 = document.getElementById(CPH_ + "txtDateCarto2"); 
    var btncarto2 = document.getElementById(CPH_ + "btnDateCarto2"); 
    var txtlabelfrom = document.getElementById(CPH_ + "labTitleDateCartoFrom"); 
    var txtlabelto = document.getElementById(CPH_ + "labTitleDateCartoTo"); 
  
    if (xPos.checked)
    {
        txtcarto2.style.display = "none";
        btncarto2.style.display = "none";
        txtlabelto.style.display = "none";
        txtlabelfrom.innerText = txtlabelfrom.textContent ="Le";
    }
    else
    {
        txtcarto2.style.display = "block";
        btncarto2.style.display = "block";
        txtlabelto.style.display = "block";
        txtlabelfrom.innerText = txtlabelfrom.textContent ="Du";
    }
}

function setRapportLocations() {
    
    // affiche les visites sur la carto mapPlanif
    var currentRapportHisto;
    var imgLoading = document.getElementById("ImgCalcCarto");
    if (imgLoading != null){
        imgLoading.style.display="block";
    }

    divRapCarto = document.getElementById("divRapportCarto");
    divRapCarto.style.display="block";

    divRap = document.getElementById("divRapports");
    divRap.style.display="none";  
    ResizeComponents();
    
    
    //WS_GetUnits.GetRapportLocations(iUnit, iDate)
    var ddlvehicarto = document.getElementById(CPH_ + "ddlVehiCarto"); 
    var txtdatecarto = document.getElementById(CPH_ + "txtDateCarto"); 
    var txtdatecarto2 = document.getElementById(CPH_ + "txtDateCarto2"); 
    var xPos = document.getElementById("cbPositions");
    var xStop = document.getElementById("cbStop");
    
    if (ddlvehicarto != null)
    {
        currentRapportHisto = ddlvehicarto.value + txtdatecarto.value + txtdatecarto2.value  + xPos.checked;
        if (currentRapportHisto == lastRapportHisto)
        { // Display uniquement
             DisplayRapportLocation();
        }
        else
        { // Récupération des données + display
            lastRapportHisto = currentRapportHisto;
            
            initCartoRapport();
        
            xmappointsRapport = new Array();
            iRapportNbLocation = 0;        
        
            var sDate=txtdatecarto.value;
            
            var iBegin = new Date();
            iBegin.setDate(1);
            iBegin.setFullYear(sDate.substring(6,10));
            iBegin.setMonth(sDate.substring(3,5));
            iBegin.setMonth(iBegin.getMonth()-1);
            iBegin.setDate(sDate.substring(0,2));
            iBegin.setHours(0,0,0,0);

            var sBegin;
            var sEnd;
            sBegin = (iBegin.getDate()+"/"+(iBegin.getMonth()+1)+"/"+iBegin.getFullYear()+"/"+
                    iBegin.getHours()+"/"+iBegin.getMinutes()+"/"+iBegin.getSeconds()+"/"+iBegin.getMilliseconds());

            var iEnd = new Date();
            iEnd = iBegin;
            if (xPos.checked == false) {
                var sDateEnd=txtdatecarto2.value;
                iEnd.setDate(1);
                iEnd.setFullYear(sDateEnd.substring(6,10));
                iEnd.setMonth(sDateEnd.substring(3,5));
                iEnd.setMonth(iEnd.getMonth()-1);
                iEnd.setDate(sDateEnd.substring(0,2));
            }
            iEnd.setDate(iEnd.getDate()+1);
            iEnd.setHours(0,0,0,0);
            sEnd = ((iEnd.getDate())+"/"+(iEnd.getMonth()+1)+"/"+iEnd.getFullYear()+"/"+
                    iEnd.getHours()+"/"+iEnd.getMinutes()+"/"+iEnd.getSeconds()+"/"+iEnd.getMilliseconds());

            WS_GetUnits.GetImageSpeedReport(parseInt(ddlvehicarto.value),sBegin, sEnd,
                                                parseInt(document.getElementById("panRapportCarto").style.width),
                                                heightImageSynop,
                                                OnMethodGetImageSpeedReportSucceeded, OnMethodError);
            // aiguillage si CBIti est coché
            if ((xStop.checked==true) && (xPos.checked==false))            
            {
                GetRapportLocationStops();
            }
            else
            {
                WS_GetUnits.GetCountLocationsFromUnitDay(parseInt(ddlvehicarto.value),
                                 sBegin, sEnd,     
                                 OnMethodGetCountRapportLocationsSucceeded,
                                 OnMethodGetRapportLocationsFailed);
            }
        }
    }
      
}

function OnMethodGetImageSpeedReportSucceeded(result, eventArgs)
{ 
// On recoit l'image du synoptique
    ResizeRapportLocation(true);
    document.images["ImgSpeedReport"].src=result;  
}

function GetRapportLocationStops()
{
//
    var ddlvehicarto = document.getElementById(CPH_ + "ddlVehiCarto"); 
    var txtdatecarto = document.getElementById(CPH_ + "txtDateCarto"); 
    var txtdatecarto2 = document.getElementById(CPH_ + "txtDateCarto2"); 

    if (ddlvehicarto != null)
    {
        var sDate=txtdatecarto.value;    
        var iBegin = new Date();
        iBegin.setDate(1);
        iBegin.setFullYear(sDate.substring(6,10));
        iBegin.setMonth(sDate.substring(3,5));
        iBegin.setMonth(iBegin.getMonth()-1);
        iBegin.setDate(sDate.substring(0,2));
        iBegin.setHours(0,0,0,0);

        var sBegin;
        var sEnd;    
        iBegin.setHours(0,0,0,0);
        sBegin = (iBegin.getDate()+"/"+(iBegin.getMonth()+1)+"/"+iBegin.getFullYear()+"/"+
                iBegin.getHours()+"/"+iBegin.getMinutes()+"/"+iBegin.getSeconds()+"/"+iBegin.getMilliseconds());

        var sDate2=txtdatecarto2.value;    
        
        var iEnd = new Date();
        iEnd.setDate(1);
        iEnd.setFullYear(sDate2.substring(6,10));
        iEnd.setMonth(sDate2.substring(3,5));
        iEnd.setMonth(iEnd.getMonth()-1);
        iEnd.setDate(sDate2.substring(0,2));
        iEnd.setHours(0,0,0,0);
        iEnd.setDate(iEnd.getDate()+1);
        sEnd = ((iEnd.getDate())+"/"+(iEnd.getMonth()+1)+"/"+iEnd.getFullYear()+"/"+
                    iEnd.getHours()+"/"+iEnd.getMinutes()+"/"+iEnd.getSeconds()+"/"+iEnd.getMilliseconds());

        WS_GetUnits.GetStopsFromUnitDay(parseInt(ddlvehicarto.value),
                                    sBegin, sEnd,     
                                    OnMethodGetRapportStopsSucceeded,
                                    OnMethodGetRapportStopsFailed);
    }

}

function OnMethodGetRapportStopsSucceeded(result, eventArgs)
{
    // result contient uniquement les arrêts détectés
    // on remplit le tableau xmappoint en insérant un position bidon entre chaque arrêt pour avoir un bon affichage
    
   iNbRequestSent = result.length;
   iNbRequestReceived = 0;
    
    for(var i=0;i<result.length;i+=1)
    {
        var smartUnitPoint;
        var geoDecimalPoint = { x:result[i].x, y:result[i].y };
        smartUnitPoint = com.ptvag.webcomponent.map.CoordUtil.geoDecimal2SmartUnit(geoDecimalPoint);
        // l'arrêt
        xmappointsRapport[2 * i] = new rmsPointRapport(smartUnitPoint.x, 
                                                                    smartUnitPoint.y, 
                                                                    result[i].sTime, 
                                                                    result[i].sStatus,
                                                                    result[i].iSpeed,
                                                                    result[i].dt,
                                                                    0, // vitesse = -1 => arrêt
                                                                    result[i].sAddress,
                                                                    result[i].x,
                                                                    result[i].y);
        
        // géocodage des arrêts
        //WS_GetMap.ReverseGeocodeXY(parseInt(xmappointsRapport[2*i].xgeo), parseInt(xmappointsRapport[2*i].ygeo), 
        //                                   2*i, OnMethodReverseGeocodeSucceeded, OnMethodReverseGeocodeFailed);
                                                                    
        // la position conduite fictive
        xmappointsRapport[(2 * i) + 1] = new rmsPointRapport(smartUnitPoint.x, 
                                                                    smartUnitPoint.y, 
                                                                    result[i].sTime, 
                                                                    result[i].sStatus,
                                                                    0, // vitesse=0 => conduite
                                                                    result[i].dt + result[i].dtDuration,
                                                                    0,
                                                                    "",
                                                                    result[i].x,
                                                                    result[i].y);
                                                                    

    }
    // on appelle l'affichage classique
    iDelta = 1;    
    DisplayRapportLocation();
}


function OnMethodGetRapportStopsFailed()
{
}

function OnMethodGetCountRapportLocationsSucceeded(result, eventArgs)
{
// HISTORIQUE des positions sur une journée 2/3
// Récupère le nombre de positions à télécharger
//
    iNbRapportLocation = result;
    iNbRequestReceived = 0;
    iNbRequestSent = 6;
    
    var ddlvehicarto = document.getElementById(CPH_ + "ddlVehiCarto"); 
    var txtdatecarto = document.getElementById(CPH_ + "txtDateCarto"); 
    if (ddlvehicarto != null)
    {
        var sDate=txtdatecarto.value;    
        var iBegin = new Date();
        var iEnd = new Date();
        iBegin.setDate(1);
        iBegin.setFullYear(sDate.substring(6,10));
        iBegin.setMonth(sDate.substring(3,5));
        iBegin.setMonth(iBegin.getMonth()-1);
        iBegin.setDate(sDate.substring(0,2));
        iBegin.setHours(0,0,0,0);

        var sBegin;
        var sEnd;

        for(var i=0;i<iNbRequestSent;i+=1)
        {
            iBegin.setHours(i * (24/iNbRequestSent),0,0,0);
            sBegin = (iBegin.getDate()+"/"+(iBegin.getMonth()+1)+"/"+iBegin.getFullYear()+"/"+
                    iBegin.getHours()+"/"+iBegin.getMinutes()+"/"+iBegin.getSeconds()+"/"+iBegin.getMilliseconds());

            iEnd = iBegin;
            iEnd.setHours((i+1)*(24/iNbRequestSent)-1,59,59,999);
            sEnd = (iEnd.getDate()+"/"+(iEnd.getMonth()+1)+"/"+iEnd.getFullYear()+"/"+
                    iEnd.getHours()+"/"+iEnd.getMinutes()+"/"+iEnd.getSeconds()+"/"+iEnd.getMilliseconds());

            WS_GetUnits.GetLocationsFromUnitDay(parseInt(ddlvehicarto.value),
                                        sBegin, sEnd,     
                                        OnMethodGetRapportLocationsSucceeded,
                                        OnMethodGetRapportLocationsFailed);
        }
    }
}

function OnMethodGetRapportLocationsFailed(result, eventArgs) {
    var imgLoading = document.getElementById("ImgCalcCarto");
    if (imgLoading != null)
    {
        imgLoading.style.display="none";
    }
}

function Trier_xmappointsRapport(x1,x2)
{   
   // Tri descendant sur chaîne de caractères
//   return (x1.idt > x2.idt)? -1 : 1;
   return (x1.idt < x2.idt)? -1 : 1;
} 

function Trier_Planif(x1,x2) // tri par ressource, tournee, ordre
{   
   if (x1.name < x2.name) { return -1; }
   else
   {
        if (x1.name>x2.name) {return 1;}
        else 
        {
            if (x1.stour<x2.stour) {return -1; }
            else
            {
                if (x1.stour>x2.stour) {return 1;}
                else
                {
                    if (x1.istep<x2.istep) {return -1;}
                    else
                    {
                        if (x1.istep>x2.istep) {return 1;}
                        else {return 0;}
                    }            
                }            
            }
        }
   }
} 

function OnMethodGetRapportLocationsSucceeded(result, eventArgs) {
// HISTORIQUE des positions sur une journée 3/3
// Récupère les positions et les dessine sur la cartographie
//    
    iDelta = 1;
    for(var i=0;i<result.length;i+=iDelta)
    {
        var smartUnitPoint;
        var geoDecimalPoint = { x:result[i].x, y:result[i].y };
        smartUnitPoint = com.ptvag.webcomponent.map.CoordUtil.geoDecimal2SmartUnit(geoDecimalPoint);
        xmappointsRapport[iRapportNbLocation] = new rmsPointRapport(smartUnitPoint.x, 
                                                                    smartUnitPoint.y, 
                                                                    result[i].sTime, 
                                                                    result[i].sStatus,
                                                                    result[i].iSpeed,
                                                                    result[i].dt,
                                                                    0,
                                                                    "",
                                                                    result[i].x,
                                                                    result[i].y);
       iRapportNbLocation = iRapportNbLocation + 1;          
   }
   iNbRequestReceived = iNbRequestReceived + 1;
   
   if (iNbRequestReceived == iNbRequestSent)       
   { 
        xmappointsRapport.sort(Trier_xmappointsRapport);
        // récupération des adresses uniquement pour le premier point de type ARRET
        iNbRequestReceived = 0;
        iNbRequestSent = 0;
        bStopInProgress = false;
        for(var i=0;i<xmappointsRapport.length;i+=iDelta)
        {
            if ((xmappointsRapport[i].speed == -1) && (bStopInProgress == false)) // ARRET et pas d'arrêt en cours
            {
                bStopInProgress = true;
                iNbRequestSent = iNbRequestSent + 1;
            }
            if (xmappointsRapport[i].speed != -1)// conduite
            {
                bStopInProgress = false;
            }
        }

        bStopInProgress = false;
        for(var i=0;i<xmappointsRapport.length;i+=iDelta)
        {
            if ((xmappointsRapport[i].speed == -1) && (bStopInProgress == false)) // ARRET et pas d'arrêt en cours
            {
                bStopInProgress = true;
                WS_GetMap.ReverseGeocodeXY(parseInt(xmappointsRapport[i].xgeo), 
                                           parseInt(xmappointsRapport[i].ygeo), 
                                           i, 
                                           OnMethodReverseGeocodeSucceeded,
                                           OnMethodReverseGeocodeFailed);
            }
            if (xmappointsRapport[i].speed != -1)// conduite
            {
                bStopInProgress = false;
            }
        }
   } 
}

function OnMethodReverseGeocodeSucceeded(result, eventArgs) {
// Récupération des adresses des arrêts 4/3
// Dessine sur la cartographie
   index = result.quality;
   xmappointsRapport[index].sAddress = result.country + "-" + result.zipcode + " " + result.city + "-" + result.street;
   
   iNbRequestReceived = iNbRequestReceived + 1;

   if (iNbRequestReceived == iNbRequestSent)       
   { 
        var imgLoading = document.getElementById("ImgCalcCarto");
        if (imgLoading != null)
        {
            imgLoading.style.display="none";
        }
        DisplayRapportLocation();           
   }
}

function OnMethodReverseGeocodeFailed(result, eventArgs) {
// Récupération des adresses des arrêts 4/3
// Dessine sur la cartographie
   iNbRequestReceived = iNbRequestReceived + 1;

   if (iNbRequestReceived == iNbRequestSent)       
   { 
        var imgLoading = document.getElementById("ImgCalcCarto");
        if (imgLoading != null)
        {
            imgLoading.style.display="none";
        }
        DisplayRapportLocation();           
   }
}


function ResizeRapportLocation(bShowSynop)
{
    var bmpsynop = document.getElementById("ImgSpeedReport"); 
    var xcartorapport = document.getElementById("panRapportCarto");
    var xcartorapportmain = document.getElementById("panRapportCartoMain");
    var panSpeedReport = document.getElementById("panSpeedReport");
    
    var hScreen = getWindowHeight();
    var iMarginH = 5;
    var iMarginV = 5;
    var H;
    var xheader = document.getElementById("header");
    var xfooter = document.getElementById("footer");
    
    H = hScreen - xheader.clientHeight - xfooter.clientHeight - (3 * iMarginV);


    if (bShowSynop)
    {
        bmpsynop.height=heightImageSynop;
        panSpeedReport.style.height = heightImageSynop + "px";
        xcartorapport.style.height = H - heightImageSynop + "px";
        xcartorapportmain.style.height = H + "px";    
    }
    else
    {
        bmpsynop.height=0;
        panSpeedReport.style.height = "0px";
        xcartorapport.style.height = H + "px";
        xcartorapportmain.style.height = H + "px";    
    }
    if (mapRapport != null)
    {
        //mapRapport.updateSize();    
    }

}


function DisplayRapportLocation() {
// HISTORIQUE des positions sur une journée 4/3
// Affiche les points sur la cartographie
//
    idCircle = null;
    var imgLoading = document.getElementById("ImgCalcCarto");
    if (imgLoading != null) {
        imgLoading.style.display="block";
    }
    
    var cbStop = document.getElementById("cbStop"); 
    var cbPositions = document.getElementById("cbPositions"); 
    var cbIti = document.getElementById("cbIti");
    PTS = new Array();
   
    bDisplayDriving = false;
    if (cbPositions != null) {bDisplayDriving = cbPositions.checked;} 
    bDisplayStop = false;
    if (cbStop != null) {bDisplayStop = cbStop.checked;} 
    bDisplayItinerary = false;
    if (cbIti != null) {bDisplayItinerary = cbIti.checked;} 

    var iSize;

    iRapportPointSelected = -1;
    
    color_stop = "rgba(250,0,0, 0.7)";
    color = "rgba(50,150,250, 0.7)";
    color2 = "rgba(0,0,250, 0.7)";
    color_white= "rgba(255,255,255, 0.7)";
    color_white_bord= "rgba(170,160,150, 0.7)";

    //--- Reinitialisation
    for(var i = 0; i < locations.length; i++) {
        mapRapport.removeOverlay(locations[i]);
    }
    locations = new Array();
    
    if (xmappointsRapport != null)
    {
        PTS = new Array();
        iPTS = 0;
        var bStopInProgress = false;
       
        for(var i=0;i<(xmappointsRapport.length);i+=1)
        {
            if ((xmappointsRapport[i].speed == -1) && (bDisplayStop) && (bStopInProgress == false)) // = arrêt
            {
                PTS[iPTS] = xmappointsRapport[i];
                iPTS = iPTS + 1;
                bStopInProgress = true;
            }
            if ((xmappointsRapport[i].speed != -1)) // = conduite
            {
                if (bStopInProgress)
                {
                    iDeltaDT = parseInt((xmappointsRapport[i].idt - PTS[iPTS - 1].idt) * 24 * 60);  // nombre de minutes
                    if (iDeltaDT<60)
                    {
                        if (iDeltaDT == 0)
                        {
                            sDuree = " moins d'1 min.";
                        }
                        else
                        {
                            sDuree = iDeltaDT + " min.";
                        }
                    }
                    else
                    {
                        iHDelta = parseInt(iDeltaDT / 60);               // Heures
                        iMDelta = parseInt(iDeltaDT - (iHDelta * 60));   // Minutes
                        sDuree = iHDelta + "h";
                        if (iMDelta<10) { sDuree = sDuree + "0"; }
                        sDuree = sDuree + iMDelta + " min.";
                    }
                    PTS[iPTS - 1].iDuration = sDuree;
                    bStopInProgress = false;
                }
                if (bDisplayDriving)
                {
                    PTS[iPTS] = xmappointsRapport[i];
                    iPTS = iPTS + 1;
                }
            }
            if ((i == (xmappointsRapport.length-1)) && (bStopInProgress)) // = conduite
            {
                iDeltaDT = parseInt((xmappointsRapport[i].idt - PTS[iPTS - 1].idt) * 24 * 60);  // nombre de minutes
                iHDelta = parseInt(iDeltaDT / 60);               // Heures
                iMDelta = parseInt(iDeltaDT - (iHDelta * 60));   // Minutes
                sDuree = iHDelta + ":";
                if (iMDelta<10) { sDuree = sDuree + "0"; }
                sDuree = sDuree + iMDelta;
                
                PTS[iPTS - 1].iDuration = sDuree;
                bStopInProgress = false;
            }
        }       
       
        if (bDisplayItinerary)
        {
            PTS.sort(function (a, b) {
                    return a.dt - b.dt;
                });
            for(var i=0;i<(PTS.length-1);i+=1)
            {
                coordsRapport = new Array(new GLatLng(PTS[i].ygeo/100000, PTS[i].xgeo/100000),
                                          new GLatLng(PTS[i+1].ygeo/100000, PTS[i+1].xgeo/100000));
                if (coordsRapport[0]!=coordsRapport[1]) {
                    var line3 = new GPolyline(coordsRapport, color, 3);
                    mapRapport.addOverlay(line3);
                    locations.push(line3);
                }
            } 
        } 

        var sOldHour="";
        listAllPositions = document.getElementById("selectAllPositions");
        listAllPositions.options.length=0;
        
        for(var i=0;i<PTS.length;i+=iDelta)
        {
	       if (PTS[i].dt.length>10)
	       {
	            sHour = PTS[i].dt.substr(0,16);
	       }
	       else
	       {
	            sHour = PTS[i].dt.substr(0,5);
	       }
	       if (sHour !=sOldHour)
	       {
                if (PTS[i].speed == -1)
                { // ARRET
                    var o=new Option(PTS[i].dt + " " + PTS[i].state + " pendant " + PTS[i].iDuration + " " + PTS[i].sAddress,i);
                }
                else
                { // CONDUITE
                    var o=new Option(PTS[i].dt + " " + 
                                     PTS[i].state + " " + 
                                     PTS[i].speed + " km/h",i);
                
                }
	            listAllPositions.options[listAllPositions.options.length]=o;
	        }
	        sOldHour = sHour; 
        } // for
        // Affichage des points de positions
        var j=0;
        if (bDisplayDriving)
        {
            for(var i=0;i<PTS.length;i+=iDelta)
            {
                if (PTS[i].speed != -1)
                {

                    sIcon = "App_Themes/default/Images/green.png";
                    sTooltip = PTS[i].dt + "<br />" + PTS[i].state + "<br />" + PTS[i].speed + " km/h";
                    
                    var blueIcon = new GIcon(G_DEFAULT_ICON);
                    var size = new GSize(8, 8);
                    blueIcon.iconSize = size;
                    blueIcon.shadowSize = new GSize(0, 0);
                    blueIcon.image = sIcon;
                    blueIcon.iconAnchor = new GPoint(4, 4);
                    var markerOptions = { icon:blueIcon };
                    var y = (PTS[i].ygeo)/100000;
                    var x = (PTS[i].xgeo)/100000;
                    
                    
                    var marker = new GMarker(new GLatLng(y, x), markerOptions);
                    marker.bindInfoWindowHtml(sTooltip);
                    mapRapport.addOverlay(marker);     
                    
                    locations.push(marker);
                    j++;
                }
            }   // for       
        } // if
        
        if (bDisplayStop)
        {
            for(var i=0;i<PTS.length;i+=iDelta)
            {
                if (PTS[i].speed == -1)
                {
                    // ARRET
                    
                    sIcon = "App_Themes/default/Images/big_red.gif"; 
                    sTooltip = PTS[i].dt + 
                               "<br />" + PTS[i].state + 
                               "<br /> Duree : " + PTS[i].iDuration +
                               "<br />" + PTS[i].sAddress;       

                    var blueIcon = new GIcon(G_DEFAULT_ICON);
                    var size = new GSize(12, 12);
                    blueIcon.iconSize = size;
                    blueIcon.shadowSize = new GSize(0, 0);
                    blueIcon.image = sIcon;
                    blueIcon.iconAnchor = new GPoint(6, 6);
                    
                    var markerOptions = { icon:blueIcon };
                    var y = (PTS[i].ygeo)/100000;
                    var x = (PTS[i].xgeo)/100000;
                    var marker = new GMarker(new GLatLng(y, x), markerOptions);
                    marker.bindInfoWindowHtml(sTooltip);
                    mapRapport.addOverlay(marker);      

                    locations.push(marker);
                    j++;
                    
                } // if
             } // for
          }          // if
    }

    if(locations.length>0) {
        mapRapport.setCenter(locations[j-1].getLatLng(), 12);
    }
    var imgLoading = document.getElementById("ImgCalcCarto");
    if (imgLoading != null)
    {
        imgLoading.style.display="none";
    }
    // Calcul des adresses
    ReverseGeocodeRapportStops();
        
}

function ReverseGeocodeRapportStops()
{

}

function onSelectPosition()
{
    listPositions = document.getElementById("selectAllPositions");
    if (listAllPositions != null)
    {
        if (listAllPositions.options.selectedIndex != -1)
        {
            //alert("Position sélectionnée indice=" + listAllPositions.options[listAllPositions.options.selectedIndex].value);
            setSelectedPoint();
        }
    }
}

function centerSelectedPoint()
{
    if (iRapportPointSelected != null)
    {
        if (iRapportPointSelected != -1)
        {
        var smartUnitPoint;
            var center = { x:xmappointsRapport[iRapportPointSelected].x, y:xmappointsRapport[iRapportPointSelected].y };
            mapRapport.setCenter(center);
            //mapRapport.setZoom(3);
        }
    }
            
}
            
function setSelectedPoint() {    
    listPositions = document.getElementById("selectAllPositions");
    if (listAllPositions != null) {
        iRapportPointSelected = parseInt(listAllPositions.options[listAllPositions.options.selectedIndex].value);
    }
    
    var color_stop = "#0000FF";
   
    if (idCircle != null) { mapRapport.removeOverlay(idCircle);}
   
   
    var x = PTS[iRapportPointSelected].xgeo/100000;
    var y = PTS[iRapportPointSelected].ygeo/100000;
    var lstPos = new Array(new GLatLng(y-0.001, x+0.001), new GLatLng(y+0.001, x+0.001), new GLatLng(y+0.001, x-0.001), new GLatLng(y-0.001, x-0.001), new GLatLng(y-0.001, x+0.001));
    idCircle = new GPolygon(lstPos, color_stop, 3, 1, color_stop, 0.5) ;
    mapRapport.addOverlay(idCircle);
    mapRapport.setCenter(new GLatLng(y, x), 15);
}

function onSelectHours()
{}



function setVisitsLocations() {
    // affiche les visites sur la carto mapPlanif
    document.getElementById("divDroitHaut2").style.display="block";
    document.getElementById("divDroitHaut").style.display="none";  
    ResizeComponents();
    WS_GetUnits.GetPlanifVisitsMinMax(OnMethodGetPlanifVisitsMinMaxSucceeded, OnMethodError);
}

function OnMethodGetPlanifVisitsMinMaxSucceeded(result, eventArgs) {
    var iBegin;
    var iEnd;
    var iDelta=500;
    iPOIPlanif = parseInt(result.maxId - result.minId);
    var iNbPlanif = parseInt(iPOIPlanif / iDelta) + 1;
    //alert("iNb=" + iNb + " maxId=" + result.maxId + " minId=" + result.minId);
    initCartoPlanif();

    var vector = com.ptvag.webcomponent.map.vector;
    var vectorLayer = mapPlanif.getLayer("vector");
    vectorLayer.removeAllElements();
    
    xmappointsPlanif = new Array();
    iPlanif = 0;
    for(var i=0;i<iNbPlanif;i++)
    {  
        iBegin = i * iDelta;
        iEnd = (i + 1) * iDelta;
        if (iEnd > result.maxId)
        {
            iEnd = result.maxId;
        }
        if (iEnd > iBegin)
        {
            WS_GetUnits.GetPlanifVisits(iBegin, iEnd, OnMethodGetVisitsLocationsSucceeded, OnMethodError);
        }
    }
}

function OnMethodGetVisitsLocationsSucceeded(result, eventArgs) {
        //alert("OnMethodGetVisitsLocationsSucceeded count=" + result.length);
    var vector = com.ptvag.webcomponent.map.vector;
    var vectorLayer = mapPlanif.getLayer("vector");
    iDelta = 1;
    for(var i=0;i<result.length;i+=iDelta)
    {
        var smartUnitPoint;
        var geoDecimalPoint = { x:result[i].x, y:result[i].y };
        smartUnitPoint = com.ptvag.webcomponent.map.CoordUtil.geoDecimal2SmartUnit(geoDecimalPoint);
        xmappointsPlanif[iPlanif] = new rmsTourPoint(smartUnitPoint.x,smartUnitPoint.y, result[i].sResource, result[i].sTourCode, result[i].iStepOrder);
        iPlanif = iPlanif + 1;
   }
       
    // dessin des tournées
    if (iPlanif == iPOIPlanif)
    {
        xmappointsPlanif.sort(Trier_Planif);
        
        //alert("panif : tout récupéré");
      //  if (iPOIPlanif > 300) {iDelta = parseInt(iPOIPlanif/300)+1;}
      //  else if (iPOIPlanif > 900) {iDelta = 10;}
           
        for(var i=0;i<iPlanif;i+=iDelta)
        {
            var circle = new com.ptvag.webcomponent.map.vector.Circle();
            circle.setX(xmappointsPlanif[i].x);
            circle.setY(xmappointsPlanif[i].y);
            circle.setPixelSize(15);
            
            sRes=xmappointsPlanif[i].name;
            if (sRes=="-1") {color="rgba(128,128,128, 0.7)";}
            else if (sRes=="0") {color="rgba(255, 0, 0, 0.7)";}
            else if (sRes=="1") {color="rgba(0, 255, 0, 0.7)";}
            else if (sRes=="2") {color="rgba(255, 0, 255, 0.7)";}
            else if (sRes=="3") {color="rgba(0, 0, 255, 0.7)";}
            else if (sRes=="4") {color="rgba(255, 255, 0, 0.7)";}
            else if (sRes=="5") {color="rgba(0, 255, 255, 0.7)";}
            else if (sRes=="6") {color="rgba(0, 128, 128, 0.7)";}
            else if (sRes=="7") {color="rgba(128, 0, 0, 0.7)";}
            else if (sRes=="8") {color="rgba(0, 128, 0, 0.7)";}
            else if (sRes=="9") {color="rgba(0, 0, 128, 0.7)";}
            else {color="rgba(192,192,192, 0.7)";}
            circle.setColor(color);
            vectorLayer.addElement(circle);
        }
        
            var pts=new Array();
            OldTour="";
            sTour = "";
            iStep = -1;
            var ipts = 0;
            sRes="";
            for(var i=0;i<xmappointsPlanif.length;i+=1)
            {   
               sTour = xmappointsPlanif[i].stour;
               iStep = xmappointsPlanif[i].istep;
               if (((sTour != OldTour) || (i==(xmappointsPlanif.length-1))) && (OldTour != "") && (sTour!="-1"))
               { // nouvelle tournée
                    if (pts.length != 0)
                    {
                        // on rajoute le premier point pour boucler
                        //pts[ipts]=pts[0]; ipts++;
                        //pts[ipts]=pts[1]; ipts++;
                        if ((i==(xmappointsPlanif.length-1)) && (iStep!=-1)) // dernier point de la tournée en cours
                        {
                            pts[ipts]=xmappointsPlanif[i].x; ipts++;
                            pts[ipts]=xmappointsPlanif[i].y; ipts++;
                        }
                        
                        var trace = new com.ptvag.webcomponent.map.vector.Line();
                        trace.setCoordinates(pts);
                        trace.setPixelSize(3);
                        //line3.setEndArrowLength(10); 
                        if (sRes=="-1") {color="rgba(128,128,128, 0.7)";}
                        else if (sRes=="0") {color="rgba(255, 0, 0, 0.7)";}
                        else if (sRes=="1") {color="rgba(0, 255, 0, 0.7)";}
                        else if (sRes=="2") {color="rgba(255, 0, 255, 0.7)";}
                        else if (sRes=="3") {color="rgba(0, 0, 255, 0.7)";}
                        else if (sRes=="4") {color="rgba(255, 255, 0, 0.7)";}
                        else if (sRes=="5") {color="rgba(0, 255, 255, 0.7)";}
                        else if (sRes=="6") {color="rgba(0, 128, 128, 0.7)";}
                        else if (sRes=="7") {color="rgba(128, 0, 0, 0.7)";}
                        else if (sRes=="8") {color="rgba(0, 128, 0, 0.7)";}
                        else if (sRes=="9") {color="rgba(0, 0, 128, 0.7)";}
                        else {color="rgba(192,192,192, 0.7)";}
                        trace.setColor(color);
                                   
                        //trace.setColor("rgba(0, 0, 0, 0.7)");
                        vectorLayer.addElement(trace);
                    
                    }
                    var pts=new Array();
                    ipts=0;
                    // premier point de la nouvelle tournée si nouvelle tournée
                    if ((sTour != OldTour) && (sTour != "") && (iStep!=-1))
                    {
                        pts[ipts]=xmappointsPlanif[i].x; ipts++;
                        pts[ipts]=xmappointsPlanif[i].y; ipts++;
                        sRes=xmappointsPlanif[i].name;                        
                    }
                    
               }
               else
               {
                    if ((sTour != "") && (iStep!=-1))
                    {
                        pts[ipts]=xmappointsPlanif[i].x; ipts++;
                        pts[ipts]=xmappointsPlanif[i].y; ipts++;
                        sRes=xmappointsPlanif[i].name;                        
                    }
               }
               OldTour = sTour;
            }
    }
    mapPlanif.setViewToPoints(xmappointsPlanif);       
}


function setLocations() {
// affiche les dernières positions des véhicules sur la cartographie
        WS_GetUnits.GetUnitsAndLocations(OnMethodGetLocationsSucceeded, OnMethodError);
}


// *********************************************************************************
//


function getWindowHeight() {
    var windowHeight=0;
    /*if (typeof(window.innerHeight)=='number') {
        windowHeight=window.innerHeight;
        alert("1");
    }
    else {
*/     if (document.documentElement&&
       document.documentElement.clientHeight) {
         windowHeight = document.documentElement.clientHeight;
    }
    else {
     if (document.body&&document.body.clientHeight) {
         windowHeight=document.body.clientHeight;
      }
     }
    /*}*/
    return windowHeight;
}

function getWindowWidth() {
    var windowWidth=0;
    if (typeof(window.innerWidth)=='number') {
        windowWidth=window.innerWidth;
    }
    else {
     if (document.documentElement&&
       document.documentElement.clientWidth) {
         windowWidth = document.documentElement.clientWidth;
    }
    else {
     if (document.body&&document.body.clientWidth) {
         windowWidth=document.body.clientWidth;
      }
     }
    }
    return windowWidth;
}


function GetCRA() {
    var btnExtract = document.getElementById("btnExtractReport");
    if (btnExtract != null)
    {
        btnExtract.disabled = true;
    }
    var imgLoading = document.getElementById("ImgLoading");
    if (imgLoading != null)
    {
        imgLoading.style.display="block";
    }
        
    var title;
    var cbList = document.getElementById("ctl00_ddlVehicles");
    var sTitle = document.getElementById("ctl00_tbTitle");
    if (cbList==null)
    {
        return false;
    }
    if (cbList.options.selectedIndex == -1) // aucun véhicule sélectionné
    {
        return false;
    }   
    var ids = new Array(GetVehiUnitId(cbList.options[cbList.options.selectedIndex].value));
    var dtFrom, dtTo;
    title = "Rapport quotidien";
    if (sTitle != null)
    {
        if (sTitle.value != "")
        {
            title = sTitle.value;
        }
    }
    dtFrom = new Date();
    dtTo = dtFrom - 1;
    WS_GetUnits.GetCRA24H(0, title, ids,OnMethodGetCRASucceeded, OnMethodError);
   return true;                            
}

function GetCRAWeek() {
    var btnExtract = document.getElementById("btnExtractReport");
    if (btnExtract != null)
    {
        btnExtract.disabled = true;
    }
    
    var title;
    var cbList = document.getElementById("ctl00_ddlVehicles");
    var sTitle = document.getElementById("ctl00_tbTitle");
    if (cbList==null)
    {
        return false;
    }
   
    var ids = new Array(GetVehiUnitId(cbList.options[cbList.options.selectedIndex].value));
    var dtFrom, dtTo;
    title = "Rapport hebdomadaire";
    if (sTitle != null)
    {
        if (sTitle.value != "")
        {
            title = sTitle.value;
        }
    }
    dtFrom = new Date();
    dtTo = dtFrom - 1;
    WS_GetUnits.GetCRA7J(0, title, ids,OnMethodGetCRASucceeded, OnMethodError);
   return true;                            
}

function OnMethodGetCRASucceeded(result, eventArgs) {
    var sPDFFile = result + ".PDF";
    var largeur, hauteur, x, y;
    
    var sOptions, sNom;
    var panVehi  = document.getElementById("panSelectVehi");
    
    var imgLoading = document.getElementById("ImgLoading");
    if (imgLoading != null)
    {
        imgLoading.style.display="none";
    }
    var btnExtract = document.getElementById("btnExtractReport");
    if (btnExtract != null)
    {
        btnExtract.disabled = false;
    }
    
    largeur = parseInt(window.screen.width * 0.7);
    hauteur = parseInt(window.screen.height * 0.7);
    x = parseInt(window.screen.width * 0.15);
    y = parseInt(window.screen.height * 0.2);
    //menubar=no, 
    sOptions = "status=no, menubar=no, titlebar=no, location=no, toolbar=no, directories=no, width=" + largeur + ", height=" + hauteur + ", left=" + x + ",top=" + y;
    sNom = 'Rapport_quotidien';
    window.open(sPDFFile, sNom, sOptions);
    
    if (panVehi != null)
    { // on cache le panel de sélection du véhi pour génération rapport
        panVehi.style.display = "none"; 
    }
    //SelectMenuItem(0);
    SelectMenuCarto();
    
    WS_GetMap.ActiveTimerCarto(true, OnMethodSuccess, OnMethodError);
}

function CenterMap(sender, xCenter, yCenter, bCenterAll) {
    if (bCenterAll) {
        var bounds = new GLatLngBounds();
        var tab = locations;
        for(var i = 0; i < tab.length; i++) {
            if(!bounds.containsLatLng(tab[i].getLatLng())) {
                //alert("extend "+i+" à lat:"+tab[i].getLatLng().lat()+" lon:"+tab[i].getLatLng().lng());
                bounds.extend(tab[i].getLatLng());
            }
        }
        var center = bounds.getCenter();
        var SW = bounds.getSouthWest();
        var NE = bounds.getNorthEast();
        var larg = NE.lng()-SW.lng();
        var haut = ((NE.lat() - SW.lat())*3)/2;
        if(larg>0.05 && haut > 0.05) {
            var coef = haut>larg?haut:larg;
            coef = 1/(coef/140);
            coef = calcBase2(coef);
        } else {
            coef = 12;
        }
        //alert("centermap ! carré de"+larg+" par "+haut+" soit un coef de "+coef+" centre : et "+center.lat()+", "+center.lng());
        
        
       if (locations.length >0) {
            if(map != null) {
                map.setCenter(center, coef);
            }
            if (mapRapport != null)
            {
                mapRapport.setCenter(center, coef);
            }
       }
    }
    else {
        var center = new GLatLng(yCenter/100000, xCenter/100000);
        if(map != null) {
            map.setCenter(center, 18);
        }
        if (mapRapport != null)
        {
            mapRapport.setCenter(center, 18);
        }

    }
    bFirst = false;
}

function calcBase2(input) {
    res = 1;
    while((input = input/2) >= 1) {
        res++
    }
    return res;
}

function HidePanSelectVehi()
{
    var panSelectVehi = document.getElementById("panSelectVehi"); 
    panSelectVehi.style.display = "none";
}

function CenterAddress() {
    var tZC = document.getElementById("txtZipCode"); 
    var tLOC = document.getElementById("txtLocality"); 
    var tADR = document.getElementById("txtAddress"); 
    var panSA = document.getElementById("panSA"); 
    
    panSA.style.display = "none";
    WS_GetMap.GeocodeEx("F", "", tZC.value, tLOC.value, "", tADR.value, "", 10000, OnMethodCenterAddressSucceeded); 
    
   
    tZC.value = "";
    tLOC.value = "";                          
    tADR.value = "";                          
}

function OnMethodSucceeded(result, eventArgs) 
{
    var hfLeft = document.getElementById(CPH+"HF_ImgMapLeft"); 
    var hfTop = document.getElementById(CPH+"HF_ImgMapTop"); 
    var hfRight = document.getElementById(CPH+"HF_ImgMapRight"); 
    var hfBottom = document.getElementById(CPH+"HF_ImgMapBottom"); 

    document.images["ImgMap"].src=result.sUrl;  
    hfLeft.value = result.iLeft;
    hfTop.value = result.iTop;
    hfRight.value = result.iRight;
    hfBottom.value = result.iBottom;
    var img = document.getElementById("ImgMap"); 
    if (img != null)
    {
        img.style.display = "";
    }   
}


function OnMethodCenterAddressSucceeded(result, eventArgs)
{
    var Res = result;
    if (Res != null)
    {
        CenterMap("OnMethodCenterAddressSucceeded", Res.x, Res.y, false);
    }
}

function OnMethodFailed(error) {
   alert(error.get_message());
}

function CancelMapCentering()
// Cette fonction annule les centrages de cartographie en cours.
// Cela concerne aussi bien le centrage sur tous les objets que le centrage sur un véhicule.
{
    var tbCenterAll = document.getElementById(CPH_+"HF_ImgMapCenterAll"); 
    var tbCenterX = document.getElementById(CPH_+"HF_ImgMapCenterX"); 
    var tbCenterY = document.getElementById(CPH_+"HF_ImgMapCenterY");
    tbCenterAll.value = "0";
    tbCenterX.value = "99999999";
    tbCenterY.value = "99999999";    
}


function ShowpanCarto()
{
    var img = document.getElementById("panCarto"); 
    //img.style.display = "none";
    img.style.visibility = "false";
//    img.style.display = "block";
    
}

  function toggle( targetId ){
  if (document.getElementById){
        target = document.getElementById(targetId);
        if (target != null)
        {
           if (target.style.display == "none"){
              target.style.display = "block";
           } else {
              target.style.display = "none";
           }
        }
     }
  }


function ShowMap()
{
    var img = document.getElementById("ImgMap"); 
    img.style.display = "block";
//    img.style.display = "block";
    
}
function HideMap()
{
    var img = document.getElementById("ImgMap"); 
    img.style.display = "none";
//    img.style.display = "block";
    
}

  
function ImageMapMouseMove()
{
    // navigator.appname
    // .NET Request
    var labPos = document.getElementById("labPos"); 
    if (!e) var e = window.event;
    if (e.pageX || e.pageY)
    {
        posx = e.pageX;
        posy = e.pageY;
    }
    else if (e.clientX || e.clientY)
    {
        posx = e.clientX;
        posy = e.clientY;
    }
    //alert(posx + " " + posy);
    labPos.value = posx + " " + posy;
    //labPos.value=posx + " " + posy;
}

function OnRapport24H()
{
    //alert("Rapport 24 heures");
    window.open(page,"nom_popup","menubar=no, status=no, scrollbars=no, menubar=no, width=200, height=100");
//    alert("Rapport 24 heures après");
}

 function isPostBack()
 {
  if ( !document.getElementById(CPH_ + 'clientSideIsPostBack') )
   return false;

  if ( document.getElementById(CPH_ + 'clientSideIsPostBack').value == 'Y' )
   return true;
  else
   return false;
 }

// Initializes global variables and session state.
function pageLoad()
{
    //var img = document.getElementById("ImgMap"); 
    //var hmMapWidth2 = document.getElementById("labSize"); 
    //ResizeComponents(); 
    
//    var logo = document.getElementById("header_left");
//    logo.style.background = 'App_Themes/default/Images/menu_item1_n.png';
//    logo.style.background = 'url(images/capteur.png)';
       
     
    var selMenu=document.getElementById(MASTER_PREFIX + "HF_select_menu");
    menu_selected = -1;
    if (selMenu != null)
    {
        if (selMenu.value != "")
        {
            menu_selected = selMenu.value;
        }
        if (menu_selected != -1)
        {
            SelectCurrentMenuItem();
        }
        else {initMap();}
    }
    else
    {
//        alert("pageLoad HF_select_menu inconnu");
    }
    
    var panCentrageAdresse = document.getElementById("panSA"); 
    if (panCentrageAdresse != null)
    {
        panCentrageAdresse.style.display = "none";
    
    }
    var img = document.getElementById("ImgMap"); 
    if (img != null)
    {
        img.style.display = "none";
    }
    
    
    
    var panReport = document.getElementById(CPH_ + "panReport"); 
    if (panReport != null)
    {
        panReport.style.display = "none";
    
    }
    var hf_userid = document.getElementById("ctl00_" + "HF_session_userid");
    var hf_sessionid = document.getElementById("ctl00_" + "HF_session_sessionid");
    var hf_accountname = document.getElementById("ctl00_" + "HF_session_accountname");
    
    ResizeComponents();

        if (menu_selected != -1)
        {
            updateMap();
        }
/*
    if (bFirst)
    {
        if (menu_selected != -1)
        {
            updateMap();
        }
    }
  */
    if (menu_selected != -1)
    {
        WS_GetUnits.GetSessionValue("PAGE_LOADED", OnMyLoadPage, OnMethodError);       
    }
    // initialisation locale page par page
}

function pageResize()
{
    ResizeComponents();
}


function ResizeComponents()
{
// Redimensionne la zone des véhicules et la cartographie
    var xheader = document.getElementById("header");
    var xfooter = document.getElementById("footer");
    var xmain = document.getElementById("main");
    var xmaincontent = document.getElementById("main_acc");
    var xlogincontainer = document.getElementById("logincontainer");
    var xxlcol = document.getElementById("xlcol");    
    var xcontent = document.getElementById("content");
    var xlcol = document.getElementById("column_l");
    var xlcolcontent = document.getElementById("ctl00_ContentPlaceHolder1_column_l_content");
    var xrcol = document.getElementById("column_r");
    var xcarto = document.getElementById("carto");
    var xcartoplanif = document.getElementById("divDroitHaut2");
    var xdataplanif = document.getElementById("divDroitHaut");
    var xcartorapport = document.getElementById("panRapportCarto");
    var xdivcartorapport = document.getElementById("divRapportCarto");
    
    var xcolLeft = document.getElementById("colLeft");
    var xcartorapportmain = document.getElementById("panRapportCartoMain");
    var xpanSpeedReport = document.getElementById("panSpeedReport");
    var bmpsynop = document.getElementById("ImgSpeedReport"); 
    var selectAllPositions = document.getElementById("selectAllPositions"); 
    var panSelectAllPositions = document.getElementById("panSelectAllPositions"); 
    
    // si écran de login, on masque le menu
    var login = document.getElementById("ctl00_ContentPlaceHolder1_Wuc_login1_btnConnect");
    var tabMenu = document.getElementById("tabMenu");
    if (tabMenu != null)
    {
        if (login != null)
        {         tabMenu.style.display="none";}
        else {    tabMenu.style.display="block";}
    }
    
    var xwelcome = document.getElementById("labelWelcome");
    var psv = document.getElementById("panSelectVehi");
    var divRapportCarto = document.getElementById("divRapportCarto");
    
    var wScreen = getWindowWidth() * 0.99;
    var hScreen = getWindowHeight();
    var iMarginH = 5;
    var iMarginV = 5;
    var hearder_height = 81;
    var footer_height = 60 + 5;
    var footer_width = 800 + 5;
    var H;
    
    if (psv != null)
    {
        psv.style.posLeft = (wScreen - psv.clientWidth) / 2;
        psv.style.posTop = (hScreen - psv.clientHeight) / 2;
    }
    H = hScreen - hearder_height
                - footer_height
                - (3 * iMarginV);

    //alert("hscreen="+hScreen + " screen.availHeight=" + screen.availHeight);
    //document.body.style.height = hScreen;
    if (xmain != null)
    {
        xmain.style.height = hScreen  + "px";//H
    }
    if (xmaincontent != null)
    {
        xmaincontent.style.height = hScreen - hearder_height + "px";
    }
    if (xcontent != null)
    {
        xcontent.style.height = H + "px";
    }
    if (xcarto != null)
    {
        if (xlcol != null)
        {
            xlcol.style.top = hearder_height + iMarginV + "px";
            xlcol.style.left = iMarginH + "px";
            xlcol.style.height = H + "px";
            xlcol.style.height = H + "px";
            xlcolcontent.style.height = H-25 + "px";

        }
       
        if (xrcol != null)
        {
            xrcol.style.top = xlcol.style.posTop;
            xrcol.style.left = parseInt(xlcol.style.width) + (2 * iMarginH) + "px";
            xrcol.style.width = wScreen - parseInt(xlcol.style.width) - (3 * iMarginH) + "px";
            xrcol.style.height = H + "px";
            xcarto.style.width =xrcol.style.width;
            xcarto.style.height = H + "px";
        }
    }
    if (xfooter != null) 
    {
        xfooter.style.top = hScreen - footer_height + "px";
        xfooter.style.left = wScreen - footer_width + "px";//iMarginH;
        //xfooter.style.width = wScreen - 250 - (3 * iMarginH) + "px";    
    }    
    if (divRapportCarto != null)
    {
        divRapportCarto.style.height = H + "px";
        var colLeft = document.getElementById("colLeft");
        colLeft.style.height = H + "px";
        var panRapportsLeft = document.getElementById("panRapportsLeft");
        panRapportsLeft.style.height = H + "px";
        var panVehicule = document.getElementById("ctl00_ContentPlaceHolder1_panVehicule");
        panVehicule.style.height = parseInt(panRapportsLeft.style.height) - 120 - 65 + "px";        
        
        var cbVehicles = document.getElementById("ctl00_ContentPlaceHolder1_cbVehicles");
        cbVehicles.style.height = parseInt(panVehicule.style.height) - 20 -30  + "px";
    }
    
    
    if (xcartoplanif != null)
    {
        xcartoplanif.style.width = wScreen - 250 - (4 * iMarginH) + "px";
        xcartoplanif.style.height = H + "px";    
    }    
    if (xdataplanif != null)
    {
        xdataplanif.style.width = wScreen - 250 - (4 * iMarginH) + "px";
        xdataplanif.style.height = H + "px";                    
    }
    
    if (mapPlanif != null) 
    {
        mapPlanif.updateSize();
    }

    if (xcartorapport != null)
    {
        xcartorapport.style.width = wScreen - 450 - (5*iMarginH) + "px";// -  (2 * iMarginH) + "px";
        if (bmpsynop.height == 0)
        {
            xcartorapport.style.height = H - 2*iMarginV + "px";
        }
        else
        {
            xcartorapport.style.height = H - bmpsynop.height - 3*iMarginV + "px";
        } 
        xcartorapportmain.style.width =      xcartorapport.style.width;
        xcartorapportmain.style.height = H  + "px";
        xdivcartorapport.style.height = H + "px";
        xpanSpeedReport.style.width = xcartorapport.style.width;
        bmpsynop.width = wScreen - 450 - (5*iMarginH);// -  (2 * iMarginH);
        xcolLeft.style.height = xdivcartorapport.style.height;
    }    

    if (mapRapport != null) 
    {
        //mapRapport.updateSize();
    }

    if (map != null) 
    {
        //map.updateSize();
    }
    if (selectAllPositions != null)
    {
//        selectAllPositions.size = parseInt(panSelectAllPositions.style.pixelHeight/20);
        selectAllPositions.size = (H - 130 - 50) / 14;
    }
    
    if (xlogincontainer != null)
    {
            if (xxlcol != null)
            {
                xlogincontainer.style.left = parseInt(xxlcol.style.width) + 
                                                        parseInt((wScreen - parseInt(xxlcol.style.width) -
                                                        parseInt(xlogincontainer.style.width) - 10)/2) + "px";
            } else {
                xlogincontainer.style.left = parseInt((wScreen - 
                                                        parseInt(xlogincontainer.style.width) - 10)/2) + "px";
            }
            xlogincontainer.style.top = hearder_height + //parseInt(xheader.style.height) + 
                                        parseInt((H - parseInt(xlogincontainer.style.height))/2) + "px";
    }
    
}

function GetSize()
{}



// Gets the session state value.
function GetSessionValue(key) 
{
    PageMethods.GetSessionValue(key, 
        OnSucceeded, OnFailed);
}

//Sets the session state value.
function SetSessionValue(key, value) 
{
    PageMethods.SetSessionValue(key, value, 
        OnSucceeded, OnFailed);
    alert("SetSessionValue");
}

// Callback function invoked on successful 
// completion of the page method.
function OnSucceeded(result, userContext, methodName) 
{
    if (methodName == "GetSessionValue")
    {
        displayElement.innerHTML = "Current session state value: " + 
            result;
    }
}

// Callback function invoked on failure 
// of the page method.
function OnFailed(error, userContext, methodName) 
{
    if(error !== null) 
    {
        displayElement.innerHTML = "An error occurred: " + 
            error.get_message();
    }
}

if (typeof(Sys) !== "undefined") Sys.Application.notifyScriptLoaded();

///
/// Gestion des menus
///
function SelectMenuCarto()
{
//    WS_GetMap.ActiveTimerCarto(true, OnMethodSuccess, OnMethodError);
//    document.location.href="main.aspx";
    WS_GetUnits.IsFunctionAllowed(1, OnMethodIsGeolocTRAllowedSucceeded, OnMethodAllowedError);  
    SelectMenuItem(0);              
}

function SelectMenuRapports()
{
    WS_GetUnits.IsFunctionAllowed(4, OnMethodIsRapportAllowedSucceeded, OnMethodAllowedError);                
    //WS_GetMap.ActiveTimerCarto(false, OnMethodSuccess, OnMethodError);
    //document.location.href="rapports.aspx";
    SelectMenuItem(3);              
}

function SelectMenuRapports24H()
{
    WS_GetUnits.IsFunctionAllowed(2, OnMethodIsRapport24HAllowedSucceeded, OnMethodAllowedError);                
    SelectMenuItem(1);              
}

function SelectMenuRapports7J()
{
    WS_GetUnits.IsFunctionAllowed(3, OnMethodIsRapport7JAllowedSucceeded, OnMethodAllowedError);                
    SelectMenuItem(2);              
}

function SelectMenuEntretien()
{
//    WS_GetMap.ActiveTimerCarto(false, OnMethodSuccess, OnMethodError);
//    document.location.href="entretien.aspx";
    WS_GetUnits.IsFunctionAllowed(6, OnMethodIsEntretienAllowedSucceeded, OnMethodAllowedError);        
    SelectMenuItem(5);              
}

function SelectMenuReglages()
{
    //WS_GetMap.ActiveTimerCarto(false, OnMethodSuccess, OnMethodError);
    //document.location.href="reglages.aspx";
    WS_GetUnits.IsFunctionAllowed(5, OnMethodIsReglageAllowedSucceeded, OnMethodAllowedError);        
    SelectMenuItem(4);              
}

function SelectMenuPlanif()
{
    //WS_GetMap.ActiveTimerCarto(false, OnMethodSuccess, OnMethodError);
    //document.location.href="planif.aspx";
    WS_GetUnits.IsFunctionAllowed(8, OnMethodIsPlanifAllowedSucceeded, OnMethodAllowedError);        
    SelectMenuItem(7);              
}

function SelectMenuAdmin()
{
//    WS_GetMap.ActiveTimerCarto(false, OnMethodSuccess, OnMethodError);
    //document.location.href="admin.aspx";
    WS_GetUnits.IsFunctionAllowed(7, OnMethodIsAdminAllowedSucceeded, OnMethodAllowedError);        
    SelectMenuItem(6);              
}

function SelectMenuDisconnect()
{
    WS_GetMap.ActiveTimerCarto(false, OnMethodSuccess, OnMethodError);
    document.location.href="login.aspx";
}

function SelectCarto()
{
    bFirst = true;    
    WS_GetMap.ActiveTimerCarto(true, OnMethodSuccess, OnMethodError);
    if (document.location.href.lastIndexOf("main.aspx")==-1)
    {
        document.location.href="main.aspx";
    }
}

function SelectCurrentMenuItem()
{
    var selMenu=document.getElementById(MASTER_PREFIX + "HF_select_menu");
    if (selMenu!=null)
    {
            SelectMenuItem(selMenu.value);
    }
}


function SelectMenuItem(indexMenu)
{
    if (indexMenu == "")
    {
        indexMenuToDisplay = 0;
    }
    else
    {
        indexMenuToDisplay = indexMenu;
    }
    WS_GetUnits.GetSessionValue("SELECT_MENU", OnSelectMenuItemSuccedeed, OnMethodError);

}

function OnSelectMenuItemSuccedeed(result, eventArgs)
{
    //return;
    
    selMenu = result; // menu actuel
    var cbList = document.getElementById("ctl00_ddlVehicles");
    var bHasVehicles = true;
    if (cbList==null)
    {
        bHasVehicles = false;
    }
    if (cbList.options.length == 0) // aucun véhicule 
    {
        bHasVehicles = false;
    }       
    //alert("Menu actuel=" + selMenu + " Menu souhaité" + indexMenuToDisplay);
    var iSelMenu = parseInt(selMenu);
    for(var i=0;i<menu_names.length;i++)
    {
        mi = document.getElementById("ctl00_" + menu_names[i]);
        if (mi != null)
        {
            if (i==indexMenuToDisplay)
            {// on sélectionne
                mi.src = menu_URLSelect[i];   
                menu_selected = i; 
            }
            else
            { // on désélectionne
                mi.src = menu_URLNormal[i];    
            }
        }
    }
   
  WS_GetUnits.SetSessionValue("SELECT_MENU", indexMenuToDisplay, OnMethodSuccess, OnMethodError); 
}

function setRMSSession(key, value) {
  WS_GetUnits.SetSessionValue(key, value, OnMethodSuccess, OnMethodError); 
}

function OnMethodSuccess(result, eventArgs)
{
}

function OnMethodError(error) {

}

function OnMethodAllowedError(error)
{
   //alert("Erreur :"+ error.get_message());
}

function OnMethodIsGeolocTRAllowedSucceeded(result, eventArgs) 
{ // Activation de l'écran GEOLOC TEMPS REEL
    if (result==1)
    {
        var panVehi = document.getElementById("panSelectVehi");
        if (panVehi != null)       
        {
            panVehi.style.display="none";
        }
        WS_GetMap.ActiveTimerCarto(true, OnMethodSuccess, OnMethodError);
        SelectCarto();
    }
    else
    {
        alert("Acces retreint - Contactez-nous pour acceder a cette fonction.");
    }
}

function OnMethodIsRapport24HAllowedSucceeded(result, eventArgs) 
{ // Activation de l'écran RAPPORT 24H
    if (result==1)
    {
        SelectCarto();
        
        var panVehi = document.getElementById("panSelectVehi");
        var title =  document.getElementById("ctl00_tbTitle");
        var but =  document.getElementById("btnExtractReport");

        //WS_GetMap.ActiveTimerCarto(false);
        if (panVehi != null)
        {
            title.value="Rapport quotidien";
            but.onclick = function(){GetCRA();};
            panVehi.style.display="block";
        }
    }
    else
    {
        alert("Acces retreint - Contactez-nous pour acceder a cette fonction.");
    }
    
}

function OnMethodIsRapport7JAllowedSucceeded(result, eventArgs) 
{ // Activation de l'écran RAPPORT 7J
    if (result==1)
    {
        SelectCarto();
        
        var panVehi = document.getElementById("panSelectVehi");
        var title =  document.getElementById("ctl00_tbTitle");
        var but =  document.getElementById("btnExtractReport");
        
        if (panVehi != null)
        {
            title.value="Rapport hebdomadaire";
            but.onclick = function(){GetCRAWeek();};
            panVehi.style.display="block";
        }
    }
    else
    {
        alert("Acces retreint - Contactez-nous pour acceder a cette fonction.");
    }
    
}



function OnMethodIsAdminAllowedSucceeded(result, eventArgs) 
{ // Activation de l'écran ADMIN
    if (result==1)
    {
        WS_GetMap.ActiveTimerCarto(false, OnMethodSuccess, OnMethodError);
        document.location.href="admin.aspx";
    }
    else
    {
        alert("Acces retreint - Contactez-nous pour acceder a cette fonction.");
    }
}


function OnMethodIsRapportAllowedSucceeded(result, eventArgs) 
{ // Activation de l'écran RAPPORT
    if (result==1)
    {
        WS_GetMap.ActiveTimerCarto(false, OnMethodSuccess, OnMethodError);
        document.location.href="rapports.aspx";
    }
    else
    {
        alert("Acces retreint - Contactez-nous pour acceder a cette fonction.");
    }
}

function OnMethodIsReglageAllowedSucceeded(result, eventArgs) 
{ // Activation de l'écran REGLAGE
    if (result==1)
    {
        WS_GetMap.ActiveTimerCarto(false, OnMethodSuccess, OnMethodError);
        document.location.href="reglages.aspx";
    }
    else
    {
        alert("Acces retreint - Contactez-nous pour acceder a cette fonction.");
    }
}

function OnMethodIsPlanifAllowedSucceeded(result, eventArgs) 
{ // Activation de l'écran PLANIFICATION
    if (result==1)
    {
        WS_GetMap.ActiveTimerCarto(false, OnMethodSuccess, OnMethodError);
        document.location.href="Planner.aspx";
    }
    else
    {
        alert("Acces retreint - Contactez-nous pour acceder à cette fonction.");
    }
}

function OnMyLoadPage(result, eventArgs) 
{
    // result vaut l'ancienne page
    // indexMenuToDisplay vaut la page en cours
    var selMenu=document.getElementById(MASTER_PREFIX + "HF_select_menu");
    
    if (selMenu.value != result)
    {   // première activation ECRA PLANIFICATION
        if (selMenu.value == "8")
        {
            setVisitsLocations();
        }
    
    }
    // on met à jour la page actuelle
    WS_GetUnits.SetSessionValue("PAGE_LOADED", selMenu.value, OnMethodSuccess, OnMethodError); 
}

function OnMethodIsEntretienAllowedSucceeded(result, eventArgs) 
{
    if (result==1)
    {
        WS_GetMap.ActiveTimerCarto(false, OnMethodSuccess, OnMethodError);
        document.location.href="entretien.aspx";
    }
    else
    {
        alert("Acces retreint - Contactez-nous pour acceder a cette fonction.");
    }
}

function MouseOver(indexMenu)
{
    mi =document.getElementById(menu_names[indexMenu]);
    if (mi == null) 
    {
        mi = document.getElementById(MASTER_PREFIX + menu_names[indexMenu]);
    }
    if (mi != null)
    {
        if (indexMenu  != menu_selected)
        {
            mi.src = menu_URLOver[indexMenu];
        }
    }
}

function MouseOut(indexMenu)
{
    mi = document.getElementById(menu_names[indexMenu]);
    if (mi == null) 
    {
        mi = document.getElementById(MASTER_PREFIX + menu_names[indexMenu]);
    }
    if (mi != null)
    {
        if (indexMenu != menu_selected)
        {
            mi.src = menu_URLNormal[indexMenu];
        }
    }
}

function InitMenu()
{
// Initialise les menus avec les valeurs renseignées dans les variables en haut de ce fichier
    for(var i=0;i<menu_names.length;i++)
    {
        mi = document.getElementById(menu_names[i]);
        if (mi != null)
        {
            mi.src = menu_URLNormal[i];      
            mi.onmouseover = "alert('mouseover');"; //"MouseOver(" + i + ")";
            mi.onmouseout = "MouseOut(" + i + ");";
            mi.onclick = "SelectMenuItem(" + i + ");";
        
        
        }
    }

}


function ClearTours() { 
    // supprimer les tournées en cours
    var vector = com.ptvag.webcomponent.map.vector;
    var vectorLayer = map.getLayer("vector");
    vectorLayer.removeAllElements();

    xmapsteps = new Array();
}


function Hello()
{
    WS_GetUnits.GetHello2(HelloSucceeded);    
}

function selectzone() {
    //z = document.getElementById(CPH_ + "ddlZoneExport");
    //alert(z.value);
    //var izone = parseInt(z.value);
    if (WS_GetUnits ==null)
    {
    alert("null");
    }
    WS_GetUnits.HelloWorld(onhw, OnMethodErrorZone);
    //WS_GetUnits.GetZone(izone, onselectzoneSucceeded, OnMethodErrorZone);  
}


function OnMethodErrorZone(result)
{
    alert("OnMethodErrorZone");
}
function onhw(result)
{
    alert(result);
}





//
//
// Fonctions de la pages rapports
//
//
//
function SelectReport(ireport)
{
    var title="";
    var colorSelected = "white";
    var colorUnselected = "white";
    var titleSelected = "Title" + (ireport+1);
    var titleTmp;
    var bVitesse = false;
    var bZone = false;
    var bSynthese = false;
    var bDetail = false;

    //debugger;
    document.getElementById("HF_IDREPORT").value = ireport;
    for(var i=1;i<=6;i++)
    {
        titleTmp = "Title" + i;
        if (titleTmp == titleSelected)
        {
            document.getElementById(titleTmp).style.color= colorSelected;
            document.getElementById("tab" + titleTmp).style.background ="url(App_Themes/default/Images/barre_haut_or_200x24.png)";
            document.getElementById("ctl00_ContentPlaceHolder1_panVehiDetail" + i).style.backgroundImage ="url(App_Themes/default/Images/barre_bas_or_200x150.png)";
            title = document.getElementById(titleTmp).title;
        }
        else
        {
            document.getElementById(titleTmp).style.color= colorUnselected;
            document.getElementById("tab" + titleTmp).style.backgroundImage ="url(App_Themes/default/Images/barre_haut_200x24.png)";
            document.getElementById("ctl00_ContentPlaceHolder1_panVehiDetail" + i).style.backgroundImage ="url(App_Themes/default/Images/barre_bas_200x150.png)";
        }                                    
    }
    if (ireport==0) // vitesse
    {
        bVitesse = true; 
    }
    if (ireport==1) // zone
    {
        bZone = true;
    }
    if (ireport==3)
    {
        bSynthese = true;
    }
    if (ireport==4)
    {
        bDetail = true;
    }

    document.getElementById("ctl00_ContentPlaceHolder1_labTitle").innerText = document.getElementById("ctl00_ContentPlaceHolder1_labTitle").textContent = title;
    if (bVitesse)
        document.getElementById("ctl00_ContentPlaceHolder1_panVitesse").style.display="block";
    else
        document.getElementById("ctl00_ContentPlaceHolder1_panVitesse").style.display="none";               


    if (bSynthese)
        document.getElementById("ctl00_ContentPlaceHolder1_panSynthese").style.display="block";
    else
        document.getElementById("ctl00_ContentPlaceHolder1_panSynthese").style.display="none";               

    divRap = document.getElementById("divRapports");
    divRapDetail = document.getElementById("divRapportDetail");
    divRapCarto = document.getElementById("divRapportCarto");
    divRapLeft = document.getElementById("panRapportsLeft");
    panVehicles = document.getElementById("ctl00_ContentPlaceHolder1_panVehicule");
    panDate = document.getElementById("ctl00_ContentPlaceHolder1_panDate");
    
    if (ireport==4)  // RAPPORT DETAIL
    {
        divRap.style.display="block"; 
        if (divRapDetail != null)
        {
            divRapDetail.style.display="block";
        }
        if (divRapCarto != null)
        {
            divRapCarto.style.display="none";
        }           
        if (panVehicles != null)
        {
            panVehicles.style.display="none";
        }           
        if (panDate != null)
        {
            panDate.style.display="none";
        }           
    }
    else if (ireport==5)  // RAPPORT CARTO
    {
        divRap.style.display="none"; 
        if (divRapDetail != null)
        {
            divRapDetail.style.display="none";
        }
        if (divRapCarto != null)
        {
            divRapCarto.style.display="block";
        } 
        if (panVehicles != null)
        {
            panVehicles.style.display="none";
        }           
        if (panDate != null)
        {
            panDate.style.display="none";
        }           
        setRapportLocations();                               
    }
    else
    {
        if (divRapDetail != null)
        {
            divRapDetail.style.display="none";
        }
        if (divRapCarto != null)
        {
            divRapCarto.style.display="none";
            divRap.style.display="block";    
        }
        if (panVehicles != null)
        {
            panVehicles.style.display="block";
        }           
        if (panDate != null)
        {
            panDate.style.display="block";
        }           
    }
}
//
//
//

function GetKMLFile()
{
    var imgLoading = document.getElementById("ImgCalcCarto");
    if (imgLoading != null)
    {
        imgLoading.style.display="block";
    }
    var hrefKML = document.getElementById("hrefkml");
    if (hrefKML != null)
    {
        hrefKML.disabled="disabled";
    }
    var ddlvehicarto = document.getElementById(CPH_ + "ddlVehiCarto"); 
    var txtdatecarto = document.getElementById(CPH_ + "txtDateCarto"); 
    var txtdatecarto2 = document.getElementById(CPH_ + "txtDateCarto2");
    var txtDateTo = txtdatecarto.value;
    if (txtdatecarto2.style.display != "none")
    { 
        txtDateTo = txtdatecarto2.value;
    }
    
    WS_GetUnits.GetKMLFile(parseInt(ddlvehicarto.value), 
                            txtdatecarto.value,
                            txtDateTo,
                            document.getElementById("cbStop").checked,
                            document.getElementById("cbPositions").checked,
                            document.getElementById("cbIti").checked,
                            OnMethodGetKMLFileSucceeded, OnMethodError);
                            

}

function OnMethodGetKMLFileSucceeded(result, eventArgs) {

    var imgLoading = document.getElementById("ImgCalcCarto");
    if (imgLoading != null)
    {
        imgLoading.style.display="none";
    }
    
    var hrefKML = document.getElementById("hrefkml");
    if (hrefKML != null)
    {
        hrefKML.disabled="";
        hrefKML.href=result;
    }
    return result;
}


function ReportGetCRA()
{
    //debugger;
    var title;
    var cbv = document.getElementById("ctl00_ContentPlaceHolder1_ddlVehiCarto");

    var btnExtract = document.getElementById("btnExtractReport");
    if (btnExtract != null)
    {
        btnExtract.disabled = true;
    }

    var imgLoading = document.getElementById("ImgLoading");
    if (imgLoading != null)
    {
        imgLoading.style.display="block";
    }

    var imgLoading = document.getElementById("ImgCalcCarto");
    if (imgLoading != null)
    {
        imgLoading.style.display="block";
    }

   
    var ids = new Array(); // = new Array(GetVehiUnitId(cbList.options[cbList.options.selectedIndex].value));
    var idx = 0;
    if (cbv==null) {alert("cbv null");}
    if (cbv.options==null) {alert("cbv.options null");}
    

    for(var i=0;i<=cbv.options.length;i++)
    {
        //debugger;
        var cbItem = document.getElementById("ctl00_ContentPlaceHolder1_cbVehi" + i);
        if (cbItem != null)
        {
            if (cbItem.checked == true)
            {
                var cbItemVal = document.getElementById("ctl00_ContentPlaceHolder1_cbVehi" + i + "hf");
                if (cbItemVal != null)
                {
                    ids[idx] = cbItemVal.value;
                    idx = idx + 1;
                }
            }
        }                    
    }
    title = "Rapport personnalisé";
    //debugger;
    if (document.getElementById("HF_IDREPORT").value == "0") // VITESSE
    {
        title = "Rapport de vitesse";
        WS_GetUnits.GetCRA(1,   parseInt(document.getElementById("ctl00_ContentPlaceHolder1_ddlVMax").value),
                                title, ids, 
                                document.getElementById("ctl00_ContentPlaceHolder1_dateFrom").value,
                                document.getElementById("ctl00_ContentPlaceHolder1_dateTo").value,
                                OnMethodGetCRASucceeded, OnMethodError);
    }
    if (document.getElementById("HF_IDREPORT").value == "1") // ZONE
    {
        WS_GetUnits.GetCRA(2,   -1, title, ids, 
                                document.getElementById("ctl00_ContentPlaceHolder1_dateFrom").value,
                                document.getElementById("ctl00_ContentPlaceHolder1_dateTo").value,
                                OnMethodGetCRASucceeded, OnMethodError);
    }
    if (document.getElementById("HF_IDREPORT").value == "2") // CAPTEUR
    {
        WS_GetUnits.GetCRA(3,   -1, title, ids, 
                                document.getElementById("ctl00_ContentPlaceHolder1_dateFrom").value,
                                document.getElementById("ctl00_ContentPlaceHolder1_dateTo").value,
                                OnMethodGetCRASucceeded, OnMethodError);
    }
    if (document.getElementById("HF_IDREPORT").value == "3") // SYNTHESE
    {
        var cbDisplayDetail = document.getElementById("ctl00_ContentPlaceHolder1_cbSyntheseSections");
        if (cbDisplayDetail != null) 
        {
            if (cbDisplayDetail.checked == true)
            {
                WS_GetUnits.GetCRA(0,   -1, title, ids, 
                                        document.getElementById("ctl00_ContentPlaceHolder1_dateFrom").value,
                                        document.getElementById("ctl00_ContentPlaceHolder1_dateTo").value,
                                        OnMethodGetCRASucceeded, OnMethodError);
            }
            else
            {
                WS_GetUnits.GetCRA(5,   -1, title, ids, 
                                        document.getElementById("ctl00_ContentPlaceHolder1_dateFrom").value,
                                        document.getElementById("ctl00_ContentPlaceHolder1_dateTo").value,
                                        OnMethodGetCRASucceeded, OnMethodError);
            }
        }
    }
    if (document.getElementById("HF_IDREPORT").value == "4") // DETAILLE
    {
        title = "Rapport détaillé";
        var ddlvehicarto = document.getElementById(CPH_ + "ddlVehiDetail"); 
        var txtdatecarto = document.getElementById(CPH_ + "txtDateDetail"); 
        var ids = new Array();
        ids[0] = parseInt(ddlvehicarto.value);
        WS_GetUnits.GetCRA(4,   -1, title, ids, 
                                txtdatecarto.value,
                                txtdatecarto.value,
                                OnMethodGetCRASucceeded, OnMethodError);
    }

    if (document.getElementById("HF_IDREPORT").value == "5") // HISTORIQUE CARTOGRAPHIQUE
    {
        title = "Rapport cartographique";
        var ddlvehicarto = document.getElementById(CPH_ + "ddlVehiCarto"); 
        var txtdatecarto = document.getElementById(CPH_ + "txtDateCarto"); 
        var txtdatecarto2 = document.getElementById(CPH_ + "txtDateCarto2"); 
        var txtdatecarto2 = document.getElementById(CPH_ + "txtDateCarto2");
        var txtDateTo = txtdatecarto.value;
        if (txtdatecarto2.style.display != "none")
        { 
            txtDateTo = txtdatecarto2.value;
        }        
        var ids = new Array();
        
        ids[0] = parseInt(ddlvehicarto.value);
        WS_GetUnits.GetCRA(7,   -1, title, ids, 
                                txtdatecarto.value,
                                txtDateTo,
                                OnMethodGetCRASucceeded, OnMethodError);
    }
                            
   return true;                            
    
}
                
function OnMethodGetCRASucceeded(result, eventArgs) {
    var sPDFFile = result + ".PDF";
    var largeur, hauteur, x, y;
    var sOptions, sNom;
    
    var btnExtract = document.getElementById("btnExtractReport");
    if (btnExtract != null)
    {
        btnExtract.disabled = false;
    }
    var imgLoading = document.getElementById("ImgLoading");
    if (imgLoading != null)
    {
        imgLoading.style.display="none";
    }
    var imgLoading = document.getElementById("ImgCalcCarto");
    if (imgLoading != null)
    {
        imgLoading.style.display="none";
    }
    
    
    largeur = parseInt(window.screen.width * 0.7);
    hauteur = parseInt(window.screen.height * 0.7);
    x = parseInt(window.screen.width * 0.15);
    y = parseInt(window.screen.height * 0.2);
    //menubar=no, 
    sOptions = "status=no, menubar=no, titlebar=no, location=no, toolbar=no, directories=no, width=" + largeur + ", height=" + hauteur + ", left=" + x + ",top=" + y;
    sNom = 'Rapport_personnalisé';
    if (sPDFFile == ".PDF")
    {
        alert("Aucun rapport n'a pu être généré.");
    }
    else
    {
    sOptions = "status=no, menubar=no, titlebar=no, location=no, toolbar=no, directories=no";
    sNom="Rapport";
        window.open(sPDFFile, sNom, sOptions);
    }
}

function SelectVehicles(chk)
{
    for(var i=0;i<=999;i++)
    {
        var cbId = "ctl00_ContentPlaceHolder1_cbVehi" + i;
        var cb = document.getElementById(cbId);
        if (cb == null)
        {
            break;
        }
        else
        {
            cb.checked = chk;
        }    
       
    }
}

function SelectDrivers(chk)
{
    for(var i=0;i<=999;i++)
    {
        var cbId = "ct100_ContentPlaceHolder1_cbDriver" + i;
        var cb = document.getElementById(cbId);
        if(cb == null)
        {
            break;
        }
        else
        {
            cb.checked = chk;
        }
    }
}

function redirectToSocialReports()
{
    window.location.href='SocialReportsaspx.aspx';
}

