﻿/*
    This script file includes objects and methods used by the
    external map. The map referenced by other websites that wants
    to display the Trafikkflyt.no map with RTMs.
*/
var ExternalMap = function(opts) {
    ///<summary>Constructor for the ExternalMap object</summary>
    ///<param name="opts">External Map Options object</param>
    this._init(opts);
    
    // Refresh map every 10 minutes.
    setTimeout(function() { GUnload(); var tmp = new ExternalMap(opts); }, 600000);
};

ExternalMap.prototype.map = null;
ExternalMap.prototype.mapDiv = null;
ExternalMap.prototype._centrePoint = null;
ExternalMap.prototype._areaCenterCoords = null;
ExternalMap.prototype._markerManager = null;
ExternalMap.prototype._rtmFeed = null;
ExternalMap.prototype._defaultZoomLevel = 4;
ExternalMap.prototype._defaultAreaZoomLevel = 7;
ExternalMap.prototype._containerSize = null;
ExternalMap.prototype._mapSize = null;
ExternalMap.prototype._mapControl = null;

ExternalMap.prototype._size = function(width, height) {
    ///<summary>Size object</summary>
    ///<param name="width">Width</param>
    ///<param name="height">Height</param>

    this.width = width;
    this.height = height;
}

ExternalMap.prototype.opts = {
    ///<summary>Object holding the map options</summary>
    width: null, // container width
    height: null, // container height
    areaName: null, // area name, used for the map's center position
    cityName: null, // city name, used for the map's center position, overriden by area name
    zoomLevel: null, // map's initial zoom level
    mapControl: null, // display/hide map control
    referrer: null // name of the referrer
}

ExternalMap.prototype._wheelevent = function(e) {
    ///<summary>Prevent page scrolling if the mouse-wheel is rolled when the pointer is above the map</summary>
    ///<param name="e">Event</param>
    if (!e) e = window.event;
    if (e.preventDefault) e.preventDefault();
    e.returnValue = false;
}

ExternalMap.prototype._setBaseIcon = function() {
    ///<summary>
    /// Method used to set the base icon. The icon used for the overlaymarkers,
    /// if an icon-style is not found in the KML-feed.
    /// NOTE: The size-setting also affects the icons read from the KML-feed.
    ///</summary>
    var icon = new GIcon();
    icon.iconSize = new GSize(20, 20);
    icon.iconAnchor = new GPoint(6, 20);
    icon.infoWindowAnchor = new GPoint(5, 1);
    return icon;
},

ExternalMap.prototype._setMapCenter = function(point, zoomLevel) {
    ///<summary>
    /// Sets the center of the map to the specified point (lat/lng) at
    /// the specified zoom level.
    ///</summary>
    ///<param name="point">Lat/Lng</param>
    ///<param name="zoomLevel">Zoom level</param>
    this.map.setCenter(point, zoomLevel);
}

ExternalMap.prototype._addRTMFeed = function() {
    ///<summary>Adds the RTM-markers to the map</summary>
    var _self = this;

    this.map.savePosition();

    this._rtmFeed = new EGeoXml('rtmFeed', this.map, '/kml/feeds/roadmessages.ashx', {
        baseicon: _self._setBaseIcon(),
        icontype: 'style',
        noshadow: 'true',
        createCustomMarker: function(point, name, description, style, icon, id) {
            var marker = new GMarker(point, { icon: icon, title: name });
            GEvent.addListener(marker, 'click', function() {
                var params = Base64.encode('p=' + marker.getLatLng().lat() + ',' + marker.getLatLng().lng() + '&c=' + _self.opts.referrer + '&s=extMap');

                var content = name + '<br/>';
                content += '<a href="http://www.trafikkflyt.no/default.aspx?';
                content += params + '&m=map';
                content += '" target="_blank">Les meldingen på Trafikkflyt.no</a>';

                marker.openExtInfoWindow(_self.map, 'rtm_window', content);
                Event.observe($('rtm_window_contents'), 'click', function() {
                    _self.map.closeExtInfoWindow();
                });
            });
            _self.map.addOverlay(marker);
        }
    });

    this._markerManager = new GMarkerManager(this.map);
    GEvent.addListener(this._rtmFeed, 'parsed', function() {
        _self.map.returnToSavedPosition();
    });

    this._rtmFeed.parse();
}

ExternalMap.prototype._addMapListeners = function(obj) {
    ///<summary>Method used to listeners to the map object.</summary>
    ///<param name="obj">External map object</param>
    GEvent.addDomListener(obj.mapDiv, 'DOMMouseScroll', this._wheelevent);
    this.mapDiv.onmousewheel = this._wheelevent;
}

ExternalMap.prototype._setMapAndContainerSize = function() {
    ///<summary>Sets the map and container sizes</summary>

    $('mapContainer').style.width = this._containerSize.width + 'px';
    $('mapContainer').style.height = this._containerSize.height + 'px';

    this.mapDiv = $('map');
    this.mapDiv.style.width = this._mapSize.width + 'px';
    this.mapDiv.style.height = this._mapSize.height + 'px';
}

ExternalMap.prototype._coordsToGLatLng = function(obj) {
    ///<summary>Converts a coordinate object to GLatLng.</summary>
    ///<param name="obj">Coordinate object</param>
    ///<returns>GLatLng</returns>
    return new GLatLng(obj.lat, obj.lng);
}

ExternalMap.prototype._getOptions = function(opts) {
    ///<summary>Gets and sets the different options for this object and it's relatives.</summary>
    ///<param name="opts">Object holding the options</param>

    this.opts = opts || {};
    this._defaultZoomLevel = this.opts.zoomLevel || 4;
    this._mapControl = this.opts.mapControl == false ? false : true;

    var cWidth;
    if (!this._mapControl) cWidth = this.opts.width < 260 ? 260 : this.opts.width || 260; // Min size when control is hiden.
    else cWidth = this.opts.width < 300 ? 300 : this.opts.width || 300; // Min size when control is hiden.

    var cHeight = this.opts.height < 303 ? 303 : this.opts.height || 303;
    var mWidth = cWidth;
    var mHeight = this.opts.height - 53 < 250 ? 250 : this.opts.height - 53 || 250;

    this._containerSize = new this._size(cWidth, cHeight);
    this._mapSize = new this._size(mWidth, mHeight);
    this._setMapAndContainerSize();

    var geo = new GeoLocation();
    geo.init();

    if ((this.opts.areaName != null) && (this.opts.areaName != '')) {
        this._centrePoint = this._coordsToGLatLng(geo.findAreaLatLng(this.opts.areaName));
    } else if (this.opts.areaName == null) {
        if ((this.opts.cityName != null) && (this.opts.cityName != '')) {
            this._centrePoint = this._coordsToGLatLng(geo.findCityLatLng(this.opts.cityName));
        } else {
            this._centrePoint = new GLatLng(geo.coords[0].lattitude, geo.coords[0].longitude);
        }
    }
}

ExternalMap.prototype._init = function(opts) {
    ///<summary>Method used to initialize the map</summary>

    this._getOptions(opts);
    this.map = new GMap2(this.mapDiv);
    this.map.enableScrollWheelZoom();
    this._addMapListeners(this);
    this._setMapCenter(this._centrePoint, this._defaultZoomLevel);

    if (this._mapControl) this.map.addControl(new GSmallMapControl());

    this._addRTMFeed();
}


var Base64 = {

    // private property
    _keyStr: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",

    // public method for encoding
    encode: function(input) {
        var output = "";
        var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
        var i = 0;

        input = Base64._utf8_encode(input);

        while (i < input.length) {

            chr1 = input.charCodeAt(i++);
            chr2 = input.charCodeAt(i++);
            chr3 = input.charCodeAt(i++);

            enc1 = chr1 >> 2;
            enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
            enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
            enc4 = chr3 & 63;

            if (isNaN(chr2)) {
                enc3 = enc4 = 64;
            } else if (isNaN(chr3)) {
                enc4 = 64;
            }

            output = output +
            this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
            this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);

        }

        return output;
    },

    // public method for decoding
    decode: function(input) {
        var output = "";
        var chr1, chr2, chr3;
        var enc1, enc2, enc3, enc4;
        var i = 0;

        input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

        while (i < input.length) {

            enc1 = this._keyStr.indexOf(input.charAt(i++));
            enc2 = this._keyStr.indexOf(input.charAt(i++));
            enc3 = this._keyStr.indexOf(input.charAt(i++));
            enc4 = this._keyStr.indexOf(input.charAt(i++));

            chr1 = (enc1 << 2) | (enc2 >> 4);
            chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
            chr3 = ((enc3 & 3) << 6) | enc4;

            output = output + String.fromCharCode(chr1);

            if (enc3 != 64) {
                output = output + String.fromCharCode(chr2);
            }
            if (enc4 != 64) {
                output = output + String.fromCharCode(chr3);
            }

        }

        output = Base64._utf8_decode(output);

        return output;

    },

    // private method for UTF-8 encoding
    _utf8_encode: function(string) {
        string = string.replace(/\r\n/g, "\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if ((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
    },

    // private method for UTF-8 decoding
    _utf8_decode: function(utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;

        while (i < utftext.length) {

            c = utftext.charCodeAt(i);

            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if ((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i + 1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i + 1);
                c3 = utftext.charCodeAt(i + 2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }

        }

        return string;
    }

}