<!-- For automatic UTF-8 detection: [åäöÅÄÖ] -->

// EBubble
function EBubble(map,image,size,insize,inset,anchor,noCloseOnClick) {
    // parameters
    var that=this;
    this.map = map;
    this.image=image;
    this.size=size;
    this.insize=insize;
    this.inset=inset;
    this.anchor=anchor;
    this.noCloseOnClick=noCloseOnClick;
    // internal variables
    this.visible = false;
    // browser - specific variables
    this.ie = false;
    var agent = navigator.userAgent.toLowerCase();
    if ((agent.indexOf("msie") > -1) && (agent.indexOf("opera") < 1)){ this.ie = true} else {this.ie = false}

    this.div1 = document.createElement("div");
    this.div1.style.position = "absolute";
    this.div1.style.display="none";
    //document.body.appendChild(this.div1);
    document.getElementById("mapholder").appendChild(this.div1);

    if (this.ie && this.image.indexOf(".png")>-1) {
        var loader = "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+this.image+"', sizingMethod='scale');";
        this.div1.innerHTML = '<div style="height:' +this.size.height+ 'px; width:'+this.size.width+'px; ' +loader+ '" ></div>';
    } else {
        this.div1.innerHTML = '<img src="' + this.image + '" width="' + this.size.width +'" height="' + this.size.height +'">';
    }
    // === Close the bubble if the map moves ===
    GEvent.addListener(map, "dragstart", function() {
        that.hide();
    });
    GEvent.addListener(map, "moveend", function() {
        that.hide();
    });
    // === Listen for clicks and mousedowns ===
    GEvent.addDomListener(this.div1,"click", function() {
        if (!that.noCloseOnClick) that.hide();
        GEvent.trigger(that,"click");
    });
    GEvent.addDomListener(this.div1,"mousedown", function() {
        if (!that.noCloseOnClick) that.hide();
        GEvent.trigger(that,"click");
    });

    this.div2 = document.createElement("div");
    this.div1.appendChild(this.div2);
    this.div2.style.position = "absolute";
    this.div2.style.left = this.inset.x + "px";
    this.div2.style.top = this.inset.y + "px";
    this.div2.style.width = this.insize.width + "px";
    this.div2.style.height = this.insize.height + "px";
}

EBubble.prototype.openOnMap = function(point, html, offset) {
    this.offset = offset||new GPoint(0,0);
    this.point = point;

    //div2.style.backgroundColor = "#0000ff";
    this.div2.innerHTML = html;

    // pixel relative to map world
    var p = this.map.fromLatLngToDivPixel(point);

    // map world relative to map container
    var dragObject = this.map.getPane(G_MAP_MAP_PANE).parentNode;
    var x = p.x + parseInt(dragObject.style.left);
    var y = p.y + parseInt(dragObject.style.top);

    // map container relative to the page
    y += this.map.getContainer().offsetTop;
    x += this.map.getContainer().offsetLeft;

    // offset by the requested anchor position
    y -= this.anchor.y;
    x -= this.anchor.x;

    // offset by the specified offset position
    y -= offset.y;
    x -= offset.x;

    // Apply those values
    this.div1.style.left = x+"px";
    this.div1.style.top = y+"px";

    // make it visible
    this.show();
}

EBubble.prototype.openOnMarker = function(marker,html) {
    var vx = marker.getIcon().iconAnchor.x - marker.getIcon().infoWindowAnchor.x;
    var vy = marker.getIcon().iconAnchor.y - marker.getIcon().infoWindowAnchor.y;
    this.openOnMap(marker.getPoint(), html, new GPoint(vx,vy));
}

EBubble.prototype.show = function() {
    this.div1.style.display="";
    this.div2.style.display="";
    this.visible = true;
}

EBubble.prototype.hide = function() {
    this.div1.style.display="none";
    //this.div2.style.display="none";
    this.visible = false;
}

EBubble.prototype.isHidden = function() {
    return !this.visible;
}

EBubble.prototype.supportsHide = function() {
    return true;
}
;

// jQuery map functions
(function($) {
	$.fn.extend({
	/* jmap: function(settings)
	 * The constructor method
	 * Example: $().jmap();
	 */
	jmap: function(settings) {
		var version = "1.3.1";
		/* Default Settings*/
		var settings = jQuery.extend({
			provider: "google",		// can be "google" or "yahoo"
			maptype: "hybrid",		// can be "map", "sat" or "hybrid"
			center: [55.958858,-3.162302],	// G + Y
			zoom: 12,
			controlsize: "small",
			showtype: true,
			showoverview: true,
			dragging: true,
			scrollzoom: false,
			smoothzoom: true,
			clickmarker: false
		},settings);


		return this.each(function(){
					this.jMap = new GMap2(this);
					var jmap = this.jMap;
					switch(settings.maptype) {
						case "map":
							var loadmap = G_NORMAL_MAP;
							break;
						case "sat":
							var loadmap = G_SATELLITE_MAP;
							break;
						default:
							var loadmap = G_HYBRID_MAP;
							break;
					}
					jmap.setCenter(new GLatLng(settings.center[0],settings.center[1]),settings.zoom,loadmap);
					switch(settings.controlsize)
					{
						case "small":
							jmap.addControl(new GSmallMapControl());
							break;
						case "large":
							jmap.addControl(new GLargeMapControl());
							break;
						case "none":
							break;
						default:
							jmap.addControl(new GSmallMapControl());
					}
					if (settings.showtype == true){
						jmap.addControl(new GMapTypeControl());// Type of map Control
					}
					if (settings.showoverview == true){
						jmap.addControl(new GOverviewMapControl());//Overview Map
					}
					if (settings.scrollzoom == true) {
						/* Off by default */
						jmap.enableScrollWheelZoom();
					}
					if (settings.smoothzoom == true) {
						/* Off by default*/
						jmap.enableContinuousZoom();
					}
					if (settings.dragging == false) {
						/* On by default */
						jmap.disableDragging();
					}
					if (settings.clickmarker == true){
						GEvent.addListener(jmap, "dblclick", function(marker, point){
							if (marker) {
								jmap.removeOverlay(marker);
							} else {
								var marker = new GMarker(point);
								jmap.addOverlay(marker);
								GEvent.addListener(marker, 'click', function(){
									pointlocation = marker.getPoint();
									marker.openInfoWindowHtml("Latitude: " + pointlocation.lat() + "<br />Longitude: " + pointlocation.lng());
								})
							}
						});
					}
			/* On document unload, clean unload Google API*/
				jQuery(document).unload(function(){ GUnload(); });
		});
		},
	/* myMap: function()
	 * Returns a map object from the API, so it's available to the user
	 * Example: $().myMap().setCenter(...) for Google;
	 * Example: $().myMap().drawZoomAndCenter(...) for Yahoo;
	 */
	myMap: function() {
		return this[0].jMap;
	},
	/* custommarker: function()
	 * Creates a custom marker
	 * Example: $().customMarker(...);
	 */
	customMarker: function(iconLabel) {
	    var numIconImages = 100;
	    var iconWidth = 25;
	    var iconHeight = 27;

        // create custom marker icon
        var tinyIcon = new GIcon();
        tinyIcon.image = "/img/gmap-icons-orange/reco_bubble.png";
        tinyIcon.shadow = "/img/gmap-icons-orange/reco_bubble_shadow.png";
        tinyIcon.transparent = "/img/gmap-icons-orange/reco_bubble_transparent.png";
        if((iconLabel) && (iconLabel < numIconImages)){
            tinyIcon.styleClass = "gmarker"+Math.floor((iconLabel-1)/10)+" gm"+iconLabel%10;
            tinyIcon.label = {"url":"/img/gmap-icons-orange/reco_bubble_transparent.png", "anchor":new GPoint(0,0), "size":new GSize(iconWidth, iconHeight)};
        }
        tinyIcon.iconSize = new GSize(iconWidth, iconHeight);
        tinyIcon.imageMap = [0,0, 22,0, 22,20, 15,20, 11,24, 7,20, 0,20];
        tinyIcon.shadowSize = new GSize(32, 32);
        tinyIcon.iconAnchor = new GPoint(11, 24);
        tinyIcon.infoWindowAnchor = new GPoint(17, 1);
		return tinyIcon;
	},
	/* custommarkerfrontpage: function()
	 * Creates a custom marker
	 * Example: $().customMarkerFrontPage(...);
	 */
/*	customMarkerFrontPage: function(iconLabel) {
	    var numIconImages = 100;
	    var iconWidth = 35;
	    var iconHeight = 35;

        // create custom marker icon
        var tinyIcon = new GIcon();
        tinyIcon.image = "/img/gmap-icons/reco_bubble.png";
        tinyIcon.shadow = "/img/gmap-icons/reco_bubble_shadow.png";
        tinyIcon.transparent = "/img/gmap-icons/reco_bubble_transparent.png";
        if((iconLabel) && (iconLabel<numIconImages)){
            tinyIcon.label = {"url":"/img/gmap-icons/reco_bubble_"+iconLabel+".png", "anchor":new GPoint(0,0), "size":new GSize(iconWidth, iconHeight)};
        }
        tinyIcon.iconSize = new GSize(iconWidth, iconHeight);
        tinyIcon.imageMap = [11,0, 20,0, 27,5, 31,9, 32,12, 32,18, 28,24, 20,28, 17,33, 15,28, 5,23, 0,17, 0,8, 5,3];
        tinyIcon.shadowSize = new GSize(52, 35);
        tinyIcon.iconAnchor = new GPoint(17, 35);
        tinyIcon.infoWindowAnchor = new GPoint(17, 1);
		return tinyIcon;
	},*/
	/* activemarker: function()
	 * Creates an active marker
	 * Example: $().activeMarker(...);
	 */
	activeMarker: function() {
	    var iconWidth = 35;
	    var iconHeight = 35;

        var tinyIcon = new GIcon();
        tinyIcon.image = "/img/gmap-icons/reco_bubble.png";
        tinyIcon.shadow = "/img/gmap-icons/reco_bubble_shadow.png";
        tinyIcon.transparent = "/img/gmap-icons/reco_bubble_transparent.png";
        tinyIcon.iconSize = new GSize(iconWidth, iconHeight);
        tinyIcon.imageMap = [11,0, 20,0, 27,5, 31,9, 32,12, 32,18, 28,24, 20,28, 17,33, 15,28, 5,23, 0,17, 0,8, 5,3];
        tinyIcon.shadowSize = new GSize(52, 35);
        tinyIcon.iconAnchor = new GPoint(17, 35);
        tinyIcon.infoWindowAnchor = new GPoint(17, 1);
		return tinyIcon;
	},
	/* addPoint: function()
	 * Returns a marker to be overlayed on the Google map
	 * Example: $().addPoint(...);
	 */
	addPoint: function(latitude, longitude, myicon, html, isdraggable, removable, link, isActiveIcon, xOffset, yOffset, label) {
		var jmap = this[0].jMap;
		var point = new GLatLng(latitude, longitude);

        var markerOptions = { icon:myicon, zIndexProcess:activeIconOnTop };

        // create a custom infowindow
        var infoWindowXOffset = 0;
        infoWindowXOffset += xOffset;
        var infoWindowYOffset = 0;
        infoWindowYOffset += yOffset;
        bubble = new EBubble(jmap, "/img/info-window.png",new GSize(233,119), new GSize(217,103), new GPoint(8,8), new GPoint(infoWindowXOffset+250, infoWindowYOffset+2));

 		var marker = new GMarker(point, markerOptions);

        if(label == null){
        // events
  		if(isActiveIcon){
  		    marker.importance = 2;
  		    /*
            GEvent.addListener(marker, "mouseover", function() {
              bubble.openOnMarker(marker, html);
            });
            GEvent.addListener(marker, "mouseout", function() {
              bubble.hide();
            });
            */
        } else {
            marker.importance = 1;

            jQuery('#'+label).hover(
                    function(){bubble.openOnMarker(marker, html); marker.importance=3;},
                    function(){bubble.hide(); marker.importance=1;});


            GEvent.addListener(marker, "click", function() {
                window.location.href=link;
            });
            GEvent.addListener(marker, "mouseover", function() {
              bubble.openOnMarker(marker, html);/*
              // ugly hack for the front page. Remove this when redesignen the frontpage
              if(myicon.image == "/img/gmap-icons/reco_bubble.png"){
                marker.setImage("/img/gmap-icons/reco_bubble_info.png");
              }*/
            });
            GEvent.addListener(marker, "mouseout", function() {
              bubble.hide();
              /*// ugly hack for the front page. Remove this when redesignen the frontpage
              if(myicon.image == "/img/gmap-icons/reco_bubble.png"){
                marker.setImage("/img/gmap-icons/reco_bubble.png");
              }*/
            });
          }
        }
		return jmap.addOverlay(marker);
	},
	/* addPoly: function(poly)
	 * Takes an array of GLatLng points, converts it to a vector Polyline to display on the map
	 * Example: $().addPoly(...);
	 */
	addPoly: function (poly, colour, width, alpha) {
		var jmap = this[0].jMap;
		// Yahoo Maps
		if (jmap._mapType) {
			return	jmap.addOverlay(poly, colour, width, alpha);
		} else if (jmap.b.jMap) { // Google Maps
			return jmap.addOverlay(poly);
		}
	},
	/* addRss: function()
	 * Takes a KML file and renders it to the map.
	 * Example: $().addPoint(...);
	 */
	addRss: function (rssfile, callback) {
		var jmap = this[0].jMap;
		// Yahoo Maps
		if (jmap._mapType) {
			var geoXml = new YGeoRSS(rssfile);
			YEvent.Capture(jmap, EventsList.onEndGeoRSS, callback)
			return jmap.addOverlay(geoXml);
		} else if (jmap.b.jMap) {  // Google Maps
			var geoXml = new GGeoXml(rssfile, callback);
			return jmap.addOverlay(geoXml);
		}

	},
	searchAddress: function (address, settings, callback) {

		var settings = jQuery.extend({
			returntype: "map"	//Return as Map or a Object
		},settings);

		var jmap = this[0].jMap;
		if (jmap.b.jMap) {
			GGeocoder = new GClientGeocoder();
			GGeocoder.getLatLng(address, function(point){
				if (!point) {
					alert(address + " not found");
				} else {
					switch (settings.returntype) {
						case "object":
							var results = [];
							results[0] = point.y;
							results[1] = point.x;
							return callback(results);
							break;
						default:
							jmap.setCenter(point);
							var marker = new GMarker(point, {draggable: true});
							jmap.addOverlay(marker);
							var pointlocation = marker.getPoint();
							marker.openInfoWindowHtml("Latitude: " + pointlocation.lat() + "<br />Longitude: " + pointlocation.lng());
							GEvent.addListener(marker, "dragend", function(pointlocation){
								marker.openInfoWindowHtml("Latitude: " + pointlocation.lat() + "<br />Longitude: " + pointlocation.lng());
							});
							break;
					}
				}
			});
		} else {
			alert('Map Object Not Found!');
		}
	},
	searchDirections : function(from,to,panel) {
		var jmap = this[0].jMap;
		// Yahoo Maps
		if (jmap._mapType) {
			alert('Yahoo Maps Do Not Support Directions');
		} else if (jmap.b.jMap) { //Google Maps
			var dirpanel = document.getElementById(panel);
			search = new GDirections(jmap, dirpanel);
			search.load('from:' + from + ' to:' + to);
		}
	},
	mapAds : function (p,o) {
		var jmap = this[0].jMap;
		var o = jQuery.extend({
			maxAdsOnMap: 3,
			channel: "",
			minZoomLevel: 6
		},o);

		if (jmap._mapType) {
			alert('Yahoo Maps Do Not Support Map Ads');
		} else if (jmap.b.jMap) { //Google Maps
			var adsManager = new GAdsManager(jmap, p, o);
			adsManager.enable();
		}
	},
	showTraffic : function() {
		var jmap = this[0].jMap;
		jmap.addOverlay(new GTrafficOverlay());
	}
});
})(jQuery);

function activeIconOnTop (marker,b) {
    return GOverlay.getZIndex(marker.getPoint().lat()) + marker.importance*1000000;
}
;

// mapfunctions
function doDynZoom (jmap,mapData,defaultZoomLevel,doCenter,extraPoint) {
    var maximumZoomLevel = 16;
    var minimumZoomLevel = 11;
    //var bounds = new GLatLngBounds(jmap.myMap().getBounds().getSouthWest(), jmap.myMap().getBounds().getNorthEast());
    var bounds = new GLatLngBounds();
    if (extraPoint != null)
        bounds.extend(new GLatLng(extraPoint[0], extraPoint[1], false));
    for (var j=0; j < mapData.length; j++) {
        bounds.extend(new GLatLng(mapData[j][0], mapData[j][1], false));
    }
    var ourZoom = defaultZoomLevel; // default zoom level
    var dynamicZoom = jmap.myMap().getBoundsZoomLevel(bounds);
    if (dynamicZoom < ourZoom)
        ourZoom = dynamicZoom;
    if (ourZoom > maximumZoomLevel)
        ourZoom = maximumZoomLevel;
    if (doCenter && mapData.length > 0) {
        jmap.myMap().setCenter(bounds.getCenter());
    } else {
       ourZoom = defaultZoomLevel;
    }
    return ourZoom;
}
;
