var w = 400;
var h = 300;
var d = document;
var c = 'jpg';
var m = 100;
var tmp = '';
var browser = navigator.userAgent;
var xmlhttp = false;
var isIE = /*@cc_on!@*/false;

/*@cc_on @*/
/*@if (@_jscript_version >= 5)
// JScript gives us Conditional compilation, we can cope with old IE versions.
// and security blocked creation of the objects.
 try {
  xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
 } catch (e) {
  try {
   xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
  } catch (E) {
   xmlhttp = false;
  }
 }
@end @*/

if (d.addEventListener) { 
	d.addEventListener('DOMContentLoaded', init, false); 
} else if (d.attachEvent) { 
	d.attachEvent('onreadystatechange', function(){
		if(d.readyState === 'complete') init();
	});
}


if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
	try {
		xmlhttp = new XMLHttpRequest();
	} catch (e) {
		xmlhttp=false;
	}
}

if (!xmlhttp && window.createRequest) {
	try {
		xmlhttp = window.createRequest();
	} catch (e) {
		xmlhttp=false;
	}
}

var cmnt_pool = '';
function comment_form(id, name, comm) {
	var c = parseInt(comm);
	if (tmp == '') {
		xmlhttp.open("GET", "/blog/comment.php?psto="+id+"&nick="+name,true);
		xmlhttp.onreadystatechange=function() {
			if (xmlhttp.readyState==4) {
				obj = document.getElementById('comment_form');
				tmp = obj.innerHTML;
				obj.innerHTML = xmlhttp.responseText;
				if (c > 0) {
					field = document.getElementById('comment_body');
					field.innerHTML = ">>" + c + " ";
					field.focus();
				}
			}
		}
		xmlhttp.send(null)
	} else { document.getElementById('comment_body').innerHTML += ">>" + c + " "; }
}

function comment_close() {
	document.getElementById('comment_form').innerHTML = tmp;
	tmp = '';
}

function moveItems (tablename, action) {
	if (action == 'remove') {
		var from = document.getElementsByName('in_'+tablename)[0];
		var to = document.getElementsByName('all_'+tablename)[0];
		var chvalue = 0;
	} else if (action == 'add') {
		var from = document.getElementsByName('all_'+tablename)[0];
		var to = document.getElementsByName('in_'+tablename)[0];
		var chvalue = 1;
	} else {
		alert ('Crossboxes error...');
	}
	var selindex;
	while ((selindex=from.selectedIndex) != -1) {
		var i;
		var item = new Option(from.options[selindex].text, from.options[selindex].value, false, true);
		var origid = from.options[selindex].value;
		from.options[selindex] = null;
		//to.options[to.options.length] = item;
		for (i=0; i<to.options.length && to.options[i].text < item.text; i++) { }
		var newindex = i;
		for (i=to.options.length; i>newindex; i--) {
			to.options[i] = new Option(to.options[i-1].text, to.options[i-1].value, false, to.options[i-1].selected);
		}
		to.options[newindex] = item;
		document.getElementsByName(tablename+'['+origid+']')[0].value = chvalue;
	}
}

function new_freecap()
{
	// loads new freeCap image
	if(document.getElementById)
	{
		// extract image name from image source (i.e. cut off ?randomness)
		thesrc = document.getElementById("freecap").src;
		thesrc = thesrc.substring(0,thesrc.lastIndexOf(".")+4);
		// add ?(random) to prevent browser/isp caching
		document.getElementById("freecap").src = thesrc+"?"+Math.round(Math.random()*100000);
	} else {
		alert("Sorry, cannot autoreload freeCap image\nSubmit the form and a new freeCap will be loaded");
	}
}

function init() {
	var imgs = d.getElementsByTagName('img');
	for(i=0; i<imgs.length; i++)
		if(imgs[i].className === c) new Img(imgs[i]);

	var t = d.getElementById('html');
	if (t) new Textarea(t);
}

var Img = function(elem) {	// Constructor
	var img = d.createElement('img');
	
	elem.parentNode.replaceChild(img, elem);

	img.onload = this.load;
	img.onclick = this.click;
	img.onerror = this.error;
	img.src = elem.src;
	img.className = 'jpg';
}

Img.prototype = {		// Prototype
	zoom: false,

	load: function() {
		this.style.display = 'block';
		this.style.cursor = 'crosshair';
		this.realWidth = this.width;
		this.realHeight = this.height;
		if (this.realWidth > this.realHeight) {
			if (this.realWidth > w) this.style.width = w + 'px';
		} else {
			if (this.realHeight > h) this.style.height = h + 'px';
		}
	},

	click: function() {
		new Canvas(this.src);
	},

	error: function() {
		this.src = 'imgerr.jpg';
	},

}

var Canvas = function(src) {
	var container = d.createElement('div');	// Container
	var cnv = d.createElement('div');	// Canvas
	var img = d.createElement('img');  	// Image

	img.className = 'big';
	img.onload = this.fit;
	img.style.cursor = 'crosshair';
	img.src = src;

	container.appendChild(cnv);
	container.appendChild(img);
	container.onclick = this.close;

	d.body.appendChild(container);

	cnv.className = 'canvas';
}

Canvas.prototype = {

	close: function() {
		d.body.removeChild(this);
	},

	fit: function() {
		// Calculate viewport metrics
		if (self.innerHeight) {
			x = self.innerWidth;
			y = self.innerHeight;
		} else if (d.documentElement && d.documentElement.clientHeight) {
			x = d.documentElement.clientWidth;
			y = d.documentElement.clientHeight;
		} else if (d.body) {
			x = d.body.clientWidth;
			y = d.body.clientHeight;
		}

		// If viewport is too small, decrease margins
		k = x < 640 || y < 480 ? m/2 : m;

		// Fit image to viewport
		x = x - k*2;
		y = y - k*2;
		if (this.width > x && this.height < y) {
			width = x;
			height = this.height*(width/this.width);
		} else if (this.width < x && this.height > y) {
			height = y;
			width = this.width*(height/this.height);
		} else if (this.width > x && this.height > y) {
			if (this.width > this.height) {
				width = x;
				height = this.height*(width/this.width);
			} else {
				height = y;
				width = this.width*(height/this.height);
			}
		} else {
			width = this.width;
			height = this.height;
		}
		this.style.width = width.toFixed()+'px';
		this.style.height = height.toFixed()+'px';

		// Positioning image in the viewport
		this.style.marginTop = '-'+(height/2).toFixed()+'px';
		this.style.marginLeft = '-'+(width/2).toFixed()+'px';
	}
}

var Textarea = function(text){
	var t = d.createElement('textarea');

	text.parentNode.insertBefore(t, text);

	t.value = text.value;
	t.style.width = '640px';
	t.style.height = '400px';
	t.className = t.name = text.id;
	t.onpaste = this.paste;
	t.oninput = this.input;
	t.focus();

	text.parentNode.removeChild(text);
}

Textarea.prototype = {
	input: function() {
	},

	paste: function() {
		var chunk = isIE ? d.selection.createRange() : this.value.substring(this.selectionStart, this.selectionEnd);
		var sel = isIE ? chunk.text : chunk;
		var obj = this;
		var start = _position(obj);
		window.setTimeout(
			function() {
				var end = _position(obj);
				var buf = trim(obj.value.substring(start, end));
				var pat = /^(http|https)\:\/\/[^\s]+/i;
				var img = /\.(jpg|gif|png)$/i;
				if (pat.test(buf)) {
					var temp = img.test(buf) ?
						"<img src=\""+buf+"\""+(sel!=''?" alt=\""+sel+"\"":'')+">"
						:
						"<a href=\""+buf+"\">"+(sel!=''?sel:buf)+"</a>";

					if (isIE) chunk.text = temp;
					else obj.value = obj.value.substring(0, start)+temp+obj.value.substring(end, obj.value.length);
				}
			}, 1
		);
	},
}

function trim(str) {
	var str = str.replace(/^\s\s*/, ''),
		ws = /\s/,
		i = str.length;

	while (ws.test(str.charAt(--i)));
	return str.slice(0, i + 1);
}

function _position(obj) {
	if (isIE) {
		obj.focus();
		var r = d.selection.createRange();
		if (r == null) return 0;
		var re = obj.createTextRange(),
		rc = re.duplicate();
		re.moveToBookmark(r.getBookmark());
		rc.setEndPoint('EndToStart', re);
		return rc.text.length;
	} else {
		return obj.selectionStart;
	} 
	return 0;
}

