function register(e)
{
	if (!e) e = window.event;
	if (e.ctrlKey)
	{
		switch(e.keyCode)
		{
			case 37:
				id = $('id_prev');
				if (id) location.href = id.href;
				break;
			case 39:
				id = $('id_next');
				if (id) location.href = id.href;
				break;
		}
	}
}

Grip = function() 
{
	this.staticOffset = 0;
	this.textarea = '';
}

Grip.prototype = {
	startDrag : function(t, e) 
	{
		Event.observe(document, 'mousemove', grip.performDrag);
		Event.observe(document, 'mouseup', grip.endDrag);
		this.textarea = $(t);
		this.staticOffset = $(t).offsetHeight - Event.pointerY(e);
		return false;
	},
	
	performDrag : function(e) 
	{
		grip.textarea.setStyle({height: Math.max(48, grip.staticOffset + Event.pointerY(e)) + 'px'});
		return false;
	},

	endDrag : function(e) 
	{
		Event.stopObserving(document, 'mousemove', grip.performDrag);
		Event.stopObserving(document, 'mouseup', grip.endDrag);
	}
}

Wiki = function () {this.invokelist = new Array();}

Wiki.prototype = {
	
	getCursor : function(o)
	{
	  var result = { start: 0, end: 0 };
	  if (o.setSelectionRange)
	  {
	    result.start= o.selectionStart;
	    result.end = o.selectionEnd;
	  }
	  else if (!document.selection) { return 0; }
	  else if (document.selection && document.selection.createRange)
	  {
	    var range = document.selection.createRange();
	    var stored_range = range.duplicate();
	    stored_range.moveToElementText(o);
	    stored_range.setEndPoint('EndToEnd', range);
	    result.start = stored_range.text.length - range.text.length;
	    result.end = result.start + range.text.length;
	  }
	  return result;
	},

	setCursor : function(o, start, end)
	{
		if (o.createTextRange)
		{
			var range = o.createTextRange();
			range.move("character", start);
			range.select();
		} 
		else
		if (o.selectionStart) 
		{
			o.setSelectionRange(start, end);
		}
	},

	custom : function(id, ibTagStart, ibTagEnd, val)
	{
		var o = $(id);
		var p = 0;
		o.focus();
		var cur = this.getCursor(o);
		var top = o.scrollTop;
		if (document.selection)
		{
			var sel = document.selection;
			var rng = sel.createRange();
			rng.colapse;
			if (typeof(val)=='undefined')
			{
				v = ibTagStart + rng.text + ibTagEnd;
				p = cur.end+ibTagStart.length;
			}
			else 
			{
				v = rng.text + val;
				p = cur.end+val.length;
			}
			rng.text = v;
		}
		else
		{
			var ss = o.selectionStart;
			var es = o.selectionEnd;
			
			if (es <= 2)
			{
				es = o.textLength;
			}
			
			var start  = (o.value).substring(0, ss);
			var middle = (typeof(val)=='undefined')?(o.value).substring(ss, es):val;
			var end    = (o.value).substring(es, o.textLength);
			
			middle = ibTagStart + middle + ibTagEnd;
			o.value = start + middle + end;
			
			var p = ss + (middle.length) - ibTagEnd.length;
		}
		this.setCursor(o, p, p);
		if (top) o.scrollTop = top;
		o.focus();
	},
	
	bold : function (id)
	{
		this.custom(id, '**', '**');
	},
	
	italic : function (id)
	{
		this.custom(id, '//', '//');
	},
	
	stroke : function (id)
	{
		this.custom(id, '<del>', '</del>');
	},
	
	underline : function (id)
	{
		this.custom(id, '__', '__');
	},
	
	user : function (id)
	{
		var name = prompt("Введите имя пользователя", "");
		if (name) this.custom(id, '', '', '@'+name);
	},
	
	video : function (id)
	{
		var url = prompt("Введите URL на видео в youtube или rutube", "http://");
		if (url) this.custom(id, '', '', '{{'+url+'}}');
	},
	
	image : function (id)
	{
		if (typeof(this.invokelist['image']) == 'string') eval(this.invokelist['image']+"('"+id+"')");
	},
	
	link : function (id)
	{
		var o = $(id);
		if (o.setSelectionRange)
		{
			var s = o.selectionStart != o.selectionEnd;
		}
		else
		{
			var range = document.selection.createRange();
			var s = range.text != '';
		}
		if (!s) 
		{
			alert('Выделите текст, который хотите сделать ссылкой');
			return;
		}
		var url = prompt("Введите URL ссылки", "http://");
		if (!/^(http|https|ftp)\:\/\/[0-9A-Za-z][0-9A-Za-z\-\.]*\.[a-zA-Z]{2,4}/.test(url)) 
		{
			alert('Это не URL');
			return;
		}
		this.custom(id, '[['+url+'|', ']]');
	},
	
	getLines : function (o)
	{
		var cur = this.getCursor(o);
		
		if (document.selection)
		{
			var sel = document.selection;
			var rng = sel.createRange();
			rng.colapse;
	
			var ss = cur.start;
			var es = cur.end;
		}
		else
		{
			var ss = o.selectionStart;
			var es = o.selectionEnd;
		}
		
		if (o.value.substring(ss-1, ss) != '\n') 
		{
			ss = o.value.substring(0, ss).lastIndexOf('\n')+1;
		}
		if (o.value.substring(es, es+1) != '\n') 
		{
			es = es + o.value.substring(es+1, o.value.length).indexOf('\n')+1;
		}
		return { start: ss, end: es };
	},
	
	quote : function (id)
	{
		var o = $(id);
		o.focus();
		var lines = this.getLines(o);
		ss = lines.start;
		es = lines.end;
		var v = o.value.substring(ss, es);
	
		var start  = (o.value).substring(0, ss);
		var end    = (o.value).substring(es, o.textLength);
		var p = v.split('\n');
		v = '';
		for(i=0; i<p.length; i++) 
		{
			var s = p[i].replace(/(^\s+)|(\s+$)/g, '');
			var f = s.substring(0, 1);
			v += '\n'+((f == '>')?'>':'> ')+s;
		}
		v = v.substring(1);
		o.value = start + v + end;
		var p = ss + v.length;
		this.setCursor(o, p, p);
		o.focus();
	},
	
	list : function(id, t)
	{
		var o = $(id);
		o.focus();
		var lines = this.getLines(o);
			
		ss = lines.start;
		es = lines.end;
		var v = o.value.substring(ss, es);
	
		var start  = (o.value).substring(0, ss);
		var end    = (o.value).substring(es, o.textLength);
		var p = v.split('\n');
		v = '';
		for(i=0; i<p.length; i++) 
		{
			var s = p[i].replace(/(^\s+)|(\s+$)/g, '');
			var f = s.substring(0, 1);
			if (['-', '*'].include(f)) s = s.substring(1);
			v += '\n  '+t+s;
		}
		v = v.substring(1);
		o.value = start + v + end;
		var p = ss + v.length;
		this.setCursor(o, p, p);
		o.focus();
	},
	
	ol : function (id)
	{
		this.list(id, '*');
	},
	
	ul : function (id)
	{
		this.list(id, '-');
	},
	
	linebreak : function (id)
	{
		this.custom(id, '', '', '\n\n-------------------------\n\n');
	}
}

Editor = function()
{
	this.id = null;
}

Editor.prototype = {
	showFileDialog : function (id)
	{
		this.id = id;
		var e = document.documentElement;
		var b = document.body;
		var h = e.clientHeight ? e.clientHeight : b.scrollHeight;
		var w = e.clientWidth ? e.clientWidth : b.scrollWidth;
		idShadow = showShadow(w, h);
		idShadow.observe('mousedown', editor.hideFileDialog);

		$('idImageAlt').value = '';
		$('idImagePosition').value = 1;
		$('idImageSrc').value = 'http://';
		$('idImageBrowse').value = '';
		
		var shift = document.documentElement.scrollTop || document.body.scrollTop;
		h = (((window.innerHeight ? window.innerHeight : b.clientHeight)-400)/2)+shift+'px';
		
		$('imageForm').setStyle({display:'block', top:h, left:((w-300)/2)+'px'});
		if (Prototype.Browser.IE)
		{
			skip = $('idImagePosition');
			$$('SELECT').each(function(el){if (el != skip) el.setStyle({visibility:'hidden'})});
		}

		$$('EMBED').each(function(el){el.setStyle({visibility:'hidden'})});
	},
	
	hideFileDialog : function ()
	{
		idShadow = hideShadow();
		Event.stopObserving(idShadow, 'mousedown', editor.hideFileDialog);
		$('imageForm').hide();

		$$('SELECT').each(function(el){el.setStyle({visibility:''})});
		$$('EMBED').each(function(el){el.setStyle({visibility:''})});
	},
	
	insertImage : function (name)
	{
		var alt = $F('idImageAlt').replace(/(^\s+)|(\s+$)/g, '');
		switch ($F('idImagePosition'))
		{
			case '2': name = name+" "; break;
			case '3': name = " "+name; break;
		}
		if (alt != '') name += '|'+alt;
		wiki.custom(this.id, '', '', '{{'+name+'}}');
		this.hideFileDialog();
	}
}

function showShadow(w, h)
{
	var id = $('idShadow');
	if (!id)
	{
		id = document.createElement("DIV");
		id.className  = 'shadow';
		id.id = 'idShadow';
		document.body.appendChild(id);
		id = Element.extend(id);
	}
	id.setOpacity(0.5);
	id.setStyle({display:'block', height:h+'px', width:w+'px'});
	return id;
}

function hideShadow()
{
	return $('idShadow').hide();
}

wiki = new Wiki();
grip = new Grip();
editor = new Editor();
wiki.invokelist['image'] = "editor.showFileDialog";
new Image().src = "http://counter.yadro.ru/hit?r"+escape(document.referrer)+((typeof(screen)=="undefined")?"":";s"+screen.width+"*"+screen.height+"*"+(screen.colorDepth?screen.colorDepth:screen.pixelDepth))+";u"+escape(document.URL)+";"+Math.random();
