var ConnectorGraffitiSubmit = new Class({

	selectedTags : [],
	highlighted :false,
	map :false,
	pointList :false,
	poly :false,
	field :null,
	points : [],
	markers : [],
	cLocationInputFocus :false,

	initialize : function(mapContainer, lat, lng, flagEdit) {
		// setup flag edit
		if (typeof flagEdit == 'undefined') {
			flagEdit = false;
		}
		this.pointList = $('sg-pointList');
		this.field = $('sg-pointListString');

		// set location
		this.latitude = Number(lat);
		this.longitude = Number(lng);
		// setup map
		if ($(mapContainer)) {
			this.initMap(mapContainer);
		} else {
			// no map container
			alert('Please provide a valid container for the map!');
		}
		this.setupForm();
	},

	// TRACKING

	findMarkerIndex : function(m) {
		var index = -1;
		for ( var i = 0; i < this.markers.length; ++i) {
			if (this.markers[i] == m) {
				index = i;
				break;
			}
		}
		return index;
	},

	// TAGS

	saveTags : function() {
		if (this.selectedTags.length > 0) {
			$('cl_tag_ids').value = this.selectedTags.join('|')
					.toString();
		} else {
			$('cl_tag_ids').value = '';
		}
	},

	toggleTag : function(target) {
		var img = target.getFirst();
		var imgName = target.getProperty('title');
		var fileName = 'icon-' + imgName + '.png';
		var fileNameSelected = 'icon-' + imgName + '-select.png';
		var tag_id = target.id;
		if (tag_id.test('tag-')) {
			tag_id = Number(tag_id.substring(4).toInt());
		}
		if (target.hasClass('selected')) {
			target.removeClass('selected');
			if (img.getProperty('src').test(fileNameSelected)) {
				img.setProperty('src',
						'/images/places/icons/' + fileName);
				this.selectedTags.remove(tag_id);
			}
		} else {
			target.addClass('selected');
			if (img.getProperty('src').test(fileName)) {
				img.setProperty('src',
						'/images/places/icons/' + fileNameSelected);
				this.selectedTags.push(tag_id);
			}
		}
		this.saveTags();
	},

	setupForm : function() {
		var tagIds = $('cl_tag_ids').value.split('|');
		if (tagIds.length.toInt() > 0) {
			for ( var i = 0; i < tagIds.length; i++) {
				tagIds[i] = Number(tagIds[i].trim());
				if ($('tag-' + tagIds[i]))
					this.toggleTag($('tag-' + tagIds[i]));
			}
			this.selectedTags = tagIds;
		}
		$('post-item-message-form').addEvent('submit', function(event) {
			if (this.cLocationInputFocus) {
				new Event(event).stop();
				this.findLocation();
			}
		}.bind(this));

		var tags = $$('a.item-tag');
		for ( var i = 0; i < tags.length; i++) {
			tags[i].addEvent('click', function(event) {
				new Event(event).stop();
				var target = event.target || event.srcElement;
				this.toggleTag(target.parentNode);
			}.bind(this));
		} // end for

	},

	findLocation : function() {
		var val = $('cl_si_location_q').value;
		if (val && val.length > 2) {
			new Ajax("/findme/findLocation.php", {
				method :'post',
				data :'location_q=' + val,
				onComplete :this.findLocationResponse.bind(this),
				onFailure : function(response) {
				}
			}).request();
		}
	},

	findLocationResponse : function(response) {
		var location = Json.evaluate(response);
		if (location) {
			if (location.total > 0) {
				var locationData = location.data[0];
				this.latitude = Number(locationData.latitude);
				this.longitude = Number(locationData.longitude);
				var point = new GLatLng(this.latitude, this.longitude);
				this.map.panTo(point);
				this.addMarker(point);
			}
		}
	},

	updateMarker : function(marker) {
		var index = this.findMarkerIndex(marker);
		this.points[index] = marker.getPoint();
		this.pointList.options[index] = new Option('('
				+ this.points[index].lat() + ','
				+ this.points[index].lng() + ')', this.points[index]
				.lat()
				+ ',' + this.points[index].lng(), false, true);
		this.redrawLine();
	},

	addMarker : function(point) {

		var marker = this.createMarker(point, 'yellow' // the new point
														// is
														// automatically
														// highlighted
		);

		// Drag end update the marker position
		GEvent.addListener(marker, 'dragend', function(p) {
			this.updateMarker(marker);
		}.bind(this));

		// Click event to highlight item in list.
		GEvent.addListener(marker, 'mousedown', function(p) {
			this.highlight(this.findMarkerIndex(marker));
		}.bind(this));

		this.map.addOverlay(marker);
		this.markers.push(marker);

		var index = this.findMarkerIndex(marker);
		this.points[index] = point;

		this.pointList.options[index] = new Option('(' + point.lat()
				+ ',' + point.lng() + ')', point.lat() + ','
				+ point.lng(), false, true);

		this.highlight(index, false);

		this.redrawLine();

	},

	initMap : function(mapContainer) {
		if (GBrowserIsCompatible()) {
			this.map = new GMap2($(mapContainer));
			this.map.setCenter(new GLatLng(this.latitude,
					this.longitude), 14);
			this.map.addControl(new GSmallMapControl());
			this.map.addControl(new GMapTypeControl());

			// prepopulate
			this.addMarker(new GLatLng(this.latitude, this.longitude));

			GEvent.addListener(this.map, "click", function(overlay,
					point) {
				this.addMarker(point);
			}.bind(this));

			$('find-it-button').addEvent('click', function(event) {
				new Event(event).stop();
				this.findLocation();
			}.bind(this));

			$('remove-selected-button').addEvent('click',
					function(event) {
						new Event(event).stop();
						this.removeSelected();
					}.bind(this));

			$('remove-all-button').addEvent('click', function(event) {
				new Event(event).stop();
				this.removeAll();
			}.bind(this));

			$('find-it-button').addEvent('click', function(event) {
				new Event(event).stop();
				this.findLocation();
			}.bind(this));

			this.pointList.addEvent('dblclick', function(event) {
				new Event(event).stop();
				this.jumpToPoint();
			}.bind(this));

			this.pointList.addEvent('change', function(event) {
				new Event(event).stop();
				this.highlight(this.pointList.selectedIndex);
			}.bind(this));

		} else {
			alert('Your browser is not compatible with Google Maps.');
		} // end if
	},

	createIcon : function(color) {
		var f = new GIcon();
		f.image = "http://labs.google.com/ridefinder/images/mm_20_"
				+ color + ".png";
		f.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
		f.iconSize = new GSize(12, 20);
		f.shadowSize = new GSize(22, 20);
		f.iconAnchor = new GPoint(6, 20);
		f.infoWindowAnchor = new GPoint(6, 1);
		f.infoShadowAnchor = new GPoint(13, 13);
		return f;
	},

	createMarker : function(point, color) {
		newMarker = new GMarker(point, {
			icon :this.createIcon(color),
			draggable :true
		});
		return newMarker;
	},

	redrawLine : function() {

		if (this.poly) {
			this.map.removeOverlay(this.poly);
		}

		if (this.points.length > 1) {
			this.poly = new GPolyline(this.points, "#ff0000", 3);
			this.map.addOverlay(this.poly);
		}

		this.field.value = '';
		for (i = 0; i < this.points.length; i++) {
			this.field.value = this.field.value + ' '
					+ this.points[i].lng() + ',' + this.points[i].lat()
					+ ',0';
		}

	},

	// Move the map to the selected point in the point list.
	jumpToPoint : function() {
		if (this.pointList.selectedIndex >= 0) {
			var point = this.markers[this.pointList.selectedIndex]
					.getPoint();
			this.map.setCenter(point, this.map.getZoom());
		}
	},

	highlight : function(index, dontChange) {

		if (index < this.pointList.length) {
			this.pointList.selectedIndex = index;
		}

		// change the icon
	if (this.highlighted) {
		this.highlighted
				.setImage("http://labs.google.com/ridefinder/images/mm_20_green.png")
	}
	this.highlighted = this.markers[index];
	if (!dontChange) {
		this.highlighted
				.setImage("http://labs.google.com/ridefinder/images/mm_20_yellow.png")
	}
},

removeAll : function() {
	for ( var i = 0; i < this.markers.length; ++i) {
		this.map.removeOverlay(this.markers[i]);
	}

	while (this.pointList.options.length > 0) {
		this.pointList.remove(0);
	}
	this.markers = [];
	this.points = [];
	this.map.removeOverlay(this.poly);
	this.highlighted = false;
},

removeSelected : function() {
	if (this.points.length > 0) {
		var index = this.pointList.selectedIndex;

		if (index >= 0 && index < this.points.length) {
			this.points.splice(index, 1);

			if (this.highlighted == this.markers[index]) {
				this.highlighted = null;
			}

			this.map.removeOverlay(this.markers[index]);
			this.markers.splice(index, 1);
			this.pointList.remove(index);
		}

		if (this.points.length > 0) {
			if (index == 0) {
				index++;
			}
			this.highlight(index - 1);
		}

		this.redrawLine();
	}
}
});