// functions not tied to any api; can be used with OpenLayers, Google . . .

Utils = {
    imageLocation: "http://www.sysmaps.co.uk/bkg/",

    getQueryParams: function() {
        var qsParm = new Array();
        var query = window.location.search.substring(1);
        var parms = query.split('&');
        for (var i=0; i<parms.length; i++) {
          var pos = parms[i].indexOf('=');
          if (pos > 0) {
            var key = parms[i].substring(0,pos);
            var val = parms[i].substring(pos+1);
            qsParm[key] = val;
            }
        }
       return qsParm;
    },

    getPageName: function() {
        var pathName = window.location.pathname;
        var start = pathName.lastIndexOf('/')+1;
        var end = pathName.indexOf('.')
        return pathName.slice(start,end);
    },

    getPath: function() {
        var pathName = window.location.pathname;
        var end = pathName.lastIndexOf('/')+1;
        return pathName.slice(0,end);
    },

    latlongtoNews: function(lat, long) {
        var pos = Math.abs(lat);
        var dir = (lat>0 ? 'N' : 'S');
        var deg = Math.floor(pos);
        var min = Math.floor((pos-deg)*60);
        var sec = Math.floor((pos-deg-min/60)*3600);
        var ns = deg + '\u00B0' + min + "'" + sec + '"' + dir;
        var pos = Math.abs(long);
        var dir = (long>0 ? 'E' : 'W');
        var deg = Math.floor(pos);
        var min = Math.floor((pos-deg)*60);
        var sec = Math.floor((pos-deg-min/60)*3600);
        var ew = deg + '\u00B0' + min + "'" + sec + '"' + dir;
        return ns + ', ' + ew + ' (' + (Math.round(lat * 10000) / 10000) + ', ' + (Math.round(long * 10000) / 10000) + ')';
    },

    showPanel: function(panel) {
        document.getElementById(panel+'Panel').style.display = "";
    },
    hidePanel: function(panel) {
        document.getElementById(panel+'Panel').style.display = "none";
        return true;
    },

    getViewport: function() {
        var e = window, a = 'inner';
        if ( !( 'innerWidth' in window ) ) {
            a = 'client';
            e = document.documentElement || document.body;
        }
        return { width : e[ a+'Width' ] , height : e[ a+'Height' ] }
    },

    showTooltip: function(ttText, x, y) {
        var windowWidth = Utils.getViewport().width;
        o = document.getElementById('tooltip');
        o.innerHTML = ttText;
        if(o.offsetWidth) {
            ew = o.offsetWidth;
        } else if(o.clip.width) {
            ew = o.clip.width;
        }
        y = y + 16;
        x = x - (ew / 4);
        if (x < 2) {
            x = 2;
        } else if(x + ew > windowWidth) {
            x = windowWidth - ew - 4;
        }
        o.style.left = x + 'px';
        o.style.top = y + 'px';
        o.style.visibility = 'visible';
    },

    hideTooltip: function() {
        document.getElementById('tooltip').style.visibility = 'hidden';
    },

    gotoCoords: function() {
        var lat = document.getElementById("lat").value;
        var long = document.getElementById("long").value;
        Map.Markers.addMarker(long, lat);
    },

    jsCallify: function(func, text) {
        return '<span class="jscall" onclick="'+func+'">'+text+'</span>'
    }
}

StatusLog = {
    logDiv: null,
    msgs: {
        'init': 'Initialising map',
        'fetch': 'Fetching data',
        'mapsetup': 'Setting up map',
        'gdata': 'GData feed loading',
        'geoload': 'GeoJSON feed loading',
        'maploaded': 'Map loaded. '+Utils.jsCallify("StatusLog.logDiv.hide();return", "Close")
    },
    init: function(div) {
        this.logDiv = document.getElementById(div);
        this.logMsg('init');
    },
    logMsg: function(msg) {
        this.logDiv.innerHTML += this.msgs[msg]+'<br />';
    },
    endMsg: function() {
        this.logMsg('maploaded');
        setTimeout("StatusLog.logDiv.style.display='none'", 5000);
    }
}

WindowOpen = {
    win: null, // holds popup window object
    title: 'Route Details',
    statusBar: 'Links open in new tab/window',

    url: function(url) {
        if (!this.win)
            this.win = new Window('urlWindow', {className: 'popup', width: 500, destroyOnClose: true});
        this.win.setTitle(this.title);
        this.win.setURL(url);
        this.win.setStatusBar(this.statusBar);
        this.win.setZIndex(100);
        this.win.showCenter();
        this.win.toFront();
    },

    div: function(div) {
        if (!this.win)
            this.win = new Window('divWindow', {className: 'popup', width: 300, height: 200, destroyOnClose: true});
        else {
            var content = this.win.getContent();
            if (content.firstChild.getAttribute('id') != div) {
                content.firstChild.style.display = 'none';
                document.body.appendChild(content.firstChild);
            }
        }
        this.win.setTitle(this.title);
        this.win.setContent(div);
        this.win.setStatusBar(this.statusBar);
        this.win.setZIndex(100);
        this.win.showCenter();
        this.win.toFront();
    },

    html: function(html) {
        if (!this.win)
            this.win = new Window('htmlWindow', {className: 'popup', width: 400, height: 200, destroyOnClose: true});
        this.win.setTitle(this.title);
        this.win.setHTMLContent(html);
        this.win.setZIndex(100);
        this.win.showCenter();
        this.win.toFront();
    },

    help: function() {
        var helpWin = new Window('helpWindow', {className: 'popup', width: 500, destroyOnClose: true});
        helpWin.setTitle('Help');
        helpWin.setAjaxContent(ServerVars.serverPath+ServerVars.helpUrl, {method: 'get'});
//        helpWin.setContent('helpPanel');
        helpWin.setStatusBar(WindowOpen.statusBar);
        helpWin.setZIndex(100);
//        helpWin.setCloseCallback(function(){Utils.hidePanel('help');return true});
        helpWin.showCenter();
        helpWin.toFront();
    },

    search: function(gmaps) {
        var searchWin = new Window('searchWindow', {className: 'popup', width: 500, destroyOnClose: true});
        searchWin.setTitle('Search for Coordinates/Placenames');
		var url = 'http://www.sysmaps.co.uk/searchpanel.html';
		//var url = 'http://www.system.co.uk/searchpanel.html' + (gmaps ? '?gmaps=true' : '');
        //var url = ServerVars.serverPath+'/searchpanel.html' + (gmaps ? '?gmaps=true' : '');
        searchWin.setAjaxContent(url, {method: 'get'});
        searchWin.setStatusBar('');
        searchWin.setZIndex(100);
        searchWin.showCenter();
        searchWin.toFront();
    },

    palette: function() {
        var paletteWin = new Window('paletteWindow', {className: 'popup', width: 150, height: 200, destroyOnClose: true});
        paletteWin.setAjaxContent(ServerVars.serverPath+'/palette.html', {method: 'get'});
        paletteWin.setStatusBar('Pick a colour');
        paletteWin.setZIndex(100);
        paletteWin.showCenter();
        paletteWin.toFront();
    }
}

Feed = {
    worksheetCount: 0,

    createScript: function(id, url) {
        var old = document.getElementById(id);
        if (old != null) {
            old.parentNode.removeChild(old);
            delete old;
        }
        url = url.replace(/amp;/g,'');
        var script = document.createElement('script');
        script.id = id;
        script.type = 'text/javascript';
        script.charset = 'utf-8';
        script.src = url;
        document.getElementsByTagName("head")[0].appendChild(script);
    },

    GData: {
      findWorksheets: function(json) {
        Feed.worksheetCount += json.feed.entry.length-1;
        for (var i = 0; i < json.feed.entry.length; i++) {
            var entry = json.feed.entry[i];
            var feed = entry['title'].$t;
            var url = entry['link'][0].href + '?alt=json-in-script&callback=Feed.GData.add2Vectors';
            Feed.createScript(feed, url);
        }
      },

      add2Vectors: function(json) {
// POI json feed from Google spreadsheet with name, description, type, website, comments, latitude, longitude
// converted to GeoJson FeatureCollection and then added to vector layer
            StatusLog.logMsg('gdata');
            Map.Vectors.loadGeoJson(this.convert2GeoJson(json));
      },

      convert2GeoJson: function(json) {
        var features = [];
        var linestring = '';
        for (var i = 0; i < json.feed.entry.length; i++) {
            var entry = json.feed.entry[i];
            var props = {};
            for (var att in entry) { // only use spreadsheet fields (i.e. those starting 'gsx$')
                var ent = entry[att].$t;
                if (att.match('gsx')) {
                    att = att.replace('gsx$','');
                    if (att == 'latitude')
                        var latitude = parseFloat(ent);
                    else if (att == 'longitude')
                        var longitude = parseFloat(ent);
                    else if (att == 'linestring')
                        linestring = Map.Vectors.wkt2Geo(ent);
                    else
                        props[att] = ent;
                }
            }
            if (linestring != '') {
                features.push( { "type": "Feature", "properties": props, "geometry": linestring } );
                linestring = '';
            }
            else
                features.push( { "type": "Feature", "properties": props, "geometry": {"type": "Point", "coordinates": [longitude, latitude] } } );
        }
        return {"type": "FeatureCollection", "features": features};
      }
    },

    Json: {
      getPlaces: function() {
        var place = document.getElementById("place").value;
        var url = 'http://ws5.geonames.org/searchJSON?maxRows=10&isNameRequired=true&continentCode=eu&featureClass=P&style=full&callback=Feed.Json.showPlaces&q='+place;
        Feed.createScript('places', url);
      },

      showPlaces: function(feed) {
        if (feed == null) {
            alert('Nothing returned from geonames.org');
            return;
        }
        var geonames = feed.geonames;
        if (geonames.length == 0) {
            alert('No such place on geonames.org');
            return;
        }
        if (geonames.length == 1) {
            var lat = geonames[0].lat;
            var long = geonames[0].lng;
            Map.Markers.addMarker(long, lat);
        }
        else {
            var html = '';
            for (i=0;i< geonames.length;i++) {
                var geoname = geonames[i];
                var lat = geoname.lat;
                var long = geoname.lng;
                var fullName = geoname.name+', '+geoname.adminName1+', '+geoname.adminName2+', '+geoname.adminName3+', '+geoname.adminName4;
                html = html + Utils.jsCallify("Map.Markers.addMarker("+long+", "+lat+")", fullName)+'<br />';
            }
            document.getElementById('searchResults').innerHTML = html;
        }
      },

      getWikipedia: function(long, lat) {
        var url = 'http://ws5.geonames.org/findNearbyWikipediaJSON?callback=Feed.Json.showWikipedia&lat='+lat+'&lng='+long;
        Feed.createScript('wiki', url);
      },

      showWikipedia: function(feed) {
        if (typeof feed.geonames == 'undefined')
            var html = 'No nearby Wikipedia entries or service unavailable';
        else {
            var geonames = feed.geonames;
            if (geonames.length == 0) {
                alert('No Wikipedia entries');
                return;
            }
            var html = '';
            for (i=0;i< geonames.length;i++) {
                var geoname = geonames[i];
                html += '<b>'+geoname.title+'</b> ('+geoname.lat+', '+geoname.lng+': '+geoname.distance+'km away)';
                html += '<br />'+geoname.summary;
                html += '<br />'+Utils.jsCallify("Map.Markers.addMarker(" + geoname.lng + "," + geoname.lat + ")", "Show on map")+' | <a href="http://'+geoname.wikipediaUrl+'" target="_blank">View Wikipedia page</a><br />';
            }
        }
        document.getElementById('wikiResults').innerHTML = html;
      },

      getMetar: function(long, lat) {
        var url = 'http://ws5.geonames.org/findNearByWeatherJSON?callback=Feed.Json.showMetar&lat='+lat+'&lng='+long;
        Feed.createScript('metar', url);
      },

      showMetar: function(feed) {
        if (typeof feed.weatherObservation == 'undefined')
            var html = 'No nearby weather stations or report unavailable';
        else {
            var weather = feed.weatherObservation;
            var html = '<b>'+weather.stationName+'</b> ('+weather.ICAO+')';
            html += '<br />'+weather.lat+', '+weather.lng+'; altitude: '+weather.altitude;
            html += '<br />'+weather.datetime;
            html += '<br />'+weather.weatherCondition+'; '+weather.clouds+'; '+weather.temperature+'&deg;C; '+weather.hectoPascAltimeter+' hPa; humidity: '+weather.humidity+'%; wind: '+weather.windDirection+'&deg; @ '+weather.windSpeed+' knots';
        }
        document.getElementById('weatherResults').innerHTML = html;
      }
    }
}
