/*SET GLOBAL VARIABLES*/

var lon        = 19.56;
var lat        = 48.73;
var zoom       = 8;
var maxZoom    = 15;
var fullscreen = false;

var map, layer, vectors, features, formats, bGPhy, bGSat, bSHO, lTZT, styleMap, drawControls, pointLayer, lineLayer, fPos, selectChata, selectLimba, selectFoto, selectGC, selectedFeature, chaty, limba, foto, GC, stylePointer, results_count;

var attrib        = new Array();

attrib["TOPO"]    = '<small>Topografický podklad © SHOCart</small>';
attrib["TZT"]     = '<small>Značky a rázcestia © HIKING.SK</small>';

function init(){
    OpenLayers.IMAGE_RELOAD_ATTEMPTS = 3;
    panZoom   = new OpenLayers.Control.PanZoom({slideFactor: 192});
    panZoom.position.x = 5;
    panZoom.position.y = 35;
	
    kbDef = new OpenLayers.Control.KeyboardDefaults({slideFactor: 192});
    
    map = new OpenLayers.Map('map',
                { controls:[
		              new OpenLayers.Control.MouseDefaults(),
		              new OpenLayers.Control.Permalink(),
		              new OpenLayers.Control.Attribution({separator:"<br />"}),
		              kbDef, panZoom],
                  maxExtent: new OpenLayers.Bounds(-20037508, -20037508, 20037508, 20037508.34),
                  numZoomLevels:16, units:'m', projection: "EPSG:900913"
                });
            
    /*bGPhy = new OpenLayers.Layer.OSM();*/
    /*bGPhy = new OpenLayers.Layer.XYZ(
                "Freemap.sk","http://www.freemap.sk/layers/allinone/?/BRN/${z}/${x}/${y}.png",{sphericalMercator: true, attribution:'<small>Podklad © Freemap.sk</small>'});*/
    
/*SET LAYERS*/

    bGPhy = new OpenLayers.Layer.Google("Google Physical",{type: G_PHYSICAL_MAP, sphericalMercator:true});    
    bGSat = new OpenLayers.Layer.Google("Google Satellite",{type: G_HYBRID_MAP, sphericalMercator:true});
   
    bSHO  = new OpenLayers.Layer.XYZ("TOPO","http://mapy.hiking.sk/tiles/topo/${z}/${x}/${y}.png",{  
                     attribution: attrib['TOPO'], sphericalMercator: true, buffer: 0});
    
    lTZT = new OpenLayers.Layer.TileCache("TZT tiles","http://mapy.hiking.sk/tiles","tzt",{
                     attribution: attrib["TZT"] , sphericalMercator: true, buffer: 0});


        
    styleMap = new OpenLayers.StyleMap(OpenLayers.Util.applyDefaults(
                        {fillOpacity: 0.3, fillColor: "none", strokeOpacity:0.7, strokeWidth:4},
                    OpenLayers.Feature.Vector.style["default"]));
    
    var styleDomcek = OpenLayers.Util.extend({}, OpenLayers.Feature.Vector.style['default']);
    styleDomcek.graphicWidth   = 14;
    styleDomcek.graphicHeight  = 14;
    styleDomcek.graphicXOffset = -7;  // this is the default value
    styleDomcek.graphicYOffset = -10;
    styleDomcek.graphicOpacity = 1;
    
    stylePointer = OpenLayers.Util.extend({}, styleDomcek);
    stylePointer.graphicWidth = 27;
    stylePointer.graphicHeight  = 27;
    stylePointer.graphicXOffset = -14;  // this is the default value
    stylePointer.graphicYOffset = -23;
    
    var styleChaty = OpenLayers.Util.extend({}, styleDomcek);
    styleChaty.externalGraphic = "/OpenLayers/img/features/chaty.gif";
    
    var styleLimba = OpenLayers.Util.extend({}, styleDomcek);
    styleLimba.externalGraphic = "/OpenLayers/img/features/limba.gif";
    
    var styleGC = OpenLayers.Util.extend({}, styleDomcek);
    styleGC.externalGraphic = "/OpenLayers/img/features/geocache.gif";
    styleGC.graphicWidth   = 12;
    styleGC.graphicHeight  = 10;
    styleGC.graphicXOffset = -6;  // this is the default value
    styleGC.graphicYOffset = -5;
    
    var styleHrady = OpenLayers.Util.extend({}, styleDomcek);
    styleHrady.externalGraphic = "/OpenLayers/img/features/hrad.gif";
    
    var styleFoto = OpenLayers.Util.extend({}, styleDomcek);
    styleFoto.externalGraphic = "/OpenLayers/img/features/image.gif";
    styleFoto.graphicYOffset = -7;
    
    //Style2
    sketchSymbolizers = {
            "Point": {
                pointRadius: 8,
                graphicName: "cross",
                fillColor: "#FF0000",
                fillOpacity: 0.8,
                strokeWidth: 1,
                strokeOpacity: 1,
                strokeColor: "white"
            },
            "Line": {
                strokeWidth: 3,
                strokeOpacity: 0.9,
                strokeColor: "#FF0000",
                strokeDashstyle: "dash"
            }
        };
    var style = new OpenLayers.Style();
    style.addRules([
        new OpenLayers.Rule({symbolizer: this.sketchSymbolizers})
    ]);
    styleMap2 = new OpenLayers.StyleMap({"default": style});
    
    styleHPtrack = new OpenLayers.StyleMap(OpenLayers.Util.applyDefaults(
                        {fillOpacity: 0.3, fillColor: "none", strokeOpacity:0.5, strokeWidth:11, strokeColor: "#FF6666"},
                    OpenLayers.Feature.Vector.style["default"]));
    
    vectors    = new OpenLayers.Layer.Vector("GPX imports",{styleMap: styleMap});
    hpTracks   = new OpenLayers.Layer.Vector("Hikeplanner routes",{styleMap: styleHPtrack}); 
    pointLayer = new OpenLayers.Layer.Vector("Point Layer",{styleMap: styleMap2});
    lineLayer  = new OpenLayers.Layer.Vector("Line Layer",{styleMap: styleMap});
    features   = new OpenLayers.Layer.Vector("Features",{styleMap: styleMap2});
    
    chaty = new OpenLayers.Layer.WFS('chaty, útulne, salaše, búdy', "http://mapy.hiking.sk/wfs/get_gml.php?",
                    {TYPENAME:"clanky_chaty",MAXFEATURES:"150"},
                    {extractAttributes: true,style: styleChaty});
    chaty.projection = "EPSG:4326";
    
    limba = new OpenLayers.Layer.WFS('Ubytovanie Limba', "http://mapy.hiking.sk/wfs/get_gml.php?",
                    {TYPENAME:"limba",MAXFEATURES:"100"},
                    {extractAttributes: true,style: styleLimba});
    limba.projection = "EPSG:4326";
    
    foto = new OpenLayers.Layer.WFS('Fotografie', "http://mapy.hiking.sk/wfs/get_gml.php?",
                    {TYPENAME:"foto",MAXFEATURES:"150"},
                    {extractAttributes: true,style: styleFoto});
    foto.projection = "EPSG:4326";
    
    GC = new OpenLayers.Layer.WFS('Geocache', "http://mapy.hiking.sk/wfs/get_gml.php?",
                    {TYPENAME:"geocache",MAXFEATURES:"150"},
                    {extractAttributes: true,style: styleGC});
    GC.projection = "EPSG:4326";
	
    hrady = new OpenLayers.Layer.WFS('Hrady', "http://mapy.hiking.sk/wfs/get_gml.php?",
                    {TYPENAME:"hrady",MAXFEATURES:"150"},
                    {extractAttributes: true,style: styleHrady});
    hrady.projection = "EPSG:4326";
    
    selectChata = new OpenLayers.Control.SelectFeature(chaty,{onSelect: onChataSelect, onUnselect: onChataUnselect, hover: false, toggle: true});
    selectLimba = new OpenLayers.Control.SelectFeature(limba,{onSelect: onLimbaSelect, onUnselect: onLimbaUnselect, hover: false, toggle: true});
    selectFoto  = new OpenLayers.Control.SelectFeature(foto ,{onSelect: onFotoSelect,  onUnselect: onFotoUnselect,  hover: false, toggle: true});
    selectGC    = new OpenLayers.Control.SelectFeature(GC   ,{onSelect: onGCSelect,    onUnselect: onGCUnselect,    hover: false, toggle: true});
    selectHrady = new OpenLayers.Control.SelectFeature(hrady,{onSelect: onHradySelect, onUnselect: onHradyUnselect, hover: false, toggle: true});
    
    lTZT.setVisibility(1);
    lTZT.setIsBaseLayer(0);
    bSHO.setIsBaseLayer(1);
    bGPhy.setIsBaseLayer(1);
    bGSat.setIsBaseLayer(1);
    limba.setVisibility(0);
    chaty.setVisibility(0);
    foto.setVisibility(0);
    GC.setVisibility(0);
    hrady.setVisibility(0); 
    
    /*bSHO.transitionEffect = "resize";
    lTZT.transitionEffect = "resize";*/
    
    map.addLayers([bGPhy,bGSat,bSHO,hpTracks,lTZT,vectors,lineLayer,pointLayer,features,chaty,limba,foto,GC,hrady]);
    //nemenit poradie layerov!
    
    drawControls = {
        point: new OpenLayers.Control.DrawFeature(pointLayer,OpenLayers.Handler.Point,{handlerOptions:{freehand: false, style:"default", layerOptions: {styleMap: styleMap2}}}),
        line: new OpenLayers.Control.DrawFeature(lineLayer,OpenLayers.Handler.Path,{handlerOptions: {freehand: false, style:"default", layerOptions: {styleMap: styleMap}}}),
        measure: new OpenLayers.Control.Measure(OpenLayers.Handler.Path, {handlerOptions: {style: "default", layerOptions: {styleMap: styleMap2}, persist: true},geodesic: true})
    };
    
    /*drawControls.measure.geodesic = true;*/

    var control;
    for(var key in drawControls) {
        if (key == 'measure'){
            control = drawControls[key];
            control.events.on({
                "measure": handleMeasurements, "measurepartial": handleMeasurements
            });        
        }
        map.addControl(drawControls[key]);
    }
    map.addControl(selectChata);
    map.addControl(selectLimba);
    map.addControl(selectFoto);
    map.addControl(selectGC);
    map.addControl(selectHrady);
    selectChata.activate();
    selectLimba.activate();
    selectFoto.activate();
    selectGC.activate();
    selectHrady.activate();
    
    if ((_GETvar('x')!="" && _GETvar('y')!="") || (_GETvar('lon')=="" && _GETvar('lat')=="")){
        var pozicia;
        var mapZoom;
        if(_GETvar('x')!="" && _GETvar('y')!=""){
            pozicia = new OpenLayers.LonLat(_GETvar('x'), _GETvar('y'))
            mapZoom = 14
            pozicia.transform(new OpenLayers.Projection("EPSG:4326"),new OpenLayers.Projection("EPSG:900913"));
            map.setCenter(pozicia, mapZoom);
            features.removeFeatures(fPos);
            fPos = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Point(pozicia.lon,pozicia.lat));
            features.addFeatures(fPos);
            correctLayers();        
        } else if (_GETvar('q').trim() !=""){
            goSearch(_GETvar('q'), _GETvar('st'));
        } else {
            pozicia = new OpenLayers.LonLat(lon,lat);
            mapZoom = zoom;  
            pozicia.transform(new OpenLayers.Projection("EPSG:4326"),new OpenLayers.Projection("EPSG:900913"));
            map.setCenter(pozicia, mapZoom);
        }
    }
    
    map.events.register("click", map, function(e) {
        var lonlat = map.getLonLatFromViewPortPx(e.xy);
        var divPos = document.getElementById('tm_getposition_results');
        var chbPos = document.getElementById('tm_getposition');
        var htmlPos;
        if (chbPos.checked){
            features.removeFeatures(fPos);
            fPos = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Point(lonlat.lon,lonlat.lat));
            features.addFeatures(fPos);
            lonlat.transform(new OpenLayers.Projection("EPSG:900913"), new OpenLayers.Projection("EPSG:4326"));
            ll = formatPosition(lonlat, "minutes",3);
            htmlPos = "<tt>" + ll.lat + " " + ll.lon + "<br/>";
            ll = formatPosition(lonlat, "decimal",5);
            htmlPos += ll.lat + " " + ll.lon + "</tt><br /> ";
            htmlPos += '<a href="/?x=' + lonlat.lon + '&y=' + lonlat.lat + '">permalink</a> <small>[?]</small>';
            divPos.innerHTML = htmlPos;
        }
    });
    
    map.events.register("zoomend", map, correctLayers);
    
    updateFormats();
    document.getElementById('map').style.height = document.body.clientHeight - 84
    document.getElementById('top_menu').style.zIndex = 9999;
    document.getElementById('top_logo').style.zIndex = 9998;
    window.onresize = resizeMap;
    
    try {
        gpxResult = frames['tm_gpx_upload_target'].document.getElementById('gpx');	
        if (typeof gpxResult.innerHTML != "undefined") {
    	    stopGpxUpload();    
        }
    } catch (err) {
	
    }
    
    try {
        var hpid = _GETvar("hpid");
        if (hpid.length > 10) {
            document.getElementById('tm_hiking_login').src = "http://mapy.hiking.sk/gpx/get_from_hp.php?hpid="+hpid;
        }
    } catch (err) {
    }
    
    map.pan(2,2);
    map.pan(-2,-2);

}



function onChataSelect(feature){
    selectedFeature = feature;
    popup = new OpenLayers.Popup.FramedCloud("chicken", 
                             feature.geometry.getBounds().getCenterLonLat(),
                             null,
                             "<div style='font-size:.7em; width:250px'><b>" + feature.attributes.nazov +'</b><br/><br/><img style="float: left; margin: 0px 7px 5px 0px" src="'+ feature.attributes.thumb +'"/>' + feature.attributes.popis +' <a style="color: blue" target="_blank" href="'+feature.attributes.link+'">»&nbsp;link</a><br/></div>',
                             null, true, onChataPopupClose);
    feature.popup = popup;
    map.addPopup(popup);
}

function onFotoSelect(feature){
    selectedFeature = feature;
    popup = new OpenLayers.Popup.FramedCloud("chicken", 
                             feature.geometry.getBounds().getCenterLonLat(),
                             null,
                             "<div style='font-size:.7em; width:250px'><b>" + feature.attributes.nazov +'</b><br/><img style="float: left; margin: 5px 0px 5px 0px" src="'+ feature.attributes.thumb +'"/>' + feature.attributes.popis +' <a style="color: blue" target="_blank" href="'+feature.attributes.link+'">»&nbsp;link</a><br/></div>',
                             null, true, onFotoPopupClose);
    feature.popup = popup;
    map.addPopup(popup);
}

function onGCSelect(feature){
    selectedFeature = feature;
    popup = new OpenLayers.Popup.FramedCloud("chicken", 
                             feature.geometry.getBounds().getCenterLonLat(),
                             null,
                             "<div style='font-size:.7em;'><b>" + feature.attributes.nazov + ' (' + feature.attributes.wpt + ')</b><br/>typ: ' + feature.attributes.typ + '<br/>veľkosť: ' + feature.attributes.velkost + ' <br/>autor: ' + feature.attributes.autor + ' <br/>založená: ' + feature.attributes.zalozena + ' <br/>obtiažnosť: ' + feature.attributes.obtiaznost + ' <br/>stav: ' + feature.attributes.stav + ' <br/><a style="color: blue" target="_blank" href="'+feature.attributes.link+'">»&nbsp;link</a><br/></div>',
                             null, true, onGCPopupClose);
    feature.popup = popup;
    map.addPopup(popup);
}

function onHradySelect(feature){
    selectedFeature = feature;
	var img = "";
	var popis = "";
	if (typeof feature.attributes.obrazok != "undefined") img = '<img style="" src="'+ feature.attributes.obrazok +'"/><br/>';
	if (typeof feature.attributes.popis != "undefined") popis = feature.attributes.popis;
    popup = new OpenLayers.Popup.FramedCloud("chicken", 
                             feature.geometry.getBounds().getCenterLonLat(),
                             null,
                             "<div style='font-size:.7em; width:250px'><b>" + feature.attributes.nazov +'</b><br/><br/>' + img + popis +' <a style="color: blue" target="_blank" href="'+feature.attributes.link+'">»&nbsp;link</a><br/></div>',
                             null, true, onHradyPopupClose);
    feature.popup = popup;
    map.addPopup(popup);
}

function onLimbaSelect(feature){
    selectedFeature = feature;
    popup = new OpenLayers.Popup.FramedCloud("chicken", 
                             feature.geometry.getBounds().getCenterLonLat(),
                             null,
                             "<div style='font-size:.7em;width:170px'><b>" + feature.attributes.typ +'</b><br/><br/><img style="margin: 0px 0px 0px 0px" src="'+ feature.attributes.pic +'"/><br/><b>kapacita:</b> ' + feature.attributes.kapacita +' <br/><b>cena v lete:</b> '+feature.attributes.cenaleto+' €<br/><b>cena v zime:</b> '+feature.attributes.cenazima+' €<br/><a style="color: blue" target="_blank" href="'+feature.attributes.link+'">»&nbsp;link</a><br/></div>',
                             null, true, onLimbaPopupClose);
    feature.popup = popup;
    map.addPopup(popup);
}

function onLimbaPopupClose(evt) {
    selectLimba.unselect(selectedFeature);
}

function onHradyPopupClose(evt) {
    selectHrady.unselect(selectedFeature);
}

function onFotoPopupClose(evt) {
    selectFoto.unselect(selectedFeature);
}

function onChataPopupClose(evt) {
    selectChata.unselect(selectedFeature);
}

function onGCPopupClose(evt) {
    selectGC.unselect(selectedFeature);
}

function onChataUnselect(feature){
    map.removePopup(feature.popup);
    feature.popup.destroy();
    feature.popup = null;
}

function onFotoUnselect(feature){
    map.removePopup(feature.popup);
    feature.popup.destroy();
    feature.popup = null;
}

function onLimbaUnselect(feature){
    map.removePopup(feature.popup);
    feature.popup.destroy();
    feature.popup = null;
}

function onGCUnselect(feature){
    map.removePopup(feature.popup);
    feature.popup.destroy();
    feature.popup = null;
}

function onHradyUnselect(feature){
    map.removePopup(feature.popup);
    feature.popup.destroy();
    feature.popup = null;
}

function correctLayers(){
    
    var tzt  = document.getElementById('layerTZT');
    var zoom = map.getZoomForResolution(map.getResolution());
    var topo = document.getElementById('map_topo').checked;
    
    
    if(_GETvar("layers")!="") {
    
    //zapnut prepinac podla layers premennej	
	
    } else {
	
    	if (zoom > 12) {
    	    if (topo) map.setBaseLayer(bSHO);
    	    tzt.disabled = false;
    	    if (tzt.checked && lTZT.getVisibility() == false){
    		    lTZT.setVisibility(1);
    	    }
    	    
    	    if (zoom > maxZoom){
    	        map.zoomTo(maxZoom);
    	    }
    	    
    	} else if (zoom <= 12){
    	    if(topo){
    		  map.setBaseLayer(bGPhy);
    	    } else {
    		  map.setBaseLayer(bGSat);
    	    }
    	    if (zoom <= 10 && lTZT.getVisibility() == true){
    		  lTZT.setVisibility(0);
    		  tzt.disabled = true;
    	    } else if (zoom > 11 && tzt.checked && lTZT.getVisibility() == false) {
    		  lTZT.setVisibility(1);
    		  tzt.disabled = false;
    	    }
    	}
    }
}

function resizeMap(){
    if (fullscreen){
        document.getElementById('map').style.height = document.body.clientHeight - 24;
    } else {
        document.getElementById('map').style.height = document.body.clientHeight - 84;
    }
    /*resizeResults()*/
}

function formatPosition(lonlat, type, decimals){
    var out = new Object();
    var dec = Math.pow(10,decimals);
    if (type == "decimal") {
        out.lon = "E" + Math.round(lonlat.lon * dec)/(dec);
        out.lat = "N" + Math.round(lonlat.lat * dec)/(dec);
    } else if (type == "minutes") {
        var degLon = Math.floor(lonlat.lon);
        var degLat = Math.floor(lonlat.lat);
        var minLon = Math.round(60*(lonlat.lon - degLon)* dec)/(dec);
        var minLat = Math.round(60*(lonlat.lat - degLat)* dec)/(dec);
        out.lon    = "E" + degLon + '°' + minLon + '"';
        out.lat    = "N" + degLat + '°' + minLat + '"';
    }
    return out;
}

function tm3search(){
    var pInput = new Object();
    eNotice = document.getElementById("tm3notice");
    eNotice.innerHTML = "";
    if (document.getElementById("tm3radio1").checked) {
        var pOK = true;
        var latDeg = document.getElementById("tm31latDeg");
        var latMin = document.getElementById("tm31latMin");
        var lonDeg = document.getElementById("tm31lonDeg");
        var lonMin = document.getElementById("tm31lonMin"); 
        
        if (isNaN(latDeg.value) || (latDeg.value > 51 || latDeg.value < 46)) pOK = false;
        if (isNaN(lonDeg.value) || (lonDeg.value > 25 || lonDeg.value < 15)) pOK = false;
        if (isNaN(latMin.value)) pOK = false;  
        if (isNaN(latMin.value)) pOK = flase;
        
        if (pOK == true) {
            pInput.lat = (latDeg.value*1) + ((latMin.value) / 60);
            pInput.lon = (lonDeg.value*1) + ((lonMin.value) / 60);
        } else {
            eNotice.innerHTML = "Chyba: nekorektne zadané súradnice";    
        } 
        
    } else if (document.getElementById("tm3radio2").checked) {
        var pOK = true;
        var lat = document.getElementById("tm32lat");
        var lon = document.getElementById("tm32lon");
        if (isNaN(lat.value) || (lat.value > 51 || lat.value < 46)) pOK = false;
        if (isNaN(lon.value) || (lon.value > 25 || lon.value < 15)) pOK = false;
        if (pOK == true) {
            pInput.lat = lat.value;
            pInput.lon = lon.value;
        } else {
            eNotice.innerHTML = "Chyba: nekorektne zadané súradnice";    
        }    
    } else if (document.getElementById("tm3radio3").checked) {
        var q = document.getElementById("tm33search").value.trim();
        eNotice.innerHTML = "";
        if (q.length > 2){
            goSearch(q,"");
        } else {
            setTimeout("eNotice.innerHTML = 'Chyba: treba zadať aspoň 3 znaky.';",200);
        }
        
    } else {
        eNotice.innerHTML = "Chyba: treba vybrať jednu z metód vyhľadávania";
    }
    
    if ((typeof pInput.lon != "undefined") && (typeof pInput.lat != "undefined")){
        var pozicia;
        if(pozicia = new OpenLayers.LonLat(pInput.lon, pInput.lat)){
            pozicia.transform(new OpenLayers.Projection("EPSG:4326"),new OpenLayers.Projection("EPSG:900913"));
            map.setCenter(pozicia, 14);
            features.removeFeatures(fPos);
            fPos = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Point(pozicia.lon,pozicia.lat));
            features.addFeatures(fPos);
        }
    }
    return false;  
}

function handleMeasurements(event) {

    var geometry = event.geometry;
    var units = event.units;
    var order = event.order;
    var measure = event.measure;
    var element = document.getElementById('measureOut');
    var out = ": ";
    if(order == 1) {
        out += measure.toFixed(2) + " " + units;        
    }
    element.innerHTML = out;
}

function delDrawn(s){
    if (s == 'points'){
        pointLayer.destroyFeatures();
    } else if (s == 'lines'){
        lineLayer.destroyFeatures();
    }
}

function serializeDrawn(s){
    
// kexo    
    if (s == 'points'){
        var str = formats['out']['wkt'].write(pointLayer.features, 0);
    } else if (s == 'lines'){
        var str = formats['out']['wkt'].write(lineLayer.features, 0);
    }

  str = str.replace(/([0-9]{5})([0-9]*)/g,'$1');

  frm = document.forms['dataForm'];
  frm.data.value = str;
  frm.setAttribute('action', '/gpx/cacheFile.php');
//  frm.setAttribute('target', '_blank');
  frm.submit();

}

function startGpxUpload() {
    document.getElementById('tm_gpx_status').innerHTML = "posielam súbor ...";
    return true;
}

function stopGpxUpload() {
    
    try {
        var gpxStatus = document.getElementById('tm_gpx_status');
        var gpxResult = frames['tm_gpx_upload_target'].document.getElementById('gpx');
        var result    = gpxResult.innerHTML;
    } catch (err) {
        gpxStatus.innerHTML = "Prehliadač nepodporuje túto funkciu. Skús Firefox, Chrome, Safari alebo Operu.";
    }
    
    if (result == "invalid XML") {
        //alert(result);
        alert ("Súbor nie je korektný GPX súbor.");
        gpxStatus.innerHTML = "Súbor nie je korektný GPX súbor.";
    } else if (result != 0){
        gpxStatus.innerHTML = "súbor odoslaný";
        
        var type = "gpx";
        try {
            var features = formats['in'][type].read(result);
        } catch (err) {
            gpxStatus.innerHTML = "Prehliadač nepodporuje túto funkciu. Skús Firefox, Chrome, Safari alebo Operu.";
        }
        
        //alert(result);
        
        var bounds;
        
        if (features) {
            if(features.constructor != Array) {
                features = [features];
            }
            for(var i=0; i<features.length; ++i) {
                if (!bounds) {
                    bounds = features[i].geometry.getBounds();
                } else {
                    bounds.extend(features[i].geometry.getBounds());
                }
            }
            try {
                vectors.addFeatures(features);
                map.zoomToExtent(bounds);
                var plural = (features.length > 1) ? 's' : '';
                gpxStatus.innerHTML = features.length + ' feature' + plural + ' added'
            } catch (err) {
                gpxStatus.innerHTML = "Vyskytla sa neznáma chyba pri interpretácii XML.<br/>"+err;
            }
        } else {
            gpxStatus.innerHTML = 'Zlý formát súboru ' + type;
        }
    } else {
        gpxStatus.innerHTML = "chyba pri posielaní (skontroluj, či je korektný súbor GPX)";    
    }
    gpxResult.innerHTML = "";
    return true;
}

function initSavedHPtrack(){
    try {
        var elem = frames['tm_hiking_login'].document.getElementById('txtHPgpx');
        showHPtrack(elem);
    } catch (err) {
        
    }
}

function showHPtrack(elem){
    
    elem = typeof(elem) != 'undefined' ? elem : document.getElementById('txtHPgpx');
    
    try {
        var txtHPgpx = elem.innerHTML.split("&lt;").join("<").split("&gt;").join(">");
    } catch (err){
        
    }
    
    var type = "gpx";
    if (txtHPgpx){
        try {
            var features = formats['in'][type].read(txtHPgpx);
        } catch (err) {
            //alert("Prehliadač nepodporuje túto funkciu. Skús Firefox, Chrome, Safari alebo Operu.");
        }
        
        var bounds;
        if (features){
            if(features.constructor != Array) {
                features = [features];
            }
            for(var i=0; i<features.length; ++i) {
                if (!bounds) {
                    bounds = features[i].geometry.getBounds();
                } else {
                    bounds.extend(features[i].geometry.getBounds());
                }
            }
            hpTracks.destroyFeatures();
            hpTracks.addFeatures(features);
            map.zoomToExtent(bounds);   
        } else {
            //alert(err.description);
        }
    }
}


function toggleDialog(url){
    url = typeof(url) != 'undefined' ? url : "none";  

    var iFrameDialog = frames['tm_dialog'];
    var dialog = document.getElementById('ui_dialog');
    
    if (typeof(dialog.style.display) != 'undefined') {
        
        if (url == 'none' && dialog.style.display == 'block') {
            iFrameDialog.location = 'http://mapy.hiking.sk/help.php';
            dialog.style.display = 'none';    
            
        } else if (url != 'none') {
            
            //url = url.replace("\?","\\?");
            
            try {
                document.getElementById('ui_message').style.display='none'            
            } catch (err){}
            
            iFrameDialog.location = url;
            dialog.style.display = 'block';         
        }
    }
}

function toggleFullScreen(e){

    var bottomBar = document.getElementById('bottom_bar').style;
    var rightBar  = document.getElementById('right_bar').style;
    var menu      = document.getElementById('top_menu').style;
    var map1      = document.getElementById('map').style;
    var menu_text = document.getElementById('top_menu_toggle_fullscreen');
    
    if (fullscreen){
        bottomBar.display = "block";
        rightBar.display = "block";
        menu_text.innerHTML = '<img src="/images/icons/application_side_expand.png" class="menu_icon" /> Skry lišty';
        menu.right = 230;
        map1.height = "90%";
        map.pan(100,30);
        fullscreen = false;
        
    } else {
        map.pan(-100,-30);
        bottomBar.display = "none";
        rightBar.display = "none";
        menu_text.innerHTML = '<img src="/images/icons/application_side_contract.png" class="menu_icon" /> Ukáž lišty';
        menu.right = 30;
        map1.height = "99%";
        fullscreen = true;
    }
    resizeMap();
    return false;
}

function updateFormats() {
    var in_options = {
        'internalProjection': map.baseLayer.projection,
        'externalProjection': new OpenLayers.Projection("EPSG:4326")
    };   
    var out_options = {
        'internalProjection': map.baseLayer.projection,
        'externalProjection': new OpenLayers.Projection("EPSG:4326")
    };
    var gmlOptions = {
        featureType: "feature",
        featureNS: "http://example.com/feature"
    };
    var gmlOptionsIn = OpenLayers.Util.extend(
        OpenLayers.Util.extend({}, gmlOptions),
        in_options
    );
    var gmlOptionsOut = OpenLayers.Util.extend(
        OpenLayers.Util.extend({}, gmlOptions),
        out_options
    );
    formats = {
      'in': {
        wkt: new OpenLayers.Format.WKT(in_options),
        geojson: new OpenLayers.Format.GeoJSON(in_options),
        georss: new OpenLayers.Format.GeoRSS(in_options),
        gml2: new OpenLayers.Format.GML.v2(gmlOptionsIn),
        gml3: new OpenLayers.Format.GML.v3(gmlOptionsIn),
        kml: new OpenLayers.Format.KML(in_options),
        gpx: new OpenLayers.Format.GPX(in_options)
      }, 
      'out': {
        wkt: new OpenLayers.Format.WKT(out_options),
        geojson: new OpenLayers.Format.GeoJSON(out_options),
        georss: new OpenLayers.Format.GeoRSS(out_options),
        gml2: new OpenLayers.Format.GML.v2(gmlOptionsOut),
        gml3: new OpenLayers.Format.GML.v3(gmlOptionsOut),
        kml: new OpenLayers.Format.KML(out_options),
        gpx: new OpenLayers.Format.GPX(out_options)
      } 
    };
}

function _GETvar(q) {
    get_string = document.location.search.replace("[]","%5B%5D");
    q = q.replace("[]","%5B%5D");       
    return_value = '';

    var ii=0;
    do { //This loop is made to catch all instances of any get variable.
    name_index = get_string.indexOf(q + '=');
    
    if(name_index != -1)
      {
      get_string = get_string.substr(name_index + q.length + 1, get_string.length - name_index);
      
      end_of_value = get_string.indexOf('&');
      if(end_of_value != -1)                
        value = get_string.substr(0, end_of_value);                
      else                
        value = get_string;                
        
      if(return_value == '' || value == '')
         return_value += value;
      else
         return_value += ', ' + value;
      
      ii++;
      }
    } while(name_index != -1)
     
    //if (name == "st[]") alert("string: "+document.location.search+" found:"+ii+" q:"+q); 
    //Restores all the blank spaces.
    space = return_value.indexOf('+');
    while(space != -1)
      { 
      return_value = return_value.substr(0, space) + ' ' + 
      return_value.substr(space + 1, return_value.length);
                     
      space = return_value.indexOf('+');
      }
    
    return(return_value);        
    }

function toggleControl(element) {
    for(key in drawControls) {
        var control = drawControls[key];
        if(element.value == key && element.checked) {
            control.activate();
        } else {
            control.deactivate();
            if (key=="measure"){
                control.handlerOptions.persist="false";
                document.getElementById('measureOut').innerHTML = "";
            }
        }
    }
}



function toggleLayers(element){
    var zoom = map.getZoomForResolution(map.getResolution());
    switch(element.value){
    case "sat":
        if (element.checked && bGSat.getVisibility() == false){
            map.setBaseLayer(bGSat);
        } 
        break;
    case "topo":
        if (element.checked && bSHO.getVisibility() == false){
            if (zoom > 12){
                map.setBaseLayer(bSHO);
            } else {
                map.setBaseLayer(bGPhy);   
            }
        }
        break;
    case "tzt":
        if (element.checked && lTZT.getVisibility() == false){
            lTZT.setVisibility(1);
        } else {
            lTZT.setVisibility(0);
        }
        break;
    case "limba":
        if (element.checked && limba.getVisibility() == false){
            limba.setVisibility(1);
            map.pan(1,0);
        } else {
            limba.setVisibility(0);
        }
        break;
    case "chaty":
        if (element.checked && chaty.getVisibility() == false){
            chaty.setVisibility(1);
            map.pan(1,0);
        } else {
            chaty.setVisibility(0);
        }
        break;
    case "foto":
        if (element.checked && foto.getVisibility() == false){
            foto.setVisibility(1);
            map.pan(1,0);
        } else {
            foto.setVisibility(0);
        }
        break;
	case "hrady":
        if (element.checked && hrady.getVisibility() == false){
            hrady.setVisibility(1);
            map.pan(1,0);
        } else {
            hrady.setVisibility(0);
        }
        break;
    case "gc":
        if (element.checked && GC.getVisibility() == false){
            GC.setVisibility(1);
            map.pan(1,0);
        } else {
            GC.setVisibility(0);
        }
        break; 
    }    
}

function toggleRightBar(){
    var divContent = document.getElementById('right_bar_content');
    var divRightBar = document.getElementById('right_bar');
    var divCopyright = document.getElementById('copyright');
    var aSwitcher   = document.getElementById('toggleRightBarLink');
    if (divContent.style.display == "none"){
        divRightBar.style.width = "200";
        divContent.style.display = "block";
        divCopyright.style.display = "block";
        aSwitcher.innerHTML = "&gt;&gt; skryť panel";
    } else {
        divCopyright.style.display = "none";
        divContent.style.display = "none";
        divRightBar.style.width = "16";
        aSwitcher.innerHTML = "&lt;&lt;";
    }
}

function concatObject(obj) {
  str='';
  for(prop in obj)
  {
    str+=prop + " value :"+ obj[prop]+"\n";
  }
  return(str);
}
        
function dumpProps(obj, parent) {
   // Go through all the properties of the passed-in object 
   for (var i in obj) {
      // if a parent (2nd parameter) was passed in, then use that to 
      // build the message. Message includes i (the object's property name) 
      // then the object's property value on a new line 
      if (parent) { var msg = parent + "." + i + "\n" + obj[i]; } else { var msg = i + "\n" + obj[i]; }
      // Display the message. If the user clicks "OK", then continue. If they 
      // click "CANCEL" then quit this level of recursion 
      if (!confirm(msg)) { return; }
      // If this property (i) is an object, then recursively process the object 
      if (typeof obj[i] == "object") { 
         if (parent) { dumpProps(obj[i], parent + "." + i); } else { dumpProps(obj[i], i); }
      }
   }
}

var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{
			string: navigator.userAgent,
			subString: "Chrome",
			identity: "Chrome"
		},
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari",
			versionSearch: "Version"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};
BrowserDetect.init();
