/* A few simple functions to de-clutter index.html */

var lat=51.508;
var lon=-0.118;
var zoom=9;
 
var map; //complex object of type OpenLayers.Map
var selectFeatureControl;
var selectedFeature;
var popupFeature; //Feature described in the popup window
var g_airfield;
var g_notamtext;

/* Not used */
function onPopupClose(evt) {
    selectFeatureControl.unselect(selectedFeature);
}

function showNotamOverlay() {
    //if(!selectedFeature) return;
    document.getElementById('notamoverlay').style.visibility='visible';
    document.getElementById('notamoverlay').style.display='block';
    document.getElementById('notamoverlaytext').innerHTML = "Click <a href=\"javascript:hideNotamOverlay()\">here</a> to close this box\n" + g_notamtext;
    popupFeature = selectedFeature;
}

function hideNotamOverlay() {
    document.getElementById('notamoverlay').style.visibility='hidden';
    document.getElementById('notamoverlay').style.display='none';
    document.getElementById('notamoverlaytext').innerHTML = "";
    popupFeature = false;
}

function hideFeature() {
    popupFeature.style="display:none;";
    hideNotamOverlay();
}

function onFeatureSelect(evt) {
    var feature = evt.feature;
    selectedFeature = feature;
    if(feature) {
        g_notamtext = "<h2>Notam: " + feature.attributes.name + "</h2>" + feature.attributes.description;
        document.getElementById('notamtext').innerHTML = "<i>If this text disappears off the bottom of the screen, double click on the map and you can read it in a popup box</i>" + g_notamtext;
    }
}

function onFeatureUnselect(event) {
    document.getElementById('notamtext').innerHTML = "<i>If this text disappears off the bottom of the screen, double click on the map and you can read it in a popup box</i><h2>Notam: </h2>";
    //selectedFeature = false;
}

/*Click controller from openLayers documentation */
OpenLayers.Control.Click = OpenLayers.Class(OpenLayers.Control, {                
                defaultHandlerOptions: {
                    'single': true,
                    'double': false,
                    'pixelTolerance': 0,
                    'stopSingle': false,
                    'stopDouble': false
                },

                initialize: function(options) {
                    this.handlerOptions = OpenLayers.Util.extend(
                        {}, this.defaultHandlerOptions
                    );
                    OpenLayers.Control.prototype.initialize.apply(
                        this, arguments
                    ); 
                    this.handler = new OpenLayers.Handler.Click(
                        this, {
                            'click': this.onClick,
                            'dblclick': this.onDblclick 
                        }, this.handlerOptions
                    );
                }, 

                onClick: function(evt) {
                    showNotamOverlay();
                },

                onDblclick: function(evt) {  
                    showNotamOverlay();
                }   

            });


function resetMapCentre() {
        var lonLat = new OpenLayers.LonLat(lon, lat).transform(new OpenLayers.Projection("EPSG:4326"), map.getProjectionObject());
        map.setCenter (lonLat, zoom);
}

//Initialise the 'map' object
function init() {
 
    setStartPos(document.location.href); //Uses arguments in the url to centre the map
    map = new OpenLayers.Map ("map", {
        controls:[
            new OpenLayers.Control.Navigation(),
            new OpenLayers.Control.PanZoomBar(),
            new OpenLayers.Control.Attribution()],
          maxExtent: new OpenLayers.Bounds(-20037508.34,-20037508.34,20037508.34,20037508.34),
          maxResolution: 156543.0399,
          numZoomLevels: 12,
          units: 'm',
          projection: new OpenLayers.Projection("EPSG:900913"),
          displayProjection: new OpenLayers.Projection("EPSG:4326")
    } );
 
 
    // Define the map layer
    var newLayer = new OpenLayers.Layer.TMS("Flying Map",
               "http://map-tiles.s3.amazonaws.com/",
               {type: 'png', getURL: osm_getTileURL,
               displayOutsideMaxExtent: true,
      attribution: '<a href="http://www.openstreetmap.org/">OpenStreetMap</a>'}
               );
    map.addLayer(newLayer);
 
    var notamLayer = new OpenLayers.Layer.Vector("KML", {
        projection: map.displayProjection,
        strategies: [new OpenLayers.Strategy.Fixed()],
        protocol: new OpenLayers.Protocol.HTTP({
            url: "notams.kml",
            format: new OpenLayers.Format.KML({
                extractStyles: true,
                extractAttributes: true
            })
        })
    });

    map.addLayer(notamLayer);
    //Select notams automatically on mouse over
    selectFeatureControl = new OpenLayers.Control.SelectFeature(notamLayer,
          {onSelect: onFeatureSelect, onUnselect: onFeatureUnselect,
             hover: true, multi: false});
    notamLayer.events.on({ "featureselected": onFeatureSelect,
                           "featureunselected": onFeatureUnselect});

    //Prevent notam selector from grabbing mouse clicks (so can still drag)
    selectFeatureControl.handlers["feature"].stopDown =false;
    selectFeatureControl.handlers["feature"].stopUp = false;

    map.addControl(selectFeatureControl);
    selectFeatureControl.activate();

    var clickControl = new OpenLayers.Control.Click({
         handlerOptions: {"single":false, "double": true, "stopDouble": true}});
    map.addControl(clickControl);
    clickControl.activate();

    //Set centre and zoom to where we planned
    if( ! map.getCenter() ){
        resetMapCentre();
    }
}


/* Hide the top div */
function hideDiv() {
    document.getElementById('maxbutton').style.visibility='visible';
    document.getElementById('maxbutton').style.display='inline';
    document.getElementById('header_info').style.visibility='hidden';
    document.getElementById('header_info').style.display='none';
}

/* Show the top div */
function showDiv() {
    document.getElementById('header_info').style.visibility='visible';
    document.getElementById('header_info').style.display='block';
    document.getElementById('maxbutton').style.visibility='hidden';
    document.getElementById('maxbutton').style.display='none';
}

/* Get the url for an openstreetmap tile */
function osm_getTileURL(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 limit = Math.pow(2, z);

    if (y < 0 || y >= limit) {
        return OpenLayers.Util.getImagesLocation() + "404.png";
    } else {
  x = ((x % limit) + limit) % limit;
        return this.url + z + "/" + x + "/" + y + "." + this.type;
    }
}

/* Use the location= arguement to the url to set the start position of the
map. Either we have a lat/lon (straightforward), or a airfield which we
look up */
function setStartPos(url) {
    var a = url.split('?');
    if(a.length!=2) {
        return;
    }
    var a1 = a[1].split('=');
    if(a1.length!=2) return;
    if(a1[0]!="location") return;
    var argument = a1[1];
    var eargument = unescape(argument);
    setCentrePos(eargument);
}

function setCentrePos(pos) {
    var a2 = pos.split(',');
    if(a2.length==2 || a2.length==3) { //We have a lat/lon[/zoom] pair
        lat = parseFloat(a2[0]);
        lon = parseFloat(a2[1]);
        zoom = 10;
        if(a2.length==3) {
            zoom = parseInt(a2[2]);
        }
        return;
    }
    centreOnAirfield(pos);
    return;
}

function centreOnAirfieldHandler(request)
{
    if(request.status == 200) {
        var result = request.responseText;
        var a = result.split(',');
        if(result == "Not Found" || a.length!=2) {
            document.getElementById('error').innerHTML = "<p>" + g_airfield + " airfield not found. Use the form at the bottom of <a href=\"http://www.hollo.org/flying/maps/data.html\">this page</a> to send me latitude/longitude coordinates if you have them from your own gps (not from Pooleys etc. please - they're copyright), or use a latitude/longitude instead.";
            showDiv();
            return;
        }
        lat = parseFloat(a[0]);
        lon = parseFloat(a[1]);
        zoom = 10;
        resetMapCentre();
    }
}

function centreOnAirfield(airfield)
{
    g_airfield = airfield;
    var request = OpenLayers.Request.GET({
        url: "http://www.hollo.org/cgi-bin/find_airfield?location=" + airfield,
        callback: centreOnAirfieldHandler});
}

function findAirfield()
{
    airfield = document.getElementById('location').value;
    setCentrePos(airfield);
    resetMapCentre();
    hideDiv();
}

function findAirfieldUrl()
{
    airfield = document.getElementById('location').value;
    document.location.href = ("http://www.hollo.org/flying/maps/?location=" + escape(airfield));
}

