﻿function GMapMarker(item) {
	var m = item.metadata();

	this.item = item;

	this.lat = m.lat;
	this.lng = m.lng;
	this.description = item.next().html();
	this.img = m.img ? m.img : '';
	this.zoom = m.zoom ? m.zoom : 15;
	this.marker = null;
	item.prepend('<span class="ui-icon ui-icon-image"/>');
}

(function($) {
	$.fn.gmap = function(options) {
		$.fn.gmap.defaults = {
			lat: 50.281601868071434,
			lng: 20.2919921875,
			zoom: 13,
			markers: null,
			type: G_NORMAL_MAP,
			followclick: false
		};
		this.map = null;
		var opts = $.extend($.fn.gmap.defaults, options);

		$("body:first").unload(GUnload);

		if (!GBrowserIsCompatible())
			throw "Browser is not compatible with gmaps";

		this.moveViewTo = function(lat, lng, zoom) {
			this.map.setCenter(new GLatLng(lat, lng), zoom);
		}

		//		return this.each(function(el) {
		$this = $(this);
		opts = $.extend({}, opts, $this.metadata());

		this.map = new GMap2($this[0]);
		var map = this.map;
		
		map.setCenter(new GLatLng(opts.lat, opts.lng), opts.zoom);
		map.setUIToDefault();
		map.disableScrollWheelZoom();
		if (opts.type != G_NORMAL_MAP) map.setMapType(opts.type);

		if (opts.markers != null) {
			var len = opts.markers.length;
			for (var i = 0; i < len; i++) {
				var spot = opts.markers[i];
				spot.marker = createMarker(map, spot, i);
				map.addOverlay(spot.marker);
				bindclick($this, map, spot);
			}
		}
		if (opts.followclick) {
			GEvent.addListener(map, "click", function(overlay, latlng) {
				map.openInfoWindowHtml(latlng, "lat: " + latlng.lat() + "<br/>lng: " + latlng.lng() + "<br/>zoom: " + map.getZoom());
			});
		}
		//		});
		return this;
		function bindclick(mapdiv, map, spot) {
			spot.item.click(function() {
				$.scrollTo(mapdiv, 1000);
				showBalloon(map, spot);
			});
		}

		function createMarker(map, spot, index) {
			var icon = new GIcon(G_DEFAULT_ICON);
			icon.infoWindowAnchor = new GPoint(9, 36);
			var point = new GLatLng(spot.lat, spot.lng);
			spot.marker = new GMarker(point, { icon: icon });

			var span = spot.item.find("span:first");
			if (spot.description == '') spot.description = span.html();

			GEvent.addListener(spot.marker, "click", function() {
				$.scrollTo($this, 1000);
				showBalloon(map, spot);
			});
			return spot.marker;
		}

		function showBalloon(map, spot) {
			map.setCenter(new GLatLng(spot.lat, spot.lng), spot.zoom);
			var desc = spot.description;
			if (spot.img != '')
				desc += "<br/><a href='" + spot.img + "' target='_blank'><img src='" + spot.img + "' alt='pic' class='kthumb'/></a>";
			spot.marker.openInfoWindowHtml(desc);
		}
	}
})(jQuery);