/**
 * $("google-map-canvas").googlemap({
 *     controls: false,
 *     labels: true,
 *     addresses: [
 *         "1 ABC St, NSW Australia",
 *         "2 XYZ St, NSW Australia"
 *     ]
 * });
 * 
 **/
  
(function($) {
		
	var current = null;    
    
	function Googlemap(root, conf) {
		// current instance
		var self = this;
		if (!current) {
			current = self;
		}
		
		// internal variables
		var map;
		var geo;
		var markers;
		var curZoom;
		
		var MapIconMainOrange = new GIcon({
			image: "images/map/main_blue.png",
			shadow: "images/map/main_shadow.png",
			iconSize: new GSize(25, 43),
			shadowSize: new GSize(25, 43),
			iconAnchor: new GPoint(12, 41),
			infoWindowAnchor: new GPoint(12, 20)
		});
		
		var MapIconMainRed = new GIcon({
			image: "images/map/main_red.png",
			shadow: "images/map/main_shadow.png",
			iconSize: new GSize(25, 43),
			shadowSize: new GSize(25, 43),
			iconAnchor: new GPoint(12, 41),
			infoWindowAnchor: new GPoint(12, 20)
		});
		
		var MapIconMainBlue = new GIcon({
			image: "images/map/main_blue.png",
			shadow: "images/map/main_shadow.png",
			iconSize: new GSize(25, 43),
			shadowSize: new GSize(25, 43),
			iconAnchor: new GPoint(12, 41),
			infoWindowAnchor: new GPoint(12, 20)
		});
		
		var MapIconBigOrange = new GIcon({
			image: "images/map/big_orange.png",
			shadow: "images/map/big_shadow.png",
			iconSize: new GSize(15, 20),
			shadowSize: new GSize(15, 20),
			iconAnchor: new GPoint(7, 19),
			infoWindowAnchor: new GPoint(7, 10)
		});
		
		var MapIconBigRed = new GIcon({
			image: "images/map/big_red.png",
			shadow: "images/map/big_shadow.png",
			iconSize: new GSize(15, 20),
			shadowSize: new GSize(15, 20),
			iconAnchor: new GPoint(7, 19),
			infoWindowAnchor: new GPoint(7, 10)
		});
		
		var MapIconBigBlue = new GIcon({
			image: "images/map/big_blue.png",
			shadow: "images/map/big_shadow.png",
			iconSize: new GSize(15, 20),
			shadowSize: new GSize(15, 20),
			iconAnchor: new GPoint(7, 19),
			infoWindowAnchor: new GPoint(7, 10)
		});
		
		var MapIconSmallOrange = new GIcon({
			image: "images/map/small_orange.png",
			shadow: "images/map/small_shadow.png",
			iconSize: new GSize(11, 12),
			shadowSize: new GSize(11, 12),
			iconAnchor: new GPoint(5, 6),
			infoWindowAnchor: new GPoint(5, 6)
		});
		
		var MapIconSmallRed = new GIcon({
			image: "images/map/small_red.png",
			shadow: "images/map/small_shadow.png",
			iconSize: new GSize(11, 12),
			shadowSize: new GSize(11, 12),
			iconAnchor: new GPoint(5, 6),
			infoWindowAnchor: new GPoint(5, 6)
		});

		var MapIconSmallBlue = new GIcon({
			image: "images/map/small_blue.png",
			shadow: "images/map/small_shadow.png",
			iconSize: new GSize(11, 12),
			shadowSize: new GSize(11, 12),
			iconAnchor: new GPoint(5, 6),
			infoWindowAnchor: new GPoint(5, 6)
		});

		// configuration
		var latitude    = conf.latitude;
		var longitude   = conf.longitude;
		var zoom        = conf.zoom;
		var iconType    = conf.iconType;
		var subjekt    	= conf.subjekt;
		var markerId		= conf.markerId;
		var markerTitle	= conf.markerTitle;
		var update			= conf.update;
		
		// methods
		$.extend(self, {
			// plugin specific
			getRoot: function() { return root; },
				
			// google maps specific
			getMap: function() { return map; },
			getGeo: function() { return geo; },
			getAddresses: function() { return addresses; },
			getMarkers: function() { return markers; },
			
			// api
			isBrowserCompatible: function() {
				
				if ($.isFunction(GBrowserIsCompatible)) return GBrowserIsCompatible();
					
				return false;
			},
			initialise: function() {
				
				if (self.isBrowserCompatible()) {

					var copyOSM = new GCopyrightCollection("<a href=\"http://www.openstreetmap.org/\">OpenStreetMap</a>");
					copyOSM.addCopyright(new GCopyright(1, new GLatLngBounds(new GLatLng(-90,-180), new GLatLng(90,180)), 0, " "));
					
					var tilesMapnik     = new GTileLayer(copyOSM, 1, 17, {tileUrlTemplate: 'http://tile.openstreetmap.org/{Z}/{X}/{Y}.png'});
					var tilesOsmarender = new GTileLayer(copyOSM, 1, 17, {tileUrlTemplate: 'http://tah.openstreetmap.org/Tiles/tile/{Z}/{X}/{Y}.png'});
					
					var mapMapnik     = new GMapType([tilesMapnik],     G_NORMAL_MAP.getProjection(), "Mapa 1");
					var mapOsmarender = new GMapType([tilesOsmarender], G_NORMAL_MAP.getProjection(), "Mapa 2");
					
					map         = map || new GMap2(document.getElementById($(root)[0].id), { mapTypes: [mapMapnik, mapOsmarender, G_SATELLITE_MAP] });
					geo         = geo || new GClientGeocoder();
					markers     = markers || new Array();
					curZoom 		= curZoom || zoom;
					
					map.addControl(new GLargeMapControl());
					map.addControl(new GMapTypeControl());
					
					if (update == true) {
						
						GEvent.addListener(map,"moveend", function(){ self.loadMarkers(); });
						
					} else {
						self.addMarker(longitude,latitude,iconType,markerId,markerTitle);
					}
					
					if (latitude > 0 && longitude > 0) map.setCenter(new GLatLng(latitude, longitude), zoom);
					
				}
			},

			showAddress: function(address) {
				
				geo = (geo == null) ? new GClientGeocoder() : geo;
				
				geo.getLatLng(
					address,
					function(point) {
						if (!point) {
							alert(address + " nije pronadjeno");
						} else {
							map.setCenter(point, 13);
							
							$("#loc_x").val(point.x);
							$("#loc_y").val(point.y);
							$("#loc_lev").val(map.getZoom());
							
							map.clearOverlays();
							map.addOverlay(new GMarker(point));
						}
					}
				);
			},
			
			loadMarkers: function() {
				
				var bounds = map.getBounds();
				
				var southWest = bounds.getSouthWest();
				var northEast = bounds.getNorthEast();
				
				//latitude: y /	longitude: x
				if ((map.getZoom() > 13 && curZoom <= 13) || (map.getZoom() <= 13 && curZoom > 13)) {
					markers = new Array();
				}
				curZoom = map.getZoom();

				$.ajax({
          type: "GET",
          dataType: 'json', 
					url: "mapLocations.php?marks=" + markers.join(),
					data: "subjekt=" + subjekt + "&x1=" + southWest.lng() + "&y1=" + southWest.lat() + "&x2=" + northEast.lng() + "&y2=" + northEast.lat(),
					scriptCharset: 'utf-8',
					success: function(data){
						
						if (markers.length == 0) map.clearOverlays();
						
						for (i=0; i<data.length; i++) {
						
							if (data[i].id > 0 && data[i].x > 0 && data[i].y > 0) {
								self.addMarker(data[i].x,data[i].y,data[i].type,data[i].id,data[i].title);
							}
						}
						
					},
					error: function(XMLHttpRequest, textStatus, errorThrown) {
						alert("Greska prilikom ucitavanja kordinata");
					}
				});
				
			},
			
			loadContent: function(marker,id) {

				$.ajax({
          type: "GET",
          dataType: 'json', 
					url: "mapLocations.php",
					data: "id=" + id,
					scriptCharset: 'utf-8',
					success: function(data){
						
						if (data.length > 0) {
							
							cont = data[0];
							
							html = '<div style="width:100px; height:75px; padding-right:10px; float:left;">';
							html += '<a href="index.php?lang=' + MainLang + '&sel=nekretnine&view=' + id + '" onclick="pageload(\'index.php?lang=' + MainLang + '&sel=nekretnine&view=' + id + '\');return false;">';
							html += cont.slika;
							html += '</a>';
							html += '</div>';
							html += '<div style="float:left; width:250px;">';
							html += '<a href="index.php?lang=' + MainLang + '&sel=nekretnine&view=' + id + '" onclick="pageload(\'index.php?lang=' + MainLang + '&sel=nekretnine&view=' + id + '\');return false;">' + cont.grad + '</a><br/>';
							html += '<b>' + cont.ulica + '</b><br />';
							html += '<b>Tip:</b> ' + cont.kat + '<br />';
							html += '<b>Subjekt:</b> ' + cont.sub + '<br />';
							html += '<br />';
							html += '<b>' + cont.cijena + '</b>';
							html += '</div>';
						
							marker.openInfoWindowHtml(html);
						}
					},
					error: function(XMLHttpRequest, textStatus, errorThrown) {
						marker.openInfoWindowHtml("Greska prilikom ucitavanja");
					}
				});
			},
			
			addMarker: function(x,y,type,mrkId,mrkTitle) {
				if (mrkId == null) mrkId = 0;
				if (mrkTitle == null) mrkTitle = "";
								
				var point = new GLatLng(y,x);
				
				if (type == "standard") {
					
					map.addOverlay(new GMarker(point));
					
					GEvent.addListener(map, "click", function(marker, point) {

						if (marker) {
							map.removeOverlay(marker);
			
							$("#loc_x").val("0");
							$("#loc_y").val("0");
							$("#loc_lev").val("0");
						} else {
							map.clearOverlays();
							map.addOverlay(new GMarker(point));
							
							$("#loc_x").val(point.x);
							$("#loc_y").val(point.y);
							$("#loc_lev").val(map.getZoom());
						}
					});
					
				} else {
					
					if (type == "red") {
						
						if (mrkId == markerId) {
							var marker = new GMarker(point,{icon:MapIconMainRed, title:mrkTitle});
						} else if (map.getZoom() > 13) {
							var marker = new GMarker(point,{icon:MapIconBigRed, title:mrkTitle});
						} else {
							var marker = new GMarker(point,{icon:MapIconSmallRed, title:mrkTitle});
						}
						
					} else if (type == "blue") {
						
						if (mrkId == markerId) {
							var marker = new GMarker(point,{icon:MapIconMainBlue, title:mrkTitle});
						} else if (map.getZoom() > 13) {
							var marker = new GMarker(point,{icon:MapIconBigBlue, title:mrkTitle});
						} else {
							var marker = new GMarker(point,{icon:MapIconSmallBlue, title:mrkTitle});
						}
						
					} else {
						
						if (mrkId == markerId) {
							var marker = new GMarker(point,{icon:MapIconMainOrange, title:mrkTitle});
						} else if (map.getZoom() > 13) {
							var marker = new GMarker(point,{icon:MapIconBigOrange, title:mrkTitle});
						} else {
							var marker = new GMarker(point,{icon:MapIconSmallOrange, title:mrkTitle});
						}
						
					}
					
					markers.push(mrkId);
					
					map.addOverlay(marker);
					
					GEvent.addListener(marker, "click", function() {
						self.loadContent(this,mrkId);
					});
			
				}
				
			}
			
		});//$.extend(self,
        
		function load() {
			self.initialise();
			return self;
		}
        
		load();
	}//function Googlemap(root, conf) {


	// jQuery plugin implementation
	jQuery.prototype.googlemap = function googlemap(conf) {
		// already constructed --> return API
		var api = this.eq(typeof conf == 'number' ? conf : 0).data("googlemap");
		if (api) { return api; }
        
		var opts = {
			latitude: 0,
			longitude: 0,
			zoom: 0,
			iconType: "",
			subjekt: 0,
			markerId: 0,
			markerTitle: "",
			update: false
		};
        
		$.extend(opts, conf);		
		this.each(function() {
			var el = new Googlemap($(this), opts);
			$(this).data("googlemap", el);	
		});
		
		return this;
	};
    
})(jQuery);


