var geoFeedsPams = null;

function showGMap() {
	var tmp_map = new geoFeeds();
	tmp_map.start(geoFeedsPams);
}

function isArray(obj) {
	if($.browser.safari) { 
		if (obj instanceof Array)
			return true;
		else
			return false;
	}
	else {
		if (obj.constructor.toString().indexOf("Array()") > -1)
			return true;
		else
			return false;
	}
}

function eqArray(arg1, arg2) {
	if(!isArray(arg1) || !isArray(arg2))
		return false;
	else {
		if(arg1.length != arg2.length)
			return false;
		else {
			for(var i = 0; i < arg1.length; i++) {
				if(arg1[i] != arg2[i])
					return false;
			}
			return true;
		}
	}
}

function geoFeeds() {
	var page_id  = null;
	var post_id  = null;
	var center = null;
	var zoom = null;
	var width = null;
	var height = null;
	var api_url = null;
	var source = null;
	var scheme_label = null;
	var exclude = null;
	var feed_id = null;
	var tags = null;
	var items_nr = null;

	var map = null;
	var markers = null;
	var pan_handler = null;
	
	this.start = function(p) {
		try {
			page_id = p.page_id;
			post_id = p.post_id;
			center = p.center;
			zoom = p.zoom;
			width = p.width;
			height = p.height;
			api_url = p.api_url,
			source = p.source;
			scheme_label = p.scheme_label;
			exclude = p.exclude;
			feed_id = p.feed_id;
			tags = p.tags;
			items_nr = p.items_nr;
	
			$('#map_' + post_id).css('width', width + 'px');
			$('#map_' + post_id).css('height', height + 'px');
			map = new GMap2(document.getElementById('map_' + post_id));
			geocoder = new GClientGeocoder();
			map.addControl(new GMapTypeControl());
			map.addControl(new GSmallMapControl());	            
			map.setCenter(new GLatLng(center[0], center[1]), zoom);
			map.enableDoubleClickZoom();
			map.enableContinuousZoom();
			pan_handler = GEvent.bind(map, 'moveend', this, function() {
				startGetEntries();
			})
			
			getEntries();
		}
		catch(err) { alert('GeoFeeds.start: ' + err); }
	};
	
	function getEntries() {
		try {
			var texclude = exclude ? 'true' : 'false';
			$.getJSON(api_url + '?pageid=' + page_id
						+ '&feedCategory=' + source
						+ '&feed=' + feed_id
						+ '&tags=' + scheme_label + '|' + tags
						+ '&exclude=' + texclude
						+ '&offset=0'
						+ '&limit=' + items_nr
						+ '&SW=' + map.getBounds().getSouthWest().lat() + ',' + map.getBounds().getSouthWest().lng()
						+ '&NE=' + map.getBounds().getNorthEast().lat() + ',' + map.getBounds().getNorthEast().lng()
						+ '&showHidden=0'
						+ '&jsoncallback=?',
					function(resp) {
						if(resp.success == false) {
							alert('Error: (' + resp.error.code + '): ' + resp.error.text);
							return false;
						}
						else {
							collectPosts(resp.data);
							addMarkers();
						}
					}
				);
		}
		catch(err) { alert('GeoFeeds.getEntries: ' + err); }
	};
		
	function startGetEntries() {
		center = [map.getCenter().lat(), map.getCenter().lng()];
		zoom = map.getZoom();
		getEntries();
	};
	
	function addMarkers() {
		map.clearOverlays();
		for(var i = 0; i < markers.length; i ++) {
			eval('var point = new GLatLng(' + markers[i].coords[0] + ', ' + markers[i].coords[1] + ')');
			var dims = 24;
			if(markers[i].posts.length > 100)
				dims = 64;
			else if(markers[i].posts.length > 50)
				dims = 56;
			else if(markers[i].posts.length > 20)
				dims = 48;
			else if(markers[i].posts.length > 10)
				dims = 40;
			else if(markers[i].posts.length > 1)
				dims = 32;
			
			var mymarker = createMarker(point, writeInfo(i), dims);
			map.addOverlay(mymarker);
		}
	};
	
	function collectPosts(feed) {
		try {
			markers = new Array();
			for(var i = 0; i < feed.length; i++) {
				found = false;
				var tmpc = [feed[i].latitude, feed[i].longitude];
				var tmpf = {'title': feed[i].title, 'url': feed[i].url};
				for(var j = 0; j < markers.length; j++) {
					if(eqArray(markers[j].coords, tmpc)) {
						markers[j].posts.push(tmpf);
						found = true;
						break;
					}
				}
				if(!found) {
					var tmpp = new marker(tmpc);
					tmpp.posts.push(tmpf);
					markers.push(tmpp);
				}
			}
		}
		catch(err) { alert('collectPosts: ' + err); }
	};
	
	function createMarker(point, description, dims) {
		var icon = createMarkerIcon({
			'width': dims,
			'height': dims
		});
		var marker = new GMarker(point, icon);
		GEvent.addListener(marker, 'click', function() {
			GEvent.removeListener(pan_handler);
			marker.openInfoWindowHtml(description);
			setTimeout(function() {
				pan_handler = GEvent.bind(map, 'moveend', this, function() {
					startGetEntries();
				})
			}, 2000);
		});
		return marker;
	};

	function createMarkerIcon(opts) {
		var width = opts.width || 32;
		var height = opts.height || 32;
		var primaryColor = opts.primaryColor || "#FFFF00FF";
		var strokeColor = opts.strokeColor || "#FF8A00FF";
		var cornerColor = opts.cornerColor || "#FF0000FF";
		 
		var baseUrl = "http://chart.apis.google.com/chart?cht=mm";
		var iconUrl = baseUrl + "&chs=" + width + "x" + height + 
			"&chco=" + cornerColor.replace("#", "") + "," + primaryColor.replace("#", "") + "," + strokeColor.replace("#", "") + "&ext=.png";
		var icon = new GIcon(G_DEFAULT_ICON);
		icon.image = iconUrl;
		icon.iconSize = new GSize(width, height);
		icon.shadowSize = new GSize(Math.floor(width*1.6), height);
		icon.iconAnchor = new GPoint(width/2, height);
		icon.infoWindowAnchor = new GPoint(width/2, Math.floor(height/12));
		icon.printImage = iconUrl + "&chof=gif";
		icon.mozPrintImage = iconUrl + "&chf=bg,s,ECECD8" + "&chof=gif";
		var iconUrl = baseUrl + "&chs=" + width + "x" + height + 
		    "&chco=" + cornerColor.replace("#", "") + "," + primaryColor.replace("#", "") + "," + strokeColor.replace("#", "");
		icon.transparent = iconUrl + "&chf=a,s,ffffff11&ext=.png";

		icon.imageMap = [
			width/2, height,
			(7/16)*width, (5/8)*height,
			(5/16)*width, (7/16)*height,
			(7/32)*width, (5/16)*height,
			(5/16)*width, (1/8)*height,
			(1/2)*width, 0,
			(11/16)*width, (1/8)*height,
			(25/32)*width, (5/16)*height,
			(11/16)*width, (7/16)*height,
			(9/16)*width, (5/8)*height
		];
		for (var i = 0; i < icon.imageMap.length; i++) {
			icon.imageMap[i] = parseInt(icon.imageMap[i]);
		}

		return icon;
	};
	
	function marker(coords) {
		this.coords = coords;
		this.posts = new Array();
	};

	function writeInfo(i) {
		var info = '';
		info = '<b>' + markers[i].posts.length + ' post trovati:</b>';
		info += '<ol>';
		for(var j = 0; (j < markers[i].posts.length) && (j < 5); j++) {
			var post = markers[i].posts[j];
			info += '<li><a href="' + post.url + '" target="_blank" title="">' + post.title + '</a></li>'
		}
		info += '</ol>';
		if((j == 5) && (markers[i].posts.length > 5))
			info += '...e altri ' + (markers[i].posts.length - j) + ' post!';
		return info;
	};
	
}

