var rendu=0,zoom=0,map,dragging=false,left,dsl,dst,vph,vpw,tilesX,tilesY,vb,zoommax=18,C,W=new Array(),from,to,ladder = [[64, '10000km'],[64, '5000km'],[51.10, '2000km'],[51.10, '1000km'],[51.10, '500km'],[40.88, '200km'],[40.88, '100km'],[81.76, '100km'],[81.76, '50km'],[65.41, '20km'],[65.41, '10km'],[65.41, '5km'],[52.33, '2km'],[52.33, '1000m'],[52.33, '500m'],[52.86, '250m'],[83.72, '200m'],[83.72, '100m'],[83.72, '50m']], timeTitle = new Date().getTime() / 1000 -5, hiking=0,D=document,search;

if (navigator.userAgent.indexOf("Firefox")!=-1 || navigator.userAgent.indexOf("Shiretoko")!=-1|| navigator.userAgent.indexOf("Iceweasel")!=-1 || navigator.userAgent.indexOf("Namoroka") != -1) zoommax=17;
function $(i){return D.getElementById(i)}
function getStyle(e,s){var v="0px",A=$(e);if(A.currentStyle) v=A.currentStyle[s];else if(window.getComputedStyle) v=D.defaultView.getComputedStyle(A,null).getPropertyValue(s);return parseFloat(v.substring(0,v.length-2))}
function disableSelection(e){e.onselectstart=function(){return false};e.unselectable="on";e.style.MozUserSelect="none";e.style.cursor="default"}
function lon2tile(l,z){return ((l+180)/360*Math.pow(2,z))*256|0}
//function lat2tile(l,z){var q=l*Math.PI/180;return ((1-Math.log(Math.tan(q)+1/Math.cos(q))/Math.PI)/2*Math.pow(2,z))*256|0}
function lat2tile(l,z){var q=l*0.017453292519943295769236907684886;return ((1-Math.log(Math.tan(q)+1/Math.cos(q))/Math.PI)/2*Math.pow(2,z))*256|0}
function tile2long(x,z){return x/Math.pow(2,z)*360-180}
//function tile2lat(y,z){var n=Math.PI-2*Math.PI*y/Math.pow(2,z);return 180/Math.PI*Math.atan(0.5*(Math.exp(n)-Math.exp(-n)))}
function tile2lat(y,z){var n=Math.PI-2*Math.PI*y/Math.pow(2,z);return 57.295779506*Math.atan(0.5*(Math.exp(n)-Math.exp(-n)))}
function show_search() {if($('search').style.display !="block"){$('searchicon').className='searchiconon';$('search').style.display ="block";D.f.dep.focus();} else {$('searchicon').className='';$('search').style.display ="none";
    }}
function rendu_sel(r){$('r'+rendu).style.background='transparent';rendu=r;$('r'+rendu).style.background='#ffa500';Z(zoom,1)}
function hik(){if(hiking==0) {$('r3').style.background='#ffa500';hiking=1;}else{$('r3').style.background='transparent';hiking=0;};Z(zoom,1);}
function stopImgLoad(){var m=map.getElementsByTagName("img");for(var i=0,j=m.length;i < j;i++) $(m[i].getAttribute('id')).src=''}
function geoloc(position) {geolocation('{lon:'+position.coords.longitude+',lat:'+position.coords.latitude+'}',1);}
function upgeopos () {var watchId=navigator.geolocation.getCurrentPosition(scrollMap);}
function scrollMap(position){
    ll['lon']=position.coords.longitude;
    ll['lat']=position.coords.latitude;
    Z(zoom,1,lon2tile(ll['lon'], zoom),lat2tile(ll['lat'],zoom));
    showpt(lon2tile(ll['lon'], zoom),lat2tile(ll['lat'],zoom));
    setTimeout ("upgeopos()", 2000); 
}
function addClassName(oElm, strClassName){
    var strCurrentClass = oElm.className;
	if(!new RegExp(strClassName, "i").test(strCurrentClass)){
		oElm.className = strCurrentClass + ((strCurrentClass.length > 0)? " " : "") + strClassName;
	}
}
function i(){
    // for(i=0; i < 19; i++) {
    //     var mymaps=D.createElement('div');
    //     mymaps.id='map'+i;
    //     mymaps.style.width=mymaps.style.height=256*Math.pow(2,zoom)+'px';
    //     D.appendChild(mymaps)
        
    // }
    var opt=new Array;
    if(window.location.hash){
        var h=window.location.hash.substring(1).split("&");
        for(var i in h){
            var j=h[i].split("=");
            opt[j[0]]=j[1];
        }
    }
    map=$('map');vb=$('viewbox');
    myresize(1);
    if(opt['r']) rendu=opt['r']|0;
    if(opt['h']|0 == 1) {hiking=0; hik();}
    if( typeof(opt['from'])!='undefined' && typeof(opt['to'])!='undefined') {
        from=opt['from'].replace(/\+/g, '%252B'); to=opt['to'].replace(/\+/g, '%252B');
        asyncRequest('routing.php', function(o) {getWay(o.responseText);}, 'from='+from+'&to='+to);
    }
    if( typeof(opt['lon']) != 'undefined' && typeof(opt['lat']) != 'undefined' && typeof(opt['z']) != 'undefined') {
        //ZS=256*Math.pow(2,opt['z']);
        if(Math.abs(opt['lon']) > 180 || Math.abs(opt['lat']) >180) opt['lon']=opt['lat']=0;
        if(opt['z'] > 18 || opt['z'] < 0) opt['z']=3;
        Z(opt['z'],1,lon2tile(parseFloat(opt['lon']),opt['z']),lat2tile(parseFloat(opt['lat']),opt['z']));    
    } 
    else if(D.cookie) {
        var cook;
        var nameEQ="maps_save_place=";
        var ca=D.cookie.split(';');
        for(var i=0;i < ca.length;i++) {
            var c=ca[i];
            while (c.charAt(0)==' ') c=c.substring(1,c.length);
            if (c.indexOf(nameEQ) == 0)  cook=c.substring(nameEQ.length,c.length);
        }
        var ar=cook.split('|');
        rendu=ar[3]|0;
        //ZS=256*Math.pow(2,ar[2]);
        if(ar[4] && ar[5] && ar[4]!='undefined'&&ar[5]!='undefined'){from=ar[4];to=ar[5];
            asyncRequest('routing.php', function(o) {getWay(o.responseText);}, 'from='+from+'&to='+to);
        }
        if(ar[6]|0 == 1){ hiking=0; hik();}
        if(Math.abs(opt['lon']) > 180 || Math.abs(opt['lat']) >180) opt['lon']=opt['lat']=0;
        if(opt['z'] > 18 || opt['z'] < 0) opt['z']=3;
        Z(ar[2],1,lon2tile(parseFloat(ar[0]),ar[2]),lat2tile(parseFloat(ar[1]),ar[2]));
    }
    else {
        //        alert("on est la");
        //ZS=256*Math.pow(2,2);
        opt['lat']=opt['lon']=opt['r']=0;
        zoom=2;
        rendu=0;
        Z(2, 1, lon2tile(0,2), lat2tile(0,2))
            if(navigator.geolocation.getCurrentPosition) {
                navigator.geolocation.getCurrentPosition(geoloc);
            }
            else {
                asyncRequest('geolocation.php', function(o) {geolocation(o.responseText);}, '');
            }
    }
    //  if(p==1) show_point(x,y);
    //    if(typeof(opt['from'])!='undefined' && typeof(opt['to'])!='undefined') {
    //         from=opt['from']; to=opt['to'];
    //         asyncRequest('routing.php', function(o) {getWay(o.responseText);}, 'from='+opt['from']+'&to='+opt['to']);
    //     }
    
    window.onbeforeunload=putCookie;
    vb.onmousedown=startMove;
    vb.onmousemove=processMove;
    D.onmouseup=function(){map.style.cursor="";dragging=false;checkTiles();};
    vb.oncontextmenu=function(e){
        if(!e) e=window.event; 
        Z(zoom,1,e.clientX,e.clientY);
        return false; //Sinon menu s'affiche
    };
    vb.ondragstart=function(){return false;};
    window.onresize=function(){myresize(0);return false;};
    if(vb.addEventListener) {
        vb.addEventListener('DOMMouseScroll',wheel,false);
        D.addEventListener("touchstart", touchHandler, false);
        D.addEventListener("touchmove", touchHandler, false);
        D.addEventListener("touchend", touchHandler, false);
        D.addEventListener("touchcancel", touchHandler, false);    
    }
    vb.onmousewheel=wheel;
    disableSelection(map);
    $('r'+rendu).style.background='#ffa500';
    D.onkeydown=function(evt){
        var ev=(evt.which)?evt.which:evt.keyCode;
        //alert(ev);
        switch(ev){
          case 109:
          case 45: Z(-1);break;
          case 107:
          case 43:Z(1);break;
            // case 77:lmap();break; //m
          case 37: move(256,0); break;
          case 39: move(-256,0); break;
          case 38: move(0,256); break;
          case 40: move(0,-256); break;
        }
        if(ev<41&&ev>36&&C) C.clearRect(0,0,10000,10000);
    }
    // if (navigator.userAgent.indexOf("iPhone")!=-1)  {
    //     lmap();
    //     var watchId=navigator.geolocation.getCurrentPosition(scrollMap); //navigator.geolocation.watchPosition(scrollMap);
    // }
}


function touchHandler(event){
    function carre(x){return x*x};
    var touches=event.changedTouches,first=touches[0],type="";
    switch(event.type){
    case "touchstart":
        if(event.touches.length > 1)
            multiDist=Math.sqrt(carre(event.touches[0].pageX-event.touches[1].pageX)+carre(event.touches[0].pageY-event.touches[1].pageY));
        else
            type="mousedown";
        break;
        
    case "touchmove":
        if(event.touches.length > 1)
            multiDist2=Math.sqrt(carre(event.touches[0].pageX-event.touches[1].pageX)+carre(event.touches[0].pageY-event.touches[1].pageY));
        else
            type="mousemove";        
        event.preventDefault();
        break;        
        
    case "touchend":
        if(multiDist && multiDist2) {
            (multiDist > multiDist2)?Z(-1):Z(1);
            multiDist=multiDist2=0;
        }
        else
            type="mouseup";
        break;
    default:
        return;
    }
    var simulatedEvent=D.createEvent("MouseEvent");
    simulatedEvent.initMouseEvent(type, true, true, window, 1, first.screenX, first.screenY, first.clientX, first.clientY,false, false, false, false, 0/*left*/, null);
    first.target.dispatchEvent(simulatedEvent);
}

var asyncRequest=function() {
    function handleReadyState(o, callback) {
        if (o && o.readyState == 4) {
            if (o.status==200){callback(o);/*clearTimeout(requestTimer)*/}
            //else affError();
        }
    }
    var getXHR=function() {return (window.XMLHttpRequest)?new XMLHttpRequest():new ActiveXObject("Msxml2.XMLHTTP");};
    return function(uri, callback, postData) {
        var xhr=getXHR();
        xhr.open('POST', uri, true);
        xhr.onreadystatechange=function() {handleReadyState(xhr, callback);};
        xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
        xhr.send('http=1&'+postData);
        //  requestTimer=setTimeout(function(){xhr.abort();},10);// MAXIMUM_WAITING_TIME);
        return xhr;
    };
}();

function geolocation(o,p){
    var ll=eval('('+o+')');
    Z(15,1,lon2tile(parseFloat(ll['lon']),15),lat2tile(parseFloat(ll['lat']),15));
    if(p==1) showpt(lon2tile(ll['lon'], 15),lat2tile(ll['lat'],15));
}

function search_way(t) {
    $('s').style.left='30%';
    $('bs').style.left='44%';
    $('s2').style.display='block';
    addClassName($('ws'),"bsborder");
    if(!t) return;
    
}

function search_place(t) {
    if(t){
        search = t;
        $('bs').style.background="white url(loading.gif) no-repeat 4px center";
        asyncRequest('http://nominatim.openstreetmap.org/search?polygon=1&format=json&q='+t, function(o) {getSearch(o.responseText);}, '');
    }
    else {W.p='';if(C) C.clearRect(0,0,2000,2000);}
    return false;
}

function getSearch(o){
    if(o) {
        var p=eval('(' + o + ')'); 
        if(p && p[0]) { 
            W.p=p[0].polygonpoints;
            for(var i=1;i<19;i++) {
                zoom=i-1;
                var lo=Math.abs((lon2tile(p[0].boundingbox[3],i)-lon2tile(p[0].boundingbox[2],i))/256|0);
                var la=Math.abs((lat2tile(p[0].boundingbox[1],i)-lat2tile(p[0].boundingbox[0],i))/256|0);
                if(la>=tilesY ||lo >= tilesX) break;
            }
            map.style.left=map.style.top="0px";
            Z(zoom,1,lon2tile(parseFloat(p[0].lon), zoom),lat2tile(parseFloat(p[0].lat),zoom));
            //    drawPolygon(W.p);
            
        }
        else {
            alert("Lieu non trouvé.");
        }
        $('bs').style.background="white url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAUAgMAAAGH4MUIAAAAAXNSR0IArs4c6QAAAAxQTFRFlpaWxMPD4+Pj////nDtYsgAAAAF0Uk5TAEDm2GYAAAABYktHRACIBR1IAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH2gkBDDoM79j7ywAAAFJJREFUCNdVjMEJwDAMA89Q//1I93E3yCPZf5XKCYVGGIPkk4HgonYSiVMyKgs+WcUd3DjU5F2k9X23pqLYODjLGga3jD/FMtdhKlY61gfPf+kFUSAFhHpgt7AAAAAASUVORK5CYII%3D) no-repeat scroll 4px center";
        $('bs').onclick = function () {$('s').value = '';}
        verif_search();
    }
}

function verif_search() {
    // alert($('s').value+' '+search);
    if(!$('s').value || $('s').value != search) {
        $('bs').style.background="white url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAARCAYAAADdRIy+AAAAAXNSR0IArs4c6QAAAAZiS0dEAP8A/wD/oL2nkwAAAAlwSFlzAAAOxAAADsQBlSsOGwAAAAd0SU1FB9kCBxQkAPQ1ZpQAAAGrSURBVDjLjdRNiE5xFAbw372v14zvkEGsjLD20UghKTay1uykyEIWSpY2Stmp2dhMoWQ1USYbScrKhpKyGkVDNDaGfM21ed5ct/cOp/7dc+89/+c8z/k/9xYoUPkTu7EXm7EQM3iO+3jfp/6v6NTyJbiEY1iE13iXfB+O4BdeoAxo0Q+0yLqGCRxFt1GzChfDctR/xDncxY5ak7KW9+I8JjE8H9iagJ36R9Nek5u43FZUYicGcCv3ZQtYhTk8xFYsbgPcgGnM1jb1A+vFMwxifRtgmdOba1FR1WrhR8MhRRPwA9ZFdtlgVo9ewy34mn0a9inK+KrC4TA9EZvUZe7BweQHAvipoaKABXiVNYoHmeV1PMZbbMcmnIlHh/JuPHabCc7PurS1MfU4VmN5vozjYSdgE7iBFdlzG/u1zGlbvoaleIKnkTaEQ9iIjznhQVyNoiuYwli/wXdwEiOxU5W5vsQdPMLpzLMbT47F7NO4UPRhW9V+FgP4jO+NxiM4G6azebYMk50W+WWG/C12KRpefBO2u7AyDbuY6sxj5uYqatcCX3AvhzgcX479BrxnZh85IOwcAAAAAElFTkSuQmCC) no-repeat scroll 4px center";
        $('bs').onclick = function () {search_place($('s').value);return false;}
    }
    else setTimeout('verif_search()', 100);
}
function getWay(o){
    if(o) {
        W=eval('(' + o + ')');
        alert("W:"+W);
        drawWay(W);
        if(W.r.w) {
            var mino, mina, maxo, maxa;
            mino=mina=180;maxo=maxa=-180;
            for(var i=0, k=W.r.w, l=k.length; i < l; i++) {
                if(k[i].o < mino) mino=k[i].o;
                else if(k[i].o > maxo) maxo=k[i].o;
                if(k[i].a < mina) mina=k[i].a;
                else if (k[i].a > maxa) maxa=k[i].a;
            }
            for(var i=1;i<19;i++) {
                zoom=i-2;
                if(Math.abs((lat2tile(maxa,i)-lat2tile(mina,i))/256|0)>=tilesY ||Math.abs((lon2tile(maxo,i)-lon2tile(mino,i))/256|0) >= tilesX) break;
            }
            map.style.left=map.style.top="0px";
            Z(zoom,1,lon2tile(parseFloat(maxo+mino)/2, zoom),lat2tile(parseFloat(maxa+mina)/2,zoom));    
        }
        //        upLoc();
    }
} 

function drawPolygon(p) {
    if(!p) return;
    C.beginPath();
    C.globalAlpha=0.8; 
    C.strokeStyle="blue";
    C.fillStyle="blue";
    C.lineWidth=2; 
    C.moveTo(lon2tile(p[0][0], zoom)+map.offsetLeft,lat2tile(p[0][1], zoom)+map.offsetTop);
    var l=p.length;
    for(i=0;i<l;i++) C.lineTo(lon2tile(p[i][0], zoom)+map.offsetLeft,lat2tile(p[i][1], zoom)+map.offsetTop);
    C.moveTo(lon2tile(p[i-1][0], zoom)+map.offsetLeft,lat2tile(p[i-1][1], zoom)+map.offsetTop);
    C.closePath();
    C.stroke();
    C.globalAlpha=0.2;  
    C.fill();
}

function drawWay(W) {
    if(!C) {
        var canvas=D.createElement("canvas");
        canvas.id="way";
        canvas.height=vb.offsetHeight;
        canvas.width=vb.offsetWidth;
        vb.appendChild(canvas);
        C=canvas.getContext('2d');
    }
    else C.clearRect(0,0,2000,2000);
    if(W.p) drawPolygon(W.p);

    //route
    if(W.r && W.r.w) {
        C.beginPath();
        C.strokeStyle="red";
        C.lineWidth=zoom*0.4; 
        C.globalAlpha=0.8;
        C.moveTo(lon2tile(W.r.w[0].o, zoom)+map.offsetLeft,lat2tile(W.r.w[0].a, zoom)+map.offsetTop);
        var l=W.r.w.length, X=map.offsetLeft, Y=map.offsetTop;
        for(i=0; i < l; i++) C.lineTo(lon2tile(W.r.w[i].o, zoom)+X,lat2tile(W.r.w[i].a, zoom)+Y);
        C.moveTo(lon2tile(W.r.w[i-1].o, zoom)+X,lat2tile(W.r.w[i-1].a, zoom)+Y);
        C.closePath();
        C.stroke();
    }
    
    //polygon depart
    if(W.r && W.r.pd) drawPolygon(W.r.pd);

    //polygon arrivee
    if(W.r && W.r.pf) drawPolygon(W.r.pf);   
    
    if(W.r && W.r.d && W.r.t)   $("way").title ="distance : "+W.r.d+" temps : "+W.r.t;

}

function startMove(e){
    if(!e) e=window.event;
    dsl=map.offsetLeft-e.clientX;
    dst=map.offsetTop-e.clientY;
    map.style.cursor="move";
    dragging=true;
    return false;
}

function processMove(e){
    if(dragging){
        if(!e) e=window.event;
        map.style.top=e.clientY+dst+"px";
        map.style.left=e.clientX+dsl+"px"; 
        checkTiles(); //on peut le mettre dans mouseup aussi, mais les tiles apparaissent que qd on relache le bouton alors, but more speed
    }
}

function Z(z,d,ex,ey) {
    ex=(ex)?ex:vpw/2;
    ey=ey?ey:vph/2;
    var rx=ex,ry=ey,ZX=1;
    if(d==1){ zoom=z;rx=vpw/2;ry=vph/2}
    else{
        if(z==1&&zoom!=zoommax) {
            zoom++;
            ZX=2;
        }
        else if(z==-1&&zoom!=0) {
            zoom--;
            ZX=0.5;
        }
    }
    stopImgLoad();
    map.innerHTML='';   
    map.style.height=map.style.width=256*Math.pow(2,zoom)+"px";
    map.style.left=((map.offsetLeft-ex)*ZX+rx|0)+"px";
    map.style.top =((map.offsetTop -ey)*ZX+ry|0)+"px";
    checkTiles();
    for(var i=0;i<19;i++) $("p"+i).style.opacity=(i<=zoom)?'1':'0.5';
    $('ladder').style.width=ladder[zoom][0]+'px';
    $('ladder').innerHTML=ladder[zoom][1];
} 

function checkTiles() {
    map.style.visibility="hidden";
    var frag=D.createDocumentFragment(),imgclone=new Image(), xa=-1+map.offsetLeft/-256|0, tt=tilesX+xa, ya=(map.offsetTop/-256)-1|0, yy=tilesY+ya;
    //var lim=Math.pow(2,zoom)-1;
    imgclone.style.visibility="hidden";
    imgclone.style.zIndex=1;
    imgclone.setAttribute("onload","this.style.visibility=''");
    imgclone.setAttribute("onerror","this.src='error.png'");
    //   for (var x=xa; x<=tt; x++){
    for (var x=tt; x>=xa;x--) {
    var o=zoom+'/'+x+'/';
        for (var y=ya; y<=yy; y++) {
            //       if(x < 0 || x > lim || y < 0 || y > lim) continue; //evite de dl img hors map.
            var n=o+y+'.png', idn=rendu+'|'+n;

            if(!$(idn)){
                var img=imgclone.cloneNode(false);
                img.src=make_url(x,y,n,rendu);
                img.id=idn;
                //                img.style.visibility="hidden"; 
                img.style.left=(x*256)+"px";
                img.style.top=(y*256)+"px";
                // if(hiking) img.style.opacity=0.6;
                //img.style.zIndex=1;

                //               img.setAttribute("onload","this.style.visibility=''");
                //img.setAttribute("onerror","this.src='error.png'");
                frag.appendChild(img);
                if(hiking) {
                    var img2=imgclone.cloneNode(false);
                    img2.src=make_url(x,y,n,3);
                    img2.id=idn;
                    img2.style.visibility="hidden";
                    img2.style.zIndex=2;
                    img2.style.opacity=0.8;
                    img2.style.left=(x*256)+"px";
                    img2.style.top=(y*256)+"px";
                    img2.setAttribute("onload","this.style.visibility=''");
                    img2.setAttribute("onerror","this.src='error.png'");
                    frag.appendChild(img2);
                }
                if(rendu==4) {
                     var img3=imgclone.cloneNode(false);
                    img3.src=make_url(x,y,n,0);
                    img3.id=idn;
                    img3.style.visibility="hidden";
                    img3.style.zIndex=2;
                    img3.style.opacity=0.5;
                    img3.style.left=(x*256)+"px";
                    img3.style.top=(y*256)+"px";
                    img3.setAttribute("onload","this.style.visibility=''");
                    img3.setAttribute("onerror","this.src='error.png'");
                    frag.appendChild(img3);
                }
            }
        }
    }
    map.appendChild(frag);
    map.style.visibility='';
    upLoc();
    if(W) drawWay(W); 
    draw_mask();
    getTitle();
}



function myresize(start) {
    vpw=vb.offsetWidth;vph=vb.offsetHeight;
    if(!vpw||!vph||vph<0){vb.style.height=screen.height-300;$('help_window').style.width=vb.style.width=screen.width-80}
    tilesX=Math.ceil(vpw/256)+1;tilesY=Math.ceil(vph/256)+1;
    if(start==0) Z(zoom,1);}
                                           
function showpt(x,y){
    var i=new Image;
    i.src="point.gif";
    i.style.left=x+"px";
    i.style.top=y+"px";
    i.id="marker";
    i.style.zIndex=42;
    map.appendChild(i);
}
                                           
//    case 3: return "http://beta.letuffe.org/tiles/renderer.py/hiking/"+n;
function make_url(x,y,n,r) {
    var h=["a","b","c"][x%3];
    // alert(r);
    switch(r){
    case 0: /*if(h=='a' || h=='c') */return "http://"+h+".tile.openstreetmap.org/"+n;/* else return "http://b.www.toolserver.org/tiles/osm/"+n;*/
    case 1: return "http://"+h+".andy.sandbox.cloudmade.com/tiles/cycle/"+n;
        //case 5: return "http://oatile1.mqcdn.com/naip/"+n;
    case 2: return "http://"+h+".tile.openaerialmap.org/tiles/1.0.0/openaerialmap-900913/"+n; 
    case 3: return "http://toolserver.org/~cmarqu/hill/"+n;
        // case 4: return "http://"+h+".tah.openstreetmap.org/Tiles/tile/"+n;
    case 4:  return "http://ecn.t0.tiles.virtualearth.net/tiles/a"+TileXYToQuadKey(x, y, zoom)+".jpeg?g=588&mkt=en-gb&n=z";
    case 5: return "http://ecn.t0.tiles.virtualearth.net/tiles/a"+TileXYToQuadKey(x, y, zoom)+".jpeg?g=588&mkt=en-gb&n=z";
    default: return "http://"+h+".tile.openstreetmap.org/"+n;
    }
}

function upLoc() {
    var lon=tile2long(((map.offsetLeft-(vpw/2))/-256),zoom);
    var lat=tile2lat(((map.offsetTop-(vph/2))/-256),zoom);
    window.location.hash="lon="+lon+"&lat="+lat+"&z="+zoom+"&r="+rendu+"&h="+hiking+((from && to)?("&from="+from+"&to="+to):"");
    $('editicon').href="http://www.openstreetmap.org/edit?lat="+lat+"&lon="+lon+"&zoom="+zoom;
}

function getTitle() {
    var t=new Date().getTime();
    if(zoom >= 10 && ((timeTitle + 2000) < t)) {timeTitle=t;asyncRequest('place.php', function(o) {printTitle(o.responseText);}, 'lat1='+tile2lat(((map.offsetTop)/-256),zoom)+'&lon1='+tile2long(((map.offsetLeft)/-256),zoom)+'&lat2='+tile2lat(((map.offsetTop-(vph))/-256),zoom)+'&lon2='+tile2long(((map.offsetLeft-(vpw))/-256),zoom));}  
    else if(zoom < 10) printTitle("Gheop Maps");
}

function printTitle(o){D.title=o?o:"Gheop Maps"}

function putCookie(){D.cookie="maps_save_place="+tile2long(((map.offsetLeft-(vpw/2))/-256),zoom)+'|'+tile2lat(((map.offsetTop-(vph/2))/-256),zoom)+"|"+zoom+"|"+rendu+"|"+from+"|"+to+"|"+hiking+"; expires=Fri, 3 Aug 2050 06:42:42 UTC; path=/"}

function wheel(e){
    var G=0;
    if(!e)e=window.event;
    if(e.detail)G=-e.detail/3;
    else if(e.wheelDelta){G=e.wheelDelta;if(window.opera)G=G/80;}
    if(G>0)Z(1,0,e.clientX,e.clientY);
    else if(G<0)Z(-1,0,e.clientX,e.clientY);
    e.preventDefault();
}

//
//essayer les caractères ⇱⇱⇲
//
function show_lmap(h,L){if(!L) L=$("lmap").style;if(h<128){L.height=L.width=h+"px";setTimeout('show_lmap('+(h+12.8)+');',40);} else $("reduce").src="data:image/gif;base64,R0lGODlhDAAMAKECAICEmP+lAP///////yH5BAEKAAIALAAAAAAMAAwAAAIjhI8gEO0fWBC0rjinvYxqzXSeAGJWQ4Wfk5pbK75qgmQQVAAAOw==";}// 

function hide_lmap(h,L){if(!L) L=$("lmap").style;if(h >=0){L.height=L.width=h+"px";setTimeout('hide_lmap('+(h-12.8)+');',40);} else{L.height=L.width="0px";L.display="none";$("reduce").src="data:image/gif;base64,R0lGODlhDAAMAKECAICEmP+lAP///////yH5BAEKAAIALAAAAAAMAAwAAAIijI8hAe3OmJh0RlDrtccCuSjUtpQeKKYflilkGyUJ9tRNAQA7";}}

function lmap(){var h=getStyle("lmap","height"),L=$("lmap").style;if(!h){L.display="block";show_lmap(12.8,L);}else hide_lmap(h-12.8,L);}

function move(mx, my) {
    var mv;
    if(Math.abs(mx)>15){
        mx-=mv=mx>0?16:-16;
        map.style.left=map.offsetLeft+mv+"px";
        setTimeout("move("+mx+","+my+")",40);
    }
    else if(Math.abs(my) > 15) {
        my-=mv=my>0?16:-16;
        map.style.top=map.offsetTop+mv+"px";
        setTimeout("move("+mx+","+my+")",40);
    }
    else checkTiles(); // chaque fois ou a la fin ?
}

function draw_mask(){var P=$("mask_lmap").style;var Z=1/(2*Math.pow(2,zoom));P.top=map.offsetTop*-Z+"px";P.left=map.offsetLeft*-Z+"px";P.height=vph*Z+"px";P.width=vpw*Z+"px";}

window.onload=function(){i();}














function var_dump () {
    // http://kevin.vanzonneveld.net
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // +   improved by: Zahlii
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // -    depends on: echo
    // %        note 1: For returning a string, use var_export() with the second argument set to true
    // *     example 1: var_dump(1);
    // *     returns 1: 'int(1)'

    var output = '', pad_char = ' ', pad_val = 4, lgth = 0, i = 0, d = this.window.document;
    var _getFuncName = function (fn) {
        var name = (/\W*function\s+([\w\$]+)\s*\(/).exec(fn);
        if (!name) {
            return '(Anonymous)';
        }
        return name[1];
    };

    var _repeat_char = function (len, pad_char) {
        var str = '';
        for (var i = 0; i < len; i++) {
            str += pad_char;
        }
        return str;
    };
    var _getInnerVal = function (val, thick_pad) {
        var ret = '';
        if (val === null) {
            ret = 'NULL';
        }
        else if (typeof val === 'boolean') {
            ret = 'bool(' + val + ')';
        }
        else if (typeof val === 'string') {
            ret = 'string(' + val.length+') "' + val + '"';
        }
        else if (typeof val === 'number') {
            if (parseFloat(val) == parseInt(val, 10)) {
                ret = 'int(' + val + ')';
            }
            else {
                ret = 'float('+val+')';
            }
        }
        // The remaining are not PHP behavior because these values only exist in this exact form in JavaScript
        else if (typeof val === 'undefined') {
            ret = 'undefined';
        }
        else if (typeof val === 'function') {
            var funcLines = val.toString().split('\n');
            ret = '';
            for (var i = 0, fll = funcLines.length; i < fll; i++) {
                ret += (i !== 0 ? '\n'+thick_pad : '') + funcLines[i];
            }
        }
        else if (val instanceof Date) {
            ret = 'Date('+val+')';
        }
        else if (val instanceof RegExp) {
            ret = 'RegExp('+val+')';
        }
        else if (val.nodeName) { // Different than PHP's DOMElement
            switch(val.nodeType) {
                case 1:
                    if (typeof val.namespaceURI === 'undefined' || val.namespaceURI === 'http://www.w3.org/1999/xhtml') { // Undefined namespace could be plain XML, but namespaceURI not widely supported
                        ret = 'HTMLElement("' + val.nodeName + '")';
                    }
                    else {
                        ret = 'XML Element("' + val.nodeName + '")';
                    }
                    break;
                case 2:
                    ret = 'ATTRIBUTE_NODE(' + val.nodeName + ')';
                    break;
                case 3:
                    ret = 'TEXT_NODE(' + val.nodeValue + ')';
                    break;
                case 4:
                    ret = 'CDATA_SECTION_NODE(' + val.nodeValue + ')';
                    break;
                case 5:
                    ret = 'ENTITY_REFERENCE_NODE';
                    break;
                case 6:
                    ret = 'ENTITY_NODE';
                    break;
                case 7:
                    ret = 'PROCESSING_INSTRUCTION_NODE(' + val.nodeName + ':' + val.nodeValue+')';
                    break;
                case 8:
                    ret = 'COMMENT_NODE(' + val.nodeValue + ')';
                    break;
                case 9:
                    ret = 'DOCUMENT_NODE';
                    break;
                case 10:
                    ret = 'DOCUMENT_TYPE_NODE';
                    break;
                case 11:
                    ret = 'DOCUMENT_FRAGMENT_NODE';
                    break;
                case 12:
                    ret = 'NOTATION_NODE';
                    break;
            }
        }
        return ret;
    };

    var _formatArray = function (obj, cur_depth, pad_val, pad_char) {
        var someProp = '';
        if (cur_depth > 0) {
            cur_depth++;
        }

        var base_pad = _repeat_char(pad_val * (cur_depth - 1), pad_char);
        var thick_pad = _repeat_char(pad_val * (cur_depth + 1), pad_char);
        var str = '';
        var val = '';

        if (typeof obj === 'object' && obj !== null) {
            if (obj.constructor && _getFuncName(obj.constructor) === 'PHPJS_Resource') {
                return obj.var_dump();
            }
            lgth = 0;
            for (someProp in obj) {
                lgth++;
            }
            str += 'array('+lgth+') {\n';
            for (var key in obj) {
                var objVal = obj[key];
                if (typeof objVal === 'object' && objVal !== null &&
                    !(objVal instanceof Date) && !(objVal instanceof RegExp) && !objVal.nodeName) {
                    str += thick_pad + '[' + key + '] =>\n' + thick_pad + _formatArray(objVal, cur_depth + 1, pad_val, pad_char);
                } else {
                    val = _getInnerVal(objVal, thick_pad);
                    str += thick_pad + '[' + key + '] =>\n' + thick_pad + val + '\n';
                }
            }
            str += base_pad + '}\n';
        } else {
            str = _getInnerVal(obj, thick_pad);
        }
        return str;
    };

    output = _formatArray(arguments[0], 0, pad_val, pad_char);
    for (i=1; i < arguments.length; i++) {
        output += '\n' + _formatArray(arguments[i], 0, pad_val, pad_char);
    }

    if (d.body) {
        this.alert(output);
    }
    else {
        try {
            d = XULDocument; // We're in XUL, so appending as plain text won't work
            this.alert('<pre xmlns="http://www.w3.org/1999/xhtml" style="white-space:pre;">'+output+'</pre>');
        }
        catch (e) {
            this.alert(output); // Outputting as plain text may work in some plain XML
        }
    }
}

function TileXYToQuadKey(tileX, tileY, levelOfDetail) {
    var quadKey = '';
    for (var i = levelOfDetail; i > 0; i--) {
        var digit = '0';
        var mask = 1 << (i - 1);
        if ((tileX & mask) != 0) {
            digit++;
        }
        if ((tileY & mask) != 0) {
            digit++;
            digit++;
        }
        quadKey = quadKey+''+digit;
    }
    return quadKey;
}

