/*********************************************************************************
 Copyright (c) 2002-2005 Armin Burger
 
 Permission is hereby granted, free of charge, to any person obtaining 
 a copy of this software and associated documentation files (the "Software"), 
 to deal in the Software without restriction, including without limitation 
 the rights to use, copy, modify, merge, publish, distribute, sublicense, 
 and/or sell copies of the Software, and to permit persons to whom the Software 
 is furnished to do so, subject to the following conditions:
 
 The above copyright notice and this permission notice shall be included 
 in all copies or substantial portions of the Software.
 
 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS 
 FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHOR OR 
 COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER 
 IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 
 CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
**********************************************************************************/


var gPreloadImgArray = []; 
function preloadImg() {
    var fct = arguments[arguments.length - 1];
    var len = arguments.length - 1;
    var cpt = 0;

    gPreloadImgArray = [];   
    for(var i = 0; i < arguments.length - 1; i++) {
        gPreloadImgArray[i] = new Image();
        gPreloadImgArray[i].onload = function() {
            cpt++;
            if(cpt == len) {
                fct();
            }
        }
        gPreloadImgArray[i].src = arguments[i];
    }
}
/**************************************************** 
 * LOAD MAP IMAGE INTO PARENT WINDOW MAP DIV
 * Reset parameters of some DIV's
 ****************************************************/
function resetMapImgParams() {
    var theMapImgL = document.getElementById("mapimgLayer");
    var theMapImg = document.getElementById("mapImg");
    
    theMapImg.style.width = mapW;
    theMapImg.style.height = mapH;
    
    theMapImgL.style.top  = 0;  
    theMapImgL.style.left = 0;
    theMapImgL.style.width = mapW;
    theMapImgL.style.height = mapH;
    theMapImgL.style.clip = 'rect(auto auto auto auto)';  // NEEDED TO RESET DIV TO NON-CLIPPED AND ORIGINAL SIZE
    
    document.getElementById("zoombox").style.visibility = 'hidden';
    document.getElementById('loading').style.visibility = 'hidden';
    
//    maploading = false;
}

function loadMapImg(mapImgSrc) {
    var theMapImgL = document.getElementById("mapimgLayer");
    var theMapImg = document.getElementById("mapImg");
    
    // RESET MAP DIV TO DEFAULT POSITION AND SIZE
//    theMapImgL.style.top  = 0;  
//    theMapImgL.style.left = 0;
//    theMapImgL.style.width = mapW;
//    theMapImgL.style.height = mapH;
//    theMapImgL.style.clip = 'rect(auto auto auto auto)';  // NEEDED TO RESET DIV TO NON-CLIPPED AND ORIGINAL SIZE
   
    // SWAP MAP IMG
//    theMapImg.style.width = mapW;
//    theMapImg.style.height = mapH;
    //theMapImg.src = mapImgSrc;

/*    if (parseInt(theMapImg.style.width) != mapW)
    {
        resizeDiv(false);
    }  */
    if ((ResizeEncours==0) && (movecarte == true))
    {
        preloadImg(mapImgSrc, function() { crossfade(theMapImg, mapImgSrc, 1, ''); } );
    }
    else
    {
        preloadImg(mapImgSrc, function() { crossfade(theMapImg, mapImgSrc, 0, ''); } );
        //preloadImg(mapImgSrc, function() { theMapImg.src = mapImgSrc; } );
    }
    //    window.parent.document.getElementById("zoombox").style.visibility = 'hidden';
    //alert(theMapImgL.style.clip);
}


function init() {
// BPU

    writeMenu('toc_tree.php?' + SID + '&action=write'+ SID + '&NumMenu=1', '');
    domouseclick('zoomin');
    setButton('zoomin');
    startUp();
    startUpRef();
  //  zoomfullext();
/*    if (arguments.length > 0) {
        var ext = arguments[0]+"+"+arguments[1]+"+"+arguments[2]+"+"+arguments[3];
//        zoom2extent(0,0,ext);
    }                                    */
    resizeDiv(true);

}


function resizeDiv(initmap) {
    // Margins in application window
    var lMargin  = 4; // LEFT
    var mMargin  = 5;  // MIDDLE, between map and toc
    var rMargin  = 15; // RIGHT
    var tMargin  = 10; // TOP
    var bMargin  = 10; // BOTTOM
    var m2Margin = 10; // MIDDLE, between TOC and refmap

    var ImgFlecheH = 9;  //
    var ImgFlecheW = 15; //
    var TailleBordure = 1;//
    
    var winix = document.body.clientWidth;
    var winiy = document.body.clientHeight;

    if (winix < 1 || winiy < 1)  {
        winix = parseInt(window.innerWidth);
        winiy = parseInt(window.innerHeight);
        //alert (winiy + ' - ' + winiy2);
    }
    if ((winiy < 600) || (winix < 800))  {
        winix = 800;
        winiy = 600;
     //   document.body.clientWidth = winix;
     //   document.body.clientHeight = winiy;
    }

    // Element definitions
    //____________________

    //Entete
    var top             = document.getElementById('top');
    var topTout         = document.getElementById('topTout');

    //Carte
    var mapFrame        = document.getElementById('mapFrame');
    var mapimgLayer     = document.getElementById('mapimgLayer');
    var mapImg          = document.getElementById('mapImg');
    var loading         = document.getElementById('loading');
    var zoombox         = document.getElementById('zoombox');

    var panArrowN       = document.getElementById('panArrowN');
    var panArrowS       = document.getElementById('panArrowS');
    var panArrowE       = document.getElementById('panArrowE');
    var panArrowW       = document.getElementById('panArrowW');

    //Menu
    var toc             = document.getElementById('toc');    
    var tree            = document.getElementById('tree');
    var rue             = document.getElementById('rues');
    var liste           = document.getElementById('liste');
    var itineraire      = document.getElementById('itineraire');
    var gestion         = document.getElementById('GestionAdmin');

    //Carte de référence
    var refmap          = document.getElementById('refmap');
    var RefMapTout      = document.getElementById('refmapTout');

    //Bas de page
    var copyrightGeo    = document.getElementById('copyrightGeo');


    // Position (T, L) and sizes (W, H) of elements
    //_____________________________________________

    //Entete
    var topH            = objH(top);          
    var topToutW        = objW(topTout);      

    //Carte
    var mapimgLayerL    = objLeft(mapimgLayer);
    var mapimgLayerT    = objTop(mapimgLayer);
    var mapFrameT       = objTop(mapFrame);

    //Menu
    var tocW            = objW(toc);  
    var tocH            = objH(toc);  
    var tocT            = objTop(toc);
    var treeT           = objTop(tree);

    //Carte de référence
    var refmapW         = objW(refmap); 
    var refmapH         = objH(refmap); 
    var RefMapToutT     = objTop(RefMapTout);

    //Bas de page
    var copyrightGeoH   = objH(copyrightGeo);

    // NEW sizes
    //__________
    var newImgLayerW    = winix - lMargin - tocW;
    var newImgLayerH    = winiy - tMargin - bMargin - topH;
    var newToolBarL     = mapimgLayerL + newImgLayerW;
    var newTocL         = winix - tocW - TailleBordure;//- rMargin + mMargin;
    var newTocH         = newImgLayerH - refmapH - m2Margin;
    var newleftRefmap   = winix - refmapW - rMargin + mMargin;
    var newMenuH        = newImgLayerH - ((tocT - RefMapToutT) + treeT);
    var newCopy         = mapFrameT + newImgLayerH + lMargin;

    // RESIZE elements
    //________________

    //Entete
    top.style.width             = winix + 'px';
    topTout.style.left          = (winix - topToutW)/2 + 'px';

    //Carte
    mapW = newImgLayerW;
    mapH = newImgLayerH;

    mapFrame.style.width        = newImgLayerW + 'px';
    mapFrame.style.height       = newImgLayerH + 'px';

    mapimgLayer.style.width     = newImgLayerW - (TailleBordure *2) +'px';
    mapimgLayer.style.height    = newImgLayerH - (TailleBordure *2) +'px';

    mapImg.style.width          = newImgLayerW - (TailleBordure *2) + 'px';
    mapImg.style.height         = newImgLayerH - (TailleBordure *2) + 'px';

    zoombox.style.width         = newImgLayerW - (TailleBordure *2) + 'px';
    zoombox.style.height        = newImgLayerH - (TailleBordure *2) + 'px';

    loading.style.left          = mapW/2 - 60 + 'px';
    loading.style.top           = mapH/2 - 20 + 'px'; 

    panArrowN.style.top         = mapimgLayerT;
    panArrowN.style.left        = (mapW/2) - (ImgFlecheW/2) - TailleBordure + 'px';             
    panArrowS.style.left        = (mapW/2) - (ImgFlecheW/2) + 'px';                             
    panArrowS.style.top         = mapimgLayerT + mapH - ImgFlecheH - (TailleBordure*4) + 'px';  

    panArrowW.style.top         = mapimgLayerT + (mapH/2) - (ImgFlecheW/2) + 'px';
    panArrowW.style.left        = mapimgLayerL + TailleBordure + 'px';                            
    panArrowE.style.top         = mapimgLayerT + (mapH/2) - (ImgFlecheW) - TailleBordure + 'px';  
    panArrowE.style.left        = mapW - ImgFlecheH - (TailleBordure*4) + 'px';

    //Menu
    toc.style.left              = newTocL + 'px';
    toc.style.height            = newTocH + 'px';

    tree.style.height           = newMenuH + 'px';
    rue.style.height            = newMenuH + 'px';  
    liste.style.height          = newMenuH + 'px';  
    itineraire.style.height     = newMenuH + 'px';
    gestion.style.height        = newMenuH + 53 + 'px';

    //Carte de référence
    RefMapTout.style.left       = newTocL + 'px';

    refmap.style.left           = newleftRefmap + 'px';
    refmap.style.top            = tocT - refmapH + 'px';

    //Bas de page
    copyrightGeo.style.top      = newCopy + 'px';
    copyrightGeo.style.width    = winix + 'px';

    // RELOAD MAP!!!
    //______________
    if (initmap) {

        ext="373237+1985002+374236+1985746";
        var mapurl = 'load.php?'+SID+'&mapW=' + newImgLayerW + '&mapH=' + newImgLayerH + '&mode=map&zoom_type=zoomextent&extent='+ext;
//        var mapurl = 'load.php?'+SID+ '&mapW=' + newImgLayerW + '&mapH=' + newImgLayerH + '&zoom_type=zoompoint';
        updateMap(mapurl, '');
    }
    else
    {
       var mapurl = 'load.php?'+SID+ '&mapW=' + newImgLayerW + '&mapH=' + newImgLayerH + '&zoom_type=zoompoint';
       // For IE add key to prevent automatic map refresh

       if (document.all) mapurl += '&resizeupdate=1';

     //  if (ResizeEncours==0)
     //  {
         ResizeEncours = 1;
         updateMap(mapurl, '');
     //  }
    }
    //}

}



function pMap () {
    //this.setMapProperties = pMap_setMapProperties;
    //this.getMapProperties = pMap_getMapProperties;
    this.getMapScale = pMap_setMapScale;
    this.RefMapW = pMap_getRefMapW;
    this.RefMapH = pMap_getRefMapH; 

}

function pMap_setMapProperties(width, height, scale) {
    var mapimgLayer = document.getElementById('mapimgLayer');
    mapimgLayer.style.width = width;
    mapimgLayer.style.height = height;
    
    this.width  = width;
    this.height = height;
    this.scale  = scale;
}


function pMap_getMapProperties() {
    var width = this.width;
    var height = this.height; 
    //alert(width + ' - ' + height);
    //loadMapImg0();
}


/**
 * SCALE OF CURRENT MAP
 */
function pMap_setMapScale(scale) {
    //alert (scale);
    this.scale = scale;
}

function pMap_getMapScale() {
    //alert(this.scale);
    return this.scale;
}


/**
 * REFERENCE MAP WIDTH/HEIGHT
 */
function pMap_setRefMapW(refW) {
    this.RefMapW = refW;
}

function pMap_setRefMapH(refH) {
    this.RefMapH = refH;
}

function pMap_getRefMapW() {
    return this.RefMapW;
}

function pMap_getRefMapH() {
    return this.RefMapH;
}






/*****************************************************************************
 * SWAP FUNCTIONS FOR TOOLBAR TD -> USE ALTERNATIVELY TO IMAGE SWAP
 * Changes TD class (default.css -> .TOOLBARTD...) in toolbar
 ********************************************************************/
// Function for state buttons (CLICKED TOOLS: zoomin, pan, identify, select, measure)
function setTbTDButton(button) {
    //var tdarr = document.getElementsByName('tbtd');  //!!!!! DOES NOT WORK WITH CRAPPY IE !!!!
    var tdarr = document.getElementById('toolBar').getElementsByTagName('td');
    for (var i = 0; i < tdarr.length; i++) {
        var tdid = tdarr[i].id;
        //alert(tdid);
        //if (tdid != 'tsep') {
        
        //!!!!! WORKAROUND FOR CRAPPY IE !!!!
        if (tdid == 'zoomin' || tdid == 'zoomout' || tdid == 'pan' || tdid == 'identify' || tdid == 'select' || tdid == 'measure') {
            if (tdid != button) {
                rmHighlTD(tdid)
            } else {
                highlTD(tdid);
            }
        }
    }
}

function highlTD(elId) {
    var but = document.getElementById(elId);
    if (but) but.className='TOOLBARTD_ON';
}

function rmHighlTD(elId) {
    //alert(elId);
    var but = document.getElementById(elId);
    if (but) but.className='TOOLBARTD';
}


// Functions for MouseOver/Out
function TbOverOut(elId, status){
    var but = document.getElementById(elId);
    if (but) {
        if (but.className != 'TOOLBARTD_ON') {
            if (status == 'on') {
                but.className='TOOLBARTD_OVER';
            } else {
                but.className='TOOLBARTD';
            }
        }
    }
}

/*function TbOverOut(elId, status){
alert('stop');
var but = document.getElementById(elId);

but.src = 'images/buttons/'+elId+'_'+status+'.gif';
    if (but) {
        if (but.className != 'TOOLBARTD_ON') {
            if (status == 'on') {
                but.className='TOOLBARTD_OVER';
            } else {
                but.className='TOOLBARTD';
            }
        }
}*/
// MouseDown/Up, only set for stateless buttons
function TbDownUp(elId, status){
    var but = document.getElementById(elId);
    if (status == 'd') {
        but.className='TOOLBARTD_ON';
    } else {
        but.className='TOOLBARTD';
    }
}

function moveMap(left, top, fct) {
  var mapimgLayer = document.getElementById('mapimgLayer');
  var endLeft     = parseInt(objLeft(mapimgLayer) + left, 10);
  var endTop      = parseInt(objTop(mapimgLayer)  + top,  10);
  var time        = 80;
  var nbStep      = time / 10; // toutes les 10 millisecondes  
  var stepLeft    = left / nbStep; // deplacement horizontal
  var stepTop     = top  / nbStep; // deplacement vertical
  
  var clockFunct  = function() {
    var curLeft  = objLeft(mapimgLayer);
    var curTop   = objTop(mapimgLayer);
    var clipping = false;

    if(curLeft != endLeft) {
      var newLeft = parseInt(curLeft + stepLeft, 10);
      if((left > 0 && newLeft < endLeft) || (left < 0 && newLeft > endLeft)) {
        mapimgLayer.style.left = newLeft + 'px';
      } else {
        mapimgLayer.style.left = endLeft + 'px';
      }
      clipping = true;
    }

    if(curTop != endTop) {
      var newTop = parseInt(curTop + stepTop, 10);
      if((top > 0 && newTop < endTop) || (top < 0 && newTop > endTop)) {
        mapimgLayer.style.top = newTop + 'px';
      } else {
        mapimgLayer.style.top = endTop + 'px';
      }
      clipping = true;
    }

    // clipping
    if(clipping == true) {
      var clipT = 0;
      var clipR = mapW;
      var clipB = mapH;
      var clipL = 0;

      if (objTop(mapimgLayer) > 0) {
        clipB = mapH - objTop(mapimgLayer);
      } else {
        clipT = -1 * objTop(mapimgLayer);     
      }
      
      if (objLeft(mapimgLayer) > 0) {
        clipR = mapW - objLeft(mapimgLayer);
      } else {
        clipL = -1 * objLeft(mapimgLayer);
      }       

      var clipRect = 'rect(' + clipT + 'px ' 
                   + clipR + 'px '
                   + clipB + 'px ' 
                   + clipL + 'px)'; 

      mapimgLayer.style.clip = clipRect;      
    
    // clear the timer
    } else {
      clearInterval(clockId);
     // fct();
    }
  }
  var clockId = setInterval(clockFunct, 10);
  fct();
}

function changeButtonClr(myObj, myAction) {
    switch (myAction) {
        case 'over':
            myObj.className = 'button_on';
            break;
            
        case 'out':
            myObj.className = 'button_off';
            break;
    }
}




/*****************************************************************************
 * IMAGE SWAP FUNCTIONS FOR TOOLBAR
 * swaps images from imgname_on.gif to imgname_off.gif and vice versa
 *********************************************************************/
// SWITCH IMAGE OF CLICKED TOOL TO 'ON', ALL OTHERS TO 'OFF'
function setButton(button) {
    //var imgarr = document.getElementsByTagName('img');
    var imgarr = document.getElementById('toolBar').getElementsByTagName('img');
    for (var i = 0; i < imgarr.length; i++) {
        var butid = imgarr[i].id;
      //  if (butid != '')
       // {
          if (butid != 'sep') {
              if (butid != button) {
                  setImg(butid, 'off');
              } else {
                  setImg(butid, 'on');
              }
          }
        //}
    }
    if (button == 'Supprimer')
    {
        setImg('Supprimer', 'on');
    }
    else
    {
        setImg('Supprimer', 'off');
    }
}

// set image to ON or OFF
function setImg(obj, status){
    var source = 'images/buttons/' + obj + '_' + status + '.gif';
    imgobj = document.getElementById(obj);
    imgobj.src = source;
}




/**************************************************
 * Set cursor symbol according to tool selection
 *************************************************/
// return root path of application
function getRootPath() {
    var theLoc = document.location.href;
    var theLastPos = theLoc.lastIndexOf('/');
    var RootPath = theLoc.substr(0,theLastPos) + '/';
    
    return RootPath;
}

/** 
 * set the cursor to standard internal cursors
 * or special *.cur url (IE6+ only)
 */
function setCursor(rmc) {
    if (!rmc) {
        if (document.varform) {
            var toolType = document.varform.tool.value;
        } else {
            var toolType = 'zoomin';
        }
    } else {
        toolType = 'pan';
    }

    /* Define settings for cursor to be used for tools
       set to true if you want to use the same cursors for all browsers (incl. IE) */
    var internalCursor = ((navigator.version < 6) || (navigator.appName == 'Netscape'));
    //var internalCursor = true; 
    var rootPath = getRootPath();
    var usedCursor = (internalCursor) ? toolType : "url(" +rootPath + "images/cursors/zoomin.cur)";
    document.getElementById('mapimgLayer').style.cursor = usedCursor;

    switch (toolType) {
        case "zoomin" :
            var usedCursor = (internalCursor) ? 'crosshair' : 'url(' +rootPath + 'images/cursors/zoomin.ani)';  
            break;
        
        case "zoomout" :
            var usedCursor = (internalCursor) ? 'e-resize' : 'url(' +rootPath + 'images/cursors/zoomout.cur)';  
            break;
        
        case "identify" :
            //var usedCursor = (internalCursor) ? 'help' : 'url(' +rootPath + 'images/cursors/identify.cur)';   
            var usedCursor = (internalCursor) ? 'help' : 'help';    
            break;

        case "supprimer" :
            //var usedCursor = (internalCursor) ? 'help' : 'url(' +rootPath + 'images/cursors/identify.cur)';   
            var usedCursor = (internalCursor) ? 'help' : 'help';    
            break;

        case "pan" :
            //var usedCursor = (internalCursor) ? 'move' : 'url(' +rootPath + 'images/cursors/pan.cur)';    
            var usedCursor = 'move';
            break;
            
        case "select" :
            //var usedCursor = (internalCursor) ? 'help' : 'url(' +rootPath + 'images/cursors/select.cur)';
            var usedCursor = (internalCursor) ? 'help' : 'help';                
            break;
            
        case "measure" :
            var usedCursor = (internalCursor) ? 'crosshair' : 'url(' +rootPath + 'images/cursors/measure.cur)'; 
            break;
            
        default:
            var usedCursor = 'default';
    }

    document.getElementById('mapimgLayer').style.cursor = usedCursor;

}




/*
 * OPEN RESULT WINDOW FOR IDEBNTIFY AND SEARCH
 ***********************************************/
function openResultwin(winurl) {
    var w = window.open(winurl, "resultwin", "width=500,height=200,status=no,resizable=yes,scrollbars=yes");
}


/*****************************************************************************
 * SEARCH
 **********/
// CLOSE SEARCH PAGE
function searchClose() {
    parent.searchFrame.location = "blank.html";
}

// OPEN SEARCH PAGE
function searchOpen() {
    parent.searchFrame.location = "search.phtml?"+SID;
}



/******************************************************************************
 * PRINT FUNCTIONS
 *******************/
function openPrintDlg() {
    AfficheHeader('Apercu');
    //var pwin = window.open("printdlg.phtml?"+SID,"printdlg","width=300,height=180,status=no,resizable=no");
}

function printMap() {
    var w = window.open("printmap.phtml?"+SID,"printdlg","width=300,height=180,status=no,resizable=no");
}



/*
 * OPEN HELP WINDOW 
 *************************************/
function openHelp() {
    window.open("help.phtml", "help","width=400,height=500,status=no,resizable=yes");
}



/************************************************************************************
 * DOWNLOAD FUNCTIONS
 * get image with higher resolution for paste in othet programs
 ****************************************************************/
function openDownloadDlg() {
    window.open("downloaddlg.phtml?"+SID, "dldlg","width=300,height=180,status=no,resizable=no");
}

function openDownload() {
    window.open("download.phtml?"+SID, "download");
}



/************************************************************************** 
 * DISPLAY COORDINATES IN MORE THAN ONE COORDIMNATE SYSTEM
 **************************************************************************/
function showCoords(imgxy) {
    window.open("showcoords.phtml?"+SID + "&imgxy="+imgxy, "coords","width=280,height=130,status=no,resizable=no");
}

function openProjection() {
    window.open("projection.phtml", "projection","width=320,height=180,status=no,resizable=yes");
}

