// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

var page;

var Page = Class.create({
	initialize: function(id)
	{
		this.id = id;
	},
	
	path: function()
	{
		return "/pages/" + this.id;
	}
})

function testp(ps)
{
	p = new Ajax.Request('http://127.0.0.1:3000/pages/10', {asynchronous:true, evalScripts:true, method:'put', parameters: ps});
}

function removeAttachment(title)
{
	$$(".attachment-form #attachment_title").each(function (e){
		if (e.value == title)
		{
			Effect.BlindUp(e.parentNode.parentNode.parentNode);
		}
	});
}

var map;
var markers;

var activePath;
var opaths = [];
var draws = [];

var points = $H();
var paths = $H();

var pathCount = 0;

var onPoints = true;

var gicon, bicon;


function loaded()
{
	if ($("map"))
	{
map = new GMap2($("map"));
map.setCenter(new GLatLng(49.881141, -97.148666), 11);

if ($("points"))
{
GEvent.addListener(map, "click", mapClicked);
}

		map.addControl(new GLargeMapControl());

	markers = [];

gicon = new GIcon();
gicon.image = "http://biketothefuture.org/images/mm_20_green.png";
gicon.iconSize = new GSize(12, 20);
gicon.iconAnchor = new GPoint(6, 20);
gicon.infoWindowAnchor = new GPoint(5, 1);

bicon = new GIcon();
bicon.image = "http://biketothefuture.org/images/mm_20_blue.png";
bicon.iconSize = new GSize(12, 20);
bicon.iconAnchor = new GPoint(6, 20);
bicon.infoWindowAnchor = new GPoint(5, 1);
}
}


Event.observe(window, "load", loaded);


var geoCount = 0;

function newPoint()
{
	i = new Insertion.Bottom("points", "<div id='point_" + geoCount + "'><input type='radio'/><input name='geos[" + geoCount + "][lat]'/></div>")
	
	geoCount++;
}

function newPath(id)
{
	if (!id)
	{
		id = "n" + pathCount;
	}
	else
	{
		id = id + "";
	}
	
	unhighlight("path");
	unhighlight("points");
	activePath = id;
	i = new Insertion.Bottom("paths", "<div class='path highlighted' id='path_" + id + "'<h3>path</h3><a href='#' onclick='editPath(\'" + id + "\')>edit me!</a><div>" + labelledField("path", "title", "", ["paths",id]) + labelledField("path", "description", "", ["paths",id]) + "</div></div>");
	onPoints = false;
	
	opaths[id] = [];
	
	paths[id] = new Path(id);
	
	pathCount++;
}

function unhighlight(className)
{
	document.getElementsByClassName(className).each(function(p) { p.removeClassName("highlighted"); });
}

function editPath(path)
{
	activePath = path;
	onPoints = false;
	unhighlight("path");
	$("path_" + path).addClassName("highlighted");
}

function addPoints()
{
	onPoints = true;
	unhighlight("path");
	$("points").addClassName("highlighted");
	
	paths.values().each(function(path) { path.deactivate(); });
}

function mapClicked(overlay, point)
{
	if (point)
	{
	var marker; 
	
	if (onPoints)
	{
		addPoint(point.lat(), point.lng());
	}
	else
	{
		marker = addPoint(point.lat(), point.lng(), null, true);
		marker.path = activePath;
	}
}
}

function addPoint(lat, lng, id, pathPoint)
{
	var pid = id ? id : "n" + geoCount;
	
	if (pathPoint)
	{
		i = new Insertion.Bottom("path_" + activePath, "<div id='point_" + pid + "'>" + field("point", "lat", lat, ["paths",activePath, "points", pid], true) + " " + field("point", "lng", lng, ["paths",activePath, "points", pid], true) + "</div>");
	}
	else
	{
		i = new Insertion.Bottom("points", "<div id='point_" + pid + "'>" + labelledField("point", "title", "", ["points", pid]) + " " + labelledField("point", "description", "", ["points", pid]) + " " + field("point", "lat", lat, ["points", pid], true) + " " + field("point", "lng", lng, ["points", pid], true));
	}
	
	var marker = new GMarker(new GLatLng(lat, lng), {draggable: true, bouncy: true, icon: (pathPoint ? gicon : bicon)});
	map.addOverlay(marker);
	
	var point = new Point(lat, lng, pid, marker);
	points[pid] = point;
	
	markers[pid] = marker;
	
	marker.key = pid;
	
	if (pathPoint)
	{
		marker.path = activePath;
		paths[activePath].add(point);
	}
	
		geoCount++;
	
	return marker;
}

var activeMarker;

function labelledField(type, attribute, value, prefixes)
{
	return "<label>" + attribute + "</label> " + field(type, attribute, value, prefixes, false);
}

function field(type, attribute, value, prefixes, disabled)
{
	var np = [];
	
	prefixes = $A(prefixes);
	
	prefixes.each(function(p) {
			np.push(p);
	});
	
	np.push(attribute);
		
	return "<input id=\"" + type + "_" + prefixes.last() + "_" + attribute + "\" class=\"" + attribute + "\" name=\"" + fieldName(np) + "\" value=\"" + value + "\"" + (disabled ? " disabled=\"true\"" : "") + "/>";
}

function fieldName(prefixes)
{
	var p = "";
	
	prefixes = $A(prefixes);
	
			prefixes.each(function (prefix) {
				p += "[" + prefix + "]";
			});
	return "geos" + p;
}

function markerID(pid)
{
	return "point_" + pid;
}

function revert()
{
	reversion($("version").innerHTML*1 - 1);
}

function devert()
{
	reversion($("version").innerHTML*1 + 1);
}

function reversion(v)
{
	if (v <= $("count").innerHTML && v > 0)
	{
		r = new Ajax.Request(window.location.pathname, {asynchronous: true, method: 'get', parameters: 'field=page[content]&version=' + v, onSuccess: function() { $("version").innerHTML = v; $("resave").show();}})
	}
}

function increment()
{
	count = $("count").innerHTML*1;
	$("version").innerHTML = count + 1;
	$("count").innerHTML = count + 1;
}

function resave()
{
	r = new Ajax.Request(window.location.pathname, {method: 'put', parameters: 'version=' + $("version").innerHTML});
}

function enable(selector)
{
	document.getElementsByClassName(selector).each(function (e) {
		e.enable();
	});
}

function disable(selector)
{
	document.getElementsByClassName(selector).each(function (e) {
		e.disable();
	});
}

function submitGeos()
{
	enable("lat");
	enable("lng");
	document.forms.geos.submit();
	disable("lat");
	disable("lng");
}

function addMarker(lat, lng, title)
{
	marker = new GMarker(new GLatLng(lat, lng), {icon: bicon});
	markers.push(marker);
	map.addOverlay(marker);
	
	if (title)
	{
		GEvent.addListener(marker, "click", function() {
			marker.openInfoWindowHtml("<strong>" + title + "</strong>");
		});
	}
	
	return marker;
}

function addPath(points)
{
	draw = new GPolyline(points);
	map.addOverlay(draw);
	draws.push(draw);
}

function recentre()
{
	var init;
	
	if (points.values().last())
	{
		init = points.values().last();
	}
	else
	{
		// Why is this map even showing?
		return;
	}
	
	b = new GLatLngBounds(init.latlng());
	
	points.values().each(function(m){ b.extend(m.latlng());});
	
	map.setCenter(b.getCenter(), map.getBoundsZoomLevel(b));
}

var Point = Class.create({
	initialize: function(lat, lng, key, marker, stat) {
		this.key = key;
		this.marker = marker;
		this.isNew = key[0] == "n";

		this.element = $("point_" + key);
		this.title = $("point_" + key + "_title");
		this.description = $("point_" + key + "_description");
		this.latE = $("point_" + key + "_lat");
		this.lngE = $("point_" + key + "_lng");
		
		this.active = false;
	
	if (marker)
	{
		if (stat)
		{
			var umthis = this;
			GEvent.addListener(marker, "click", function() { umthis.activate()} );
			GEvent.addListener(marker, "mouseover", function() { umthis.activate()} );
			GEvent.addListener(marker, "mouseout", function() { umthis.deactivate()} );
		}
		else
		{
	
	marker.point = this;
	
	GEvent.addListener(marker, "dragend", function() {
		var point = marker.point;
		
		point.setLat(marker.getLatLng().lat());
		point.setLng(marker.getLatLng().lng());
		
		if (point.path)
		{
			point.path.redraw();
		}
	});
	
	GEvent.addListener(marker, "click", function() {
		var point = marker.point;
		marker.openInfoWindow(point.popupContent());
		new Form.Element.Observer("popup-title", 0.15, function() { this.element.point.formUpdated(); });
		new Form.Element.Observer("popup-description", 0.15, function() { this.element.point.formUpdated(); });
	});
	
	}
	}
	
	if (!this.latE && !this.lngE)
	{
		// Fake fields for values due to lack of foresight and laziness!
		this.latE = new Object();
		this.latE.value = lat;
		this.lngE = new Object();
		this.lngE.value = lng;
	}

		if (this.element)
		{
			var umthis = this;
			Event.observe(this.element, "mouseover", function () { umthis.activate() });
			Event.observe(this.element, "mouseout", function () { umthis.deactivate() });
		}

	},
	
	lat: function() { return this.latE.value; },
	lng: function() { return this.lngE.value; },
	latlng: function() { return new GLatLng(this.latE.value, this.lngE.value); },
	setLat: function(lat) { this.latE.value = lat },
	setLng: function(lng) { this.lngE.value = lng },
	
	popupContent: function()
	{
		var content = new Element("div", {id: "popup-content"});
		
		var el, ch;
		
		el = new Element("form", {id: "popup-form"});
		
		ch = new Element("label");
		ch.innerHTML = this.path ? "path title" : "title";
		el.appendChild(ch);
		
		ch = new Element("input", {id: "popup-title"});
		ch.point = this;
		ch.value = this.path ? this.path.title.value : this.title.value;
		el.appendChild(ch);
		
			ch = new Element("label");
			ch.innerHTML = this.path ? "path description" : "description";
			el.appendChild(ch);
			
			ch = new Element("textarea", {id: "popup-description"});
			ch.point = this;
			ch.value = this.path ? this.path.description.value : this.description.value;
			el.appendChild(ch);
		
		content.appendChild(el);

		el = new Element("br");
		content.appendChild(el);
		
		el = new Element("a", {href: "#", onclick: "points['" + this.key + "'].remove();return false;"});
		el.innerHTML = "- remove this point";
		content.appendChild(el);
		
		if (this.path)
		{
			el = new Element("br");
			content.appendChild(el);
			
			el = new Element("a", {href: "#", onclick: "paths['" + this.path.key + "'].remove();return false;"});
			el.innerHTML = "- remove entire path";
			content.appendChild(el);
			
			if (!this.path.active)
			{
				el = new Element("br");
				content.appendChild(el);
				
				el = new Element("a", {href: "#", onclick: "paths['" + this.path.key + "'].activate();return false;"});
				el.innerHTML = "+ add to the end of this path";
				content.appendChild(el);
			}
		}
		
		return content;
	},
	
	formUpdated: function()
	{
		if (this.path)
		{
			this.path.title.value = $F("popup-title");
			this.path.description.value = $F("popup-description");
		}
		else
		{
			this.title.value = $F("popup-title");
			this.description.value = $F("popup-description");
		}
	},
	
	remove: function()
	{
		if (confirm("You realllly want to remove this point?"))
		{
			this.element.remove();
			//new Effect.BlindUp(this.element, {afterFinish: function() { 
			//	console.log("it's up!" + this.element)}});
			
			if (!this.isNew)
			{
				new Ajax.Request(page.path() + "/geos/" + this.key, {method: "delete"});
			}
			else
			{
				this.removed();
			}
		}
	},
	
	removed: function()
	{
		map.removeOverlay(this.marker);
		
		if (this.path)
		{
			this.path.remove(this);
			
			if (this.path.inNew)
			{
				$("flash").innerHTML = "The point will be removed from the path upon saving.";
				new Effect.Highlight("flash");
			}
		}
		
		points = points.without(this);
	},

	activate: function()
	{
		if (!this.active)
		{
			points.values().each(function(p) { p.deactivate(); });

			this.active = true;

			// Undocumented, might break!
			this.marker.hide();
			
			var ummarker = this.marker;
			
			setTimeout(function() {ummarker.show()}, 100);
			
			this.element.addClassName("highlighted");
		}
	},

	deactivate: function()
	{
		if (this.active)
		{
			this.active = false;

			this.element.removeClassName("highlighted");
		}
	}

	
});

var Path = Class.create({
	initialize: function(key)
{
	paths.values().each(function(path) {
		path.deactivate();
	});
	
	this.key = key;
	this.isNew = key[0] == "n";
	this.points = [];
	this.element = $("path_" + key);
	this.title = $("path_" + key + "_title");
	this.description = $("path_" + key + "_description");
	this.active = true;
	this.colour = "#ff00ff";
	
	var umthis = this;
	
	Event.observe(this.element, "mouseover", function () { umthis.activate() });
	Event.observe(this.element, "mouseout", function () { umthis.deactivate() });
},

add: function(point)
{
	this.points.push(point);
	point.path = this;
	
	points[point.key] = point;
	
	this.redraw();
},

remove: function(point)
{
	if (point)
	{
		this.points = this.points.without(point);
		this.redraw();
	}
	else if (confirm("You realllly want to remove this entire path?"))
	{
		this.element.remove();
		//new Effect.BlindUp(this.element, {afterFinish: function() { 
		//	console.log("it's up!" + this.element)}});
		
		if (!this.isNew)
		{
			new Ajax.Request(page.path() + "/geos/" + this.key, {method: "delete"});
		}
		else
		{
			this.removed();
		}
	}
},
removed: function()
{
	this.points.each(function (p){
		p.removed();
	});
	map.removeOverlay(this.polyline);
	
	paths = paths.without(this);
},

activate: function()
{
	if (!this.active)
	{
		paths.values().each(function(path) { path.deactivate(); });
		
		this.active = true;
		this.colour = "#ff00ff";
		this.redraw();
		
		activePath = this.key;
		
		this.element.addClassName("highlighted");
	}
},

deactivate: function()
{
	if (this.active)
	{
		this.active = false;
		this.colour = "#0000ff";
		this.redraw();
		
		this.element.removeClassName("highlighted");
	}
},

polypoints: function()
{
	return this.points.collect(function (p) { return new GLatLng(p.lat(), p.lng()) });
},

redraw: function()
{	
	if (this.polyline)
	{
		map.removeOverlay(this.polyline);
	}
	
	this.polyline = new GPolyline(this.polypoints(), this.colour);
	
	if (this.points.size() > 1)
	{
		map.addOverlay(this.polyline);
	}
	
	var umthis = this;
	GEvent.addListener(this.polyline, "click", function () { umthis.activate() });
	GEvent.addListener(this.polyline, "mouseover", function () { umthis.activate() });
	GEvent.addListener(this.polyline, "mouseout", function () { umthis.deactivate() });
}
});

var attachments = $H();
var editedAttachment;

var Attachment = Class.create({
	initialize: function(id, page, json, ej)
	{
		this.id = id;
		this.page = page;
		this.li = $("attachment_" + id);
		this.li.attachment = this;
		
		this.image = this.li.getElementsByTagName("img")[0];
		
		this.json = json;
		this.editedJ = ej;
		
		new Draggable(this.li, {revert: true});
		
		this.filenameE = this.li.getElementsByClassName("filename")[0];
		this.titleE = this.li.getElementsByClassName("title")[0];
		
		Sortable.create("attachments", {onUpdate:function(){$("attachments-loader").show();new Ajax.Request('http://127.0.0.1:3000/pages/' + page + "/attachments;order", {asynchronous:true, evalScripts:true, method:'put', parameters:Sortable.serialize("attachments")})}, overlap: "horizontal", constraint: false});
	},
	
	filename: function()
	{
		return this.filenameE.innerHTML;
	},
	
	title: function()
	{
		return this.titleE.innerHTML;
	},
	
	edit: function(piece)
	{
		var options = {asynchronous:true, evalScripts:true, method:'get', onComplete:function(request){new Effect.Grow('new-attachment');}};
		
		if (piece)
		{
			options.parameters = "piece=" + piece;
		}
		
		new Ajax.Updater('attacher', '/pages/' + this.page + '/attachments/' + this.id + "/edit", options);
	},
	
	edited: function(newJSON, editPath, ej)
	{
		var olded = this.editedJ;
		//console.log("attachment " + this.id + " was edited.");
		this.json = newJSON;
		this.editedJ = ej;
		
		var preset = ej.preset;
		
		var piece = pieces.values().find(function (p) { return p.position == preset });
		
		this.image.src = editPath;
		
		if (piece)
		{
			if (olded)
			{
				piece.attachmentEdited(this, editPath);
			}
			else
			{
				piece.attachmentAdded(this, editPath);
			}
		}
	}
});

var pieces = $H();
var converter;

if ((!(!( Showdown||false ))))
{
	converter = new Showdown.converter();
} 

var Piece = Class.create({
	initialize: function(id, page, version, versions, position) 
	{
		this.id = id;
		this.page = page;
		
		this.selector = "#piece-" + id + "-content";
		
		this.version = version;
		this.versions = versions;
		
		this.position = position;
		
		this.control = $("piece-" + id + "-versions");
		this.versionE = $$("#piece-" + id + "-versions .version")[0];
		this.countE = $$("#piece-" + id + "-versions .count")[0];
		
		this.loader = $$("#piece-" + id + "-versions .loader")[0];
		this.resaveE = $$("#piece-" + id + "-versions .resave")[0];
		
		var umthis = this;
		Event.observe(this.resaveE, "click", function () { umthis.resave() });
		
		Event.observe(window, "load", function () { umthis.preview = $("piece-" + id + "-preview"); })
		
		this.formatter = $("piece-" + id + "-formatter");
		
		this.bolder = this.formatter.getElementsByClassName("bold")[0];
		Event.observe(this.bolder, "click", function () { umthis.bold() });
		
		this.italicer = this.formatter.getElementsByClassName("italic")[0];
		Event.observe(this.italicer, "click", function () { umthis.italic() });
		
		this.headerer = this.formatter.getElementsByClassName("header")[0];
		Event.observe(this.headerer, "click", function () { umthis.header() });
		
		this.linkser = this.formatter.getElementsByClassName("link")[0];
		Event.observe(this.linkser, "click", function (e) { umthis.links(e) });
		
		this.imageser = this.formatter.getElementsByClassName("image")[0];
		Event.observe(this.imageser, "click", function (e) { umthis.images(e) });
		
		this.pieceE = $("piece-" + id);
		
		this.editorE = $("piece-" + id + "-editor")
		
		
		this.linksE = this.editorE.getElementsByClassName("links")[0];
		new Draggable(this.linksE);
		
		$A(this.linksE.getElementsByClassName("link")).each(function (link) {
			Event.observe(link, "click", function () { if (link.attributes.length == 2) {umthis.linked(link); return false;} else { umthis.link() } });
		});
				
		$A(this.linksE.getElementsByTagName("img")).each(function (image) {
			Event.observe(image, "click", function() { umthis.ilinked(image)});
		})
		
		this.imagesE = this.editorE.getElementsByClassName("images")[0];
		new Draggable(this.imagesE);
		
		this.imageEvents = $H();
		
		$A(this.imagesE.getElementsByTagName("img")).each(function (image) {
			Event.observe(image, "click", umthis.imageEvents[image.id] = function () { umthis.imaged(image); });
		});
		
		Event.observe(window, "load", function () {umthis.editing();});
		
		this.saveE = $("piece-" + id + "-save");
		Event.observe(this.saveE, "click", function () { umthis.saving() });
		
		this.savingE = $("piece-" + id + "-saving");
	},
	
	edit: function()
	{
		new Effect.toggle(this.editorE, 'blind');
	},
	
	editing: function()
	{
		var umthis = this;
		new Form.Element.Observer(this.field(), 0.15, function() {umthis.updated();});
		
		//Droppables.add(this.field(), {onDrop: function(draggable, droppable, event) {umthis.dropped(draggable);}})
		
		this.formatter.show();
	},
	
	attachmentEdited: function(attachment, imagePath)
	{
		var e = $("piece-" + this.id + "-attachment-" + attachment.id);
		
		Event.stopObserving(e, "click", this.imageEvents[e.id]);
		
		e.src = "";
		e.src = imagePath;
		
		var umthis = this;
		Event.observe(e, "click", umthis.imageEvents[e.id] = function () { umthis.imaged(e) });
	},
	
	attachmentAdded: function(attachment, imagePath)
	{
		//=image_tag attachment.edited.public_filename(:thumb), {:alt => attachment.title, :lang => attachment.id, :id => "piece-#{piece.id}-attachment-#{attachment.id}"}
		var umthis = this;
		
		var list = this.imagesE.getElementsByClassName("list")[0];
		var id = "piece-" + this.id + "-attachment-" + attachment.id;
		var alt = attachment.title();
		
		var element = new Element("img", {src: imagePath, id: id, alt: alt});
		
		list.insert({bottom: element});
		
		Event.observe(element, "click", function () { umthis.imaged(image); });
	},
	
	saving: function()
	{
		this.savingE.show();
	},
	
	saved: function()
	{
		new Effect.Fade(this.savingE);
		this.versions++;
		this.version = this.versions;
		
		this.versionE.innerHTML = this.versions;
		this.countE.innerHTML = this.versions;
	},
	
	closed: function(transport)
	{
		this.formatter.hide();
		
		if (transport)
		{
			// An AJAX request was sent, so a version might have been saved?
			if (transport.getStatus() == 200)
			{
				this.versions++;
				this.version = this.versions;
				
				this.versionE.innerHTML = this.versions;
				this.countE.innerHTML = this.versions;
			}
		}
		else
		{
			this.preview.innerHTML = $("piece-" + this.id + "-content").innerHTML;
		}
	},
	
	field: function()
	{
		return $$(this.selector)[0];
	},
	
	updated: function()
	{
		var text = this.field().value;
		text = text.replace( /!(\[((\w|\W)*?)\])?\(((\w|\W)*?)\)/g, function (w, m1, m2, m3, m4) {
			if (attachments[m4])
			{
				return "!" + m1 + "(" + attachments[m4].filenameE.href + ")";
			}
			else
			{
				return "";
			}
		});
		text = text.replace( /!#(\[((\w|\W)*?)\])?\(((\w|\W)*?)\)/g, function (w, m1, m2, m3, m4) {  
			if (attachments[m4])
			{
				return "" + m1 + "(" + attachments[m4].filenameE.href + ")";
			}
			else
			{
				return "";
			}
		});
		
		this.preview.innerHTML = converter.makeHtml(text);
	},
	
	revert: function()
	{
		this.reversion(this.version - 1);
	},
	
	devert: function()
	{
		this.reversion(this.version + 1);
	},
	
	reversion: function(v)
	{
		if (v <= this.versions)
		{
			var umthis = this;
			
			this.loader.show();
			new Ajax.Request(
				"/pages/" + this.page + "/pieces/" + this.id,
				{
					asynchronous: true,
					method: 'get',
					parameters: "version=" + v,
					onSuccess: function() {
						umthis.version = v;
						umthis.versionE.innerHTML = v;
						umthis.resaveE.show();
						new Effect.Fade(umthis.loader);
					}
				}
			);
		}
	},
	
	resave: function()
	{
		new Ajax.Request(
			"/pages/" + this.page + "/pieces/" + this.id,
			{
				method: "put",
				parameters: "version=" + this.version
			}
		);
	},
	
	resaved: function()
	{
		this.resaveE.hide();
	},
	
	link: function()
	{
		insertTags("[", "](http://example.com)", "text of link", this.field());
		new Effect.Fade(this.linksE);
	},
	
	bold: function()
	{
		insertTags("**", "**", "text to embolden", this.field());
	},
	
	italic: function()
	{
		insertTags("*", "*", "text to italicise", this.field());
	},
	
	header: function()
	{
		insertTags("\n## ", "", "Header text", this.field());
	},
	
	links: function(e)
	{
		this.linksE.show();
		new Effect.Move(this.linksE, {x: e.pageX, y: e.pageY, mode: "absolute" });
	},
	
	linked: function(link)
	{
		insertTags("[", "](" + link.attributes[0].nodeValue + ")", link.childNodes[0].textContent, this.field());
		
		new Effect.Fade(this.linksE);
		
		return false;
	},
	
	ilinked: function(image)
	{
		var attachment = attachments[image.lang];
		
		insertTags("!#[", "](" + attachment.id + ")", attachment.title(), this.field());
		
		new Effect.Fade(this.linksE);
		
		return false;
	},
	
	images: function(e)
	{
		this.imagesE.show();
		new Effect.Move(this.imagesE, {x: e.pageX, y: e.pageY, mode: "absolute" });
	},
	
	imaged: function(image)
	{
		insertTags("![", "](" + image.lang + ")", image.alt, this.field());
		
		new Effect.Fade(this.imagesE);
	},
	
	dropped: function(draggable)
	{
		insertTags("![", "](" + draggable.attachment.filename() + ")", draggable.attachment.title(), this.field());
	}
});



// apply tagOpen/tagClose to selection in textarea,
// use sampleText instead of selection if there is none
function insertTags(tagOpen, tagClose, sampleText, txtarea) {
	var selText, isSample = false;

	if (document.selection  && document.selection.createRange) { // IE/Opera

		//save window scroll position
		if (document.documentElement && document.documentElement.scrollTop)
			var winScroll = document.documentElement.scrollTop
		else if (document.body)
			var winScroll = document.body.scrollTop;
		//get current selection  
		txtarea.focus();
		var range = document.selection.createRange();
		selText = range.text;
		//insert tags
		checkSelectedText();
		range.text = tagOpen + selText + tagClose;
		//mark sample text as selected
		if (isSample && range.moveStart) {
			if (window.opera)
				tagClose = tagClose.replace(/\n/g,'');
			range.moveStart('character', - tagClose.length - selText.length); 
			range.moveEnd('character', - tagClose.length); 
		}
		range.select();   
		//restore window scroll position
		if (document.documentElement && document.documentElement.scrollTop)
			document.documentElement.scrollTop = winScroll
		else if (document.body)
			document.body.scrollTop = winScroll;

	} else if (txtarea.selectionStart || txtarea.selectionStart == '0') { // Mozilla

		//save textarea scroll position
		var textScroll = txtarea.scrollTop;
		//get current selection
		txtarea.focus();
		var startPos = txtarea.selectionStart;
		var endPos = txtarea.selectionEnd;
		selText = txtarea.value.substring(startPos, endPos);
		//insert tags
		checkSelectedText();
		txtarea.value = txtarea.value.substring(0, startPos)
			+ tagOpen + selText + tagClose
			+ txtarea.value.substring(endPos, txtarea.value.length);
		//set new selection
		if (isSample) {
			txtarea.selectionStart = startPos + tagOpen.length;
			txtarea.selectionEnd = startPos + tagOpen.length + selText.length;
		} else {
			txtarea.selectionStart = startPos + tagOpen.length + selText.length + tagClose.length;
			txtarea.selectionEnd = txtarea.selectionStart;
		}
		//restore textarea scroll position
		txtarea.scrollTop = textScroll;
	} 

	function checkSelectedText(){
		if (!selText) {
			selText = sampleText;
			isSample = true;
		} else if (selText.charAt(selText.length - 1) == ' ') { //exclude ending space char
			selText = selText.substring(0, selText.length - 1);
			tagClose += ' '
		} 
	}

}

function loadAttachment(id, piece)
{
	new Ajax.Request("/pages/" + page.id + "/attachments/" + id + ".js", {method: "get", onComplete: function() { attachmentLoaded(id, piece) } });
}

function attachmentLoaded(id, piece)
{
	if (attachments[id].filenameE.href.indexOf(".pdf") == -1)
	{
	attachments[id].edit(piece);
	}
}


var statuses = $H();

var Status = Class.create({
	initialize: function(prefix)
	{
		this.prefix = prefix;
		
		this.huh = $(prefix + "-huh");
		this.loader = $(prefix + "-loader");
	},
	
	before: function()
	{
		this.loader.show();
	},
	
	success: function()
	{
		new Effect.Fade(this.loader);
		this.huh.hide();
	},
	
	failure: function()
	{
		new Effect.Fade(this.loader);
		this.huh.show();
	}
})
