var KSIZE=1.0;
var SERVER='ftp://ftp5.gwdg.de/.../latest/img/';
var bbstring;

function setMapSize(newSize){
    var map = document.getElementById('map');
    if(newSize == '+'){
        newSize = parseInt(OpenLayers.Element.getStyle(map, 'width')) * 1.25;
    }else if(newSize == '-'){
        newSize = parseInt(OpenLayers.Element.getStyle(map, 'width'))/1.25;
    }
    var tileno = document.getElementById('tileno');
    var newsizepx = "" + newSize + "px";
    map.style.width = newsizepx;
    map.style.height = newsizepx;
    tileno.style.top = "" + (25 + newSize) + "px";
    tileno.style.width = newsizepx;
    document.getElementById('mapsize').style.width = newsizepx;
    gpxmap.updateSize();
}

function readQueryBB(){
    if(location.search){
        var query = location.search.substring(1);
        var tokens = query.split('=');
        if (tokens.length > 1 && tokens[0] == 'area'){
            bbstring = tokens[1];
            var element = document.getElementById('bb');
            if (element){
                element.value = bbstring;
            }
            element = document.getElementById('result');
            if (element){
                writeContent(element);
            }
            var element = document.getElementById('map');
            if(element){
                bounds = parseBBString()
                var bbounds = {
                    W:bounds.west,
                    N:bounds.north,
                    S:bounds.south,
                    E:bounds.east
                };
                gpxmap.setBounds(bbounds);
                resizeMap();
            }
        }
    }
}


function bookmarklet(){
    if(location.href.indexOf("http://www.openstreetmap.org") != 0){
        alert("Please go to http://www.openstreetmap.org and zoom/pan to area of interest first.");
        return;
    }
    bounds =  getMapExtent();
    newurl = "http://touren.mospace.de/kachel.html?area=";
    newurl += bounds.left.toFixed(5) + ",";
    newurl += bounds.bottom.toFixed(5) + ",";
    newurl += bounds.right.toFixed(5) + ",";
    newurl += bounds.top.toFixed(5);
    location.href = newurl;
}

function formSubmit(){
    bbstring = document.getElementById("bb").value;
    serverSelection = document.getElementById("selectServer");
    server = serverSelection.options[serverSelection.selectedIndex].value;
    if (server != ""){
        SERVER = server;
    }
    KSIZE = document.getElementById("tSize").value * 1.0;
    writeContent();
}

function writeContent(target){
    var bb = parseBBString();
    setCoordinateField(bb);
    var html = printTiles(bb, bbstring);
    var x = (target)? target : document.getElementById("result");
    x.innerHTML = html;
}

function parseBBString(){
    bbstring = bbstring.replace(/right-top/,',');
    bbstring = bbstring.replace(/left-bottom/,'');
    bbstring = bbstring.replace(/[^0-9\.\-,]/g, '');
    var bba = bbstring.split(',');
    var bb= {
        west:Math.max(bba[0] * 1, -179.99),
        south:Math.max(bba[1] * 1, -90),
        east:Math.min(bba[2] * 1, 180),
        north:Math.min(bba[3] * 1, 90)
    };
    return bb;
}

function setCoordinateField(bb){
    var bbs = "" + bb.west.toFixed(5) +", ";
    bbs += bb.south.toFixed(5) + ", ";
    bbs += bb.east.toFixed(5) + ", ";
    bbs += bb.north.toFixed(5);
    if (document.getElementById('bb')){
        document.getElementById('bb').value = bbs;
        bbstring = bbs;
    }
}

function printTiles(bb, bbstring){
    if(bb.west >= bb.east){
        alert("W must be less than E");
        return;
    }
    if(bb.south >= bb.north){
        alert("S must be less than N");
        return;
    }
    var html = "";
    html += ("<div class='content'>\n");
    /*
    html += ("<div class='header'>");
    //html += "Bounding Box: " + bbstring +"<br>\n";
    for(var x in bb){
        html += (x + ":" + bb[x] + "<br/>\n");
    }
    html+='\n';
    html += ("</div><hr />\n");*/
    var result='<div style="margin-bottom:1em">'
    result += "Click on the links, copy/paste the list of URLs to a download";
    result += "manager, or save them to a text file called ";
    result += "tiles.txt and use the bash script ";
    result += '<a href="http://touren.mospace.de/.osm/download.sh">';
    result += "download.sh</a>.</div>\n";
    result += "<div style='color:red;margin-bottom:1em'>Broken link? Check if the tile is empty by clicking the map icon next to the link. ";
    result += "If it's not empty please <a href=\"javascript:eml('9yr%3Asc63s4Boqockn0g6yctf0eqo')\">tell me</a> about the broken link!";
    result += " Since May 2010 img tiles for some densely populated areas in the Netherlands <a href=\"http://wiki.openstreetmap.org/wiki/User_talk:Computerteddy#Fehlende_Kacheln\">cannot be generated any more</a> because there is too much data.";
    result += " Computerteddy recommends to use <a href=\"http://wiki.openstreetmap.org/wiki/User:Computerteddy#Standard_Kartens.C3.A4tze\">his Europe map</a> instead.</div>";
    result += "<div class='main' style='font-size:10pt'>";

    var gentopo = document.getElementById('srtm2osm').checked;
    if(gentopo){
        topotiles = '<hr /><div class="topotiles">';
        topotiles += '<a href="http://wiki.openstreetmap.org/index.php/Srtm2Osm">';
        topotiles += "srtm2osm</a> command line for corresponding elevation ";
        topotiles += "contour tiles. The tile number of the topo tiles is the ";
        topotiles += "tile number for the corresponding map tiles with the leading ";
        topotiles += "6 replaced by 5. Thus, name clashes are avoided."
        topotiles += "<pre  style='font-size:10pt'>\n";
    }

    var south = Math.floor(bb.south / KSIZE) * KSIZE;
    var west = Math.floor(bb.west / KSIZE) * KSIZE;

    for (var lon = west; lon<= bb.east; lon+=KSIZE){
        var i = 0;
        for(var lat = south; lat<bb.north; lat+=KSIZE){
            var tileno = kachel(lat, lon, KSIZE);
            var href = SERVER.replace(/\.{3}/, "pub/misc/openstreetmap/teddynetz.de");
            if (SERVER == 'http://osm.ammit.de/osm/latest/img/'){
                href += tileno + ".img.gz";
            } else {
                href += ( "" + tileno).substring(0,5) + "/" + tileno + ".img.gz"
            }
            result +="<a style='font-size:75%' href='" + href + "'>" + href + "</a> "
            result +='<img onclick="showTile(' + tileno + ',' + KSIZE + ')" src="http://touren.mospace.de/icon/osm" style="cursor:pointer"/>'
            result += "<br/>\n";
            if(gentopo){
                topotiles += topokachel(lat, lon, KSIZE, tileno);
            }
            //document.writeln(++i + ":" + lat + ": " + (lat+90.)/KSIZE + " : " + Math.floor((lat + 90. ) / KSIZE) + "<br>");
        }
    }
    result += "\n</div>";
    html += result;
    html += "<pre>\n\n\n</pre>";
    if (gentopo){
        topotiles += "</pre></div>";
        html += topotiles;
    }
    html += "</div>\n";
    return html;
}

function topokachel(lat, lon, ksize, tileno){
    var south = Math.floor(lat / ksize) * ksize;
    var west = Math.floor(lon / ksize) * ksize;
    return "srtm2osm  -bounds1 " +  south + " " + west + " " + (south + ksize) + " " + (west + ksize) + " -o " + (tileno - 10000000) + ".osm\n";
}

function kachel(lat, lon, ksize){
    //Nummer=((int)((48,20+90)/1.5)+(int)((16,37+180)/1.5)*(int)(180/1.5))+63240001
    return (Math.floor((lat + 90. ) / ksize) +
        Math.floor((lon + 180.) / ksize) * Math.floor(180. / ksize)
        ) + 63240001;
}

function unkachel(kachelno, ksize){
    num = kachelno - 63240001;
    lonfac  = Math.floor(180/ksize);
    lonpart = Math.floor(num/lonfac);
    latpart = num - lonpart * lonfac;
    latlon  = {};
    latlon.lat = latpart * ksize - 90;
    latlon.lon = lonpart * ksize - 180;
    return latlon;
}

var gpxmap;
function initMap(){
    if (!gpxmap){
        gpxmap = new Mospace.OpenLayersMap('map', {
        baselayers: { osmmapnik:true }});
    }
    bounds = {W:-179, N:90, S:-90, E:180};
    gpxmap.setBounds(bounds);
    resizeMap();
}

var box;
function showTile(kachelno, ksize){
    if (!gpxmap){
        gpxmap = new Mospace.OpenLayersMap('map', {
        baselayers: { osmmapnik:true }});
    }
    var bl = unkachel(kachelno, ksize);
    var left   = bl.lon;
    var bottom = bl.lat;
    var right  = left + ksize;
    var top    = bottom + ksize;
    if (box){
        gpxmap.removeBoxFromMap(box);
    }
    bounds = {W:right,S:bottom,E:left,N:top};
    box = gpxmap.addBox(bounds);
    resizeMap();
    gpxmap.setBounds(bounds);
    ptileno = document.getElementById('tileno');
    if(ptileno){
        ptileno.innerHTML = "" + kachelno;
    }
}

function eml(s){
    var r = unescape(s);
    var l = r.length;
    var o = "";
    for (i = 0; i < l; i++)
    {
        o += String.fromCharCode(r.charCodeAt(i) - 2);
    }
    document.location.href =  "mail" + "to:" + o;
}


