/*
* Freemap Embedded - (C)2007-2009 Freemap Slovakia
*/

function _getFreemapScriptLocation() {
    var scriptLocation = "";
    var SCRIPT_NAME = "freemap_embedded.js";
 
    var scripts = document.getElementsByTagName('script');
    for (var i = 0; i < scripts.length; i++) {
        var src = scripts[i].getAttribute('src');
        if (src) {
            var index = src.lastIndexOf(SCRIPT_NAME);
            // is it found, at the end of the URL?
            if ((index > -1) && (index + SCRIPT_NAME.length == src.length)) {
                scriptLocation = src.slice(0, -SCRIPT_NAME.length);
                break;
            }
        }
    }
    return scriptLocation;
}

var map;
var PI = 3.14159265358979323846;
var banners;
var bannerid;
var marker, LayerMarkers, LayerCustomMarkers;
var LayerVectors, LayerMap;

var jsfiles=new Array(
    "OpenLayers2.7.js",
    "fm_mousepositionmercator_e.js",
    "fm_scalevisual_e.js",
    "fm_panzoombar_e.js",
    "fm_logo_e.js",
    "GPX_merc.js",
    "KML_merc.js"
    ); // etc.

var allScriptTags = "";
var host = _getFreemapScriptLocation();

for (var i = 0; i < jsfiles.length; i++) {
    document.write("<script src='" + host + jsfiles[i] + "' language='javascript' type='text/javascript'></script>");
}

var cssfiles=new Array(
    "freemap_embedded.css"
    ); // etc.

for (var i = 0; i < cssfiles.length; i++) {
    document.write("<link rel='stylesheet' type='text/css' href='" + host + cssfiles[i] + "'/>");
}

function freemap_init(lat, lon, zoom, div, fixedmap, uselayers, usemarker, mlat, mlon ) {
    OpenLayers.ImgPath = "/img/";

    lon_map = lon * 20037508.34 / 180;
    lat_map = Math.log(Math.tan( (90 + lat) * PI / 360)) / (PI / 180);
    lat_map = lat_map * 20037508.34 / 180;

    mlon_map = mlon * 20037508.34 / 180;
    mlat_map = Math.log(Math.tan( (90 + mlat) * PI / 360)) / (PI / 180);
    mlat_map = mlat_map * 20037508.34 / 180;


    elm = document.getElementById(div);
    var s= new String();
    s='<table width="100%" height="100%" border="0px" cellspacing="0px" cellpadding="0px">';
    s+=' <tr><td width="100%" height="100%" colsp><div id="mapborder" style="width:100%;height:100%"><div id="map" style="width:100%;height:100%"></div></div></td></tr>'
    s+='<tr><td><div id="banners" align="center"></div></td></tr>'
    s+='</table>'

    elm.innerHTML=s;

    banners = new Array(
        'Mapové podklady',
        '&copy;2009 various <a href="http://www.openstreetmap.org/" target="_blank">OpenStreetMap</a> contributors',
        'Poskytovane pod licenciou Creative Commons <a href="http://creativecommons.org/licenses/by-sa/2.0/" target="_blank">CC-BY-SA 2.0</a>',
        'Mapu poskytuje',
        'Copyright &copy;2009 Freemap Slovakia (<a href="http://wiki.freemap.sk/EmbeddedFreemap" target="_blank">www.freemap.sk</a>)'
        );

    bannerid=0;
    rotatebanner();

    OpenLayers.Util.onImageLoadErrorColor= "#E7FFC2";

    OpenLayers.Util.onImageLoadError = function() {
        this.style.backgroundColor= null;
        this.src = "img/transp404.png";
    };

    pzb =new OpenLayers.Control.PanZoomBar();
    pzb.position = new OpenLayers.Pixel(10,10);

    map = new OpenLayers.Map( "map", {
        controls:[
        //new OpenLayers.Control.LayerSwitcher(),
        new OpenLayers.Control.MousePositionMercator(),
        new OpenLayers.Control.ScaleVisual(),
        new OpenLayers.Control.Attribution(),
        new OpenLayers.Control.FreemapLogo(),
        pzb
        ],

        maxExtent: new OpenLayers.Bounds(-20037508.34,-20037508.34,20037508.34,20037508.34),
        numZoomLevels:17,
        maxZoomLevels:17,
        maxResolution:156543,
        units:'m',
        projection: new OpenLayers.Projection("EPSG:900913"),
        displayProjection: new OpenLayers.Projection("EPSG:4326")
    }
    );

    if (fixedmap == false) {
        map.addControl (new OpenLayers.Control.Navigation( {
            zoomWheelEnabled: false
        } ))
    }

    //map.addControl (new OpenLayers.Control.PanZoom());

    LayerMap = new OpenLayers.Layer.TMS( "Freemap Slovakia",
        "http://tiles.freemap.sk/" + uselayers,
        {
            type:'jpeg',
            attribution: "<a href='http://www.freemap.sk' target='_blank'>Freemap Slovakia</a>, <a href='http://www.openstreetmap.org' target='_blank'>OpenStreetMap</a>",
            getURL: get_osm_url
        });

    LayerMap.setVisibility(true);

    map.addLayer(LayerMap);

    if (LoadObjects != "") {
        LayerVectors = new OpenLayers.Layer.Vector("vectors");
        LayerVectors.setIsBaseLayer(false);
        LayerVectors.setVisibility(true);
        LayerVectors.displayInLayerSwitcher = false;

        map.addLayer(LayerVectors);
    }
		

    if (usemarker != "") {
        
        if (marker_type == "image"){
            LayerMarkers = new OpenLayers.Layer.Markers("markers");
            var near_icon = embeddedIcon(usemarker);
            marker = new OpenLayers.Marker(new OpenLayers.LonLat(mlon_map, mlat_map),near_icon.clone());
            LayerMarkers.addMarker(marker);
            map.addLayer(LayerMarkers);
        }
        if (marker_type == "txt"){
            LayerCustomMarkers = new OpenLayers.Layer.Text( "Markers", {
                location: "proxy.php?proxy_url="+usemarker,
                projection: "EPSG:4326"
            });
            map.addLayer(LayerCustomMarkers);
        }

    }

    map.setCenter(new OpenLayers.LonLat(lon_map, lat_map), zoom);

    if (LoadObjects != "")
        LoadMyObjects(type);
}

function rotatebanner() {
    elm = document.getElementById("banners");
    elm.innerHTML = banners[bannerid];

    window.setTimeout("rotatebanner()", 3000);

    if (bannerid < banners.length-1)
        bannerid++;
    else
        bannerid=0;
}

function get_osm_url (bounds) {
    var res = this.map.getResolution();
    var x = Math.round ((bounds.left - this.maxExtent.left) / (res * this.tileSize.w));
    var y = Math.round ((this.maxExtent.top - bounds.top) / (res * this.tileSize.h));
    var z = this.map.getZoom();
    var path = "/" + z + "/" + x + "/" + y;
    var url = this.url;
    if (url instanceof Array) {
        url = this.selectUrl(path, url);
    }
    return url + path;
}

function get_base_url (bounds) {
    return "img/transp404.png";
}

function embeddedIcon(url) {
    var w=64;
    var h=64;
    var x=-18;
    var y=-51;
    var url_comp = url.split(",");
    if (url_comp.length>=3) {
        w= url_comp[1];
        h= url_comp[2];
    }
    if (url_comp.length==5) {
        x= url_comp[3];
        y= url_comp[4];
    }
    var size = new OpenLayers.Size(w, h);
    var calcOffset = new OpenLayers.Pixel(x,y);
    return new OpenLayers.Icon(url_comp[0], size, calcOffset,null);
}

function LoadMyObjects(type) {
    if (LoadObjects != "") {
        if(type=="gpx") Ajax("proxy.php?proxy_url="+LoadObjects, LoadGPX);
        if(type=="kml") Ajax("proxy.php?proxy_url="+LoadObjects, LoadKML);
    }
}

function LoadGPX(element) {
    LayerVectors.destroyFeatures();
    var log = new OpenLayers.Format.GPX();
    //log.internalProjection = new OpenLayers.Projection("EPSG:4326");
    //log.externalProjection = new OpenLayers.Projection("EPSG:41001");
    var features = log.read(element);
    var bounds;
    if (features) {
        if(features.constructor != Array) {
            features = [features];
        }
        LayerVectors.addFeatures(features);

        if (NoLonLat) {
            for(var i=0; i<features.length; ++i) {
                if (!bounds) {
                    bounds = features[i].geometry.getBounds();
                } else {
                    bounds.extend(features[i].geometry.getBounds());
                }
            }
            map.zoomToExtent(bounds);
        }
    } else {
        alert('Bad GPX: ' + element);
    }
}

function LoadKML(element) {
    LayerVectors.destroyFeatures();
    var log = new OpenLayers.Format.KML();
    log.extractStyles=true;
    //log.internalProjection = new OpenLayers.Projection("EPSG:4326");
    //log.externalProjection = new OpenLayers.Projection("EPSG:41001");
    var features = log.read(element);
    var bounds;
    if (features) {
        if(features.constructor != Array) {
            features = [features];
        }
        LayerVectors.addFeatures(features);

        if (NoLonLat) {
            for(var i=0; i<features.length; ++i) {
                if (!bounds) {
                    bounds = features[i].geometry.getBounds();
                } else {
                    bounds.extend(features[i].geometry.getBounds());
                }
            }
            map.zoomToExtent(bounds);
        }
    } else {
        alert('Bad KML: ' + element);
    }
}

function Ajax(URL, Callback) {
    try {
        request = new XMLHttpRequest();
    }
    catch(e) {
        try {
            request = new ActiveXObject('Microsoft.XMLHTTP');
        }
        catch(e) {
        }
    }
    var Text = "";
    if (request != null) {
        request.onreadystatechange =
        function() {
            if (request.readyState == 4) {
                if (request.status == 200) {
                    Text = request.responseText;
                    if (Callback)
                        Text = Callback(Text);
                } else {
                    alert("Problem retrieving external data");
                }
            }
        }
    }

    request.open("GET",  URL, true);
    request.send(null);
}
