function URLEncode(plaintext)
{
	var SAFECHARS = "0123456789" +					// Numeric
					"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +	// Alphabetic
					"abcdefghijklmnopqrstuvwxyz" +
					"-_.!~*'()";					// RFC2396 Mark characters
	var HEX = "0123456789ABCDEF";

	var encoded = "";
	for (var i = 0; i < plaintext.length; i++ ) {
		var ch = plaintext.charAt(i);
	    if (ch == " ") {
		    encoded += "+";				// x-www-urlencoded, rather than %20
		} else if (SAFECHARS.indexOf(ch) != -1) {
		    encoded += ch;
		} else {
		    var charCode = ch.charCodeAt(0);
			if (charCode > 255) {
				encoded += "+";
			} else {
				encoded += "%";
				encoded += HEX.charAt((charCode >> 4) & 0xF);
				encoded += HEX.charAt(charCode & 0xF);
			}
		}
	} // for

	return encoded;
}

function URLDecode(encoded)
{
   var HEXCHARS = "0123456789ABCDEFabcdef"; 
   var plaintext = "";
   var i = 0;
   while (i < encoded.length) {
       var ch = encoded.charAt(i);
	   if (ch == "+") {
	       plaintext += " ";
		   i++;
	   } else if (ch == "%") {
			if (i < (encoded.length-2) 
					&& HEXCHARS.indexOf(encoded.charAt(i+1)) != -1 
					&& HEXCHARS.indexOf(encoded.charAt(i+2)) != -1 ) {
				plaintext += unescape( encoded.substr(i,3) );
				i += 3;
			} else {
				alert( 'Bad escape combination near ...' + encoded.substr(i) );
				plaintext += "%[ERROR]";
				i++;
			}
		} else {
		   plaintext += ch;
		   i++;
		}
	} // while
   return plaintext;
}

function trim(inputString) {
   if (typeof inputString != "string") { return inputString; }
   var retValue = inputString;
   var ch = retValue.substring(0, 1);
   while (ch == " ") {
      retValue = retValue.substring(1, retValue.length);
      ch = retValue.substring(0, 1);
   }
   ch = retValue.substring(retValue.length-1, retValue.length);
   while (ch == " ") {
      retValue = retValue.substring(0, retValue.length-1);
      ch = retValue.substring(retValue.length-1, retValue.length);
   }
   while (retValue.indexOf("  ") != -1) {
      retValue = retValue.substring(0, retValue.indexOf("  ")) + retValue.substring(retValue.indexOf("  ")+1, retValue.length); // Again, there are two spaces in each of the strings
   }
   return retValue;
}

function submitForm(id, form) {
	var s = '?';
	var first = true;
	for(var i = 0; i < form.elements.length; i++)
		if(form.elements[i].name) {
			if(first)
				first = false;
			else
				s += '&';
			s += form.elements[i].name + '=' + URLEncode(form.elements[i].value);
		}
	if(id) {
		var ug = new URLGrabber(id, form.action + s);
		ug.load();
		Modules.sortModules();
	} else {
		var w = window.open();
		w.location = (form.action + s);
	}
	return false;
}

function linkClick(id, url) {
	var s = '?';
	if(id) {
		var ug = new URLGrabber(id, url);
		ug.load();
		Modules.sortModules();
	} else {
		var w = window.open();
		w.location = (url);
	}
	return false;
}
function createCookie(name,value,days)
{
	if (days)
	{
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name)
{
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++)
	{
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name)
{
	createCookie(name,"",-1);
}

function toInt(value) {
	return isNaN(parseInt(value)) ? 0 : parseInt(value);
}

var Modules = {
	_modules : new Array(),
	onOpen : null,
	onClose : null,
	counter : 0,

	_compareModules : function(a, b) {
		return toInt(a.style.top) - toInt(b.style.top);
	},
	
	_sortModules : function()
	{
		this._modules.sort(this._compareModules);
		var l = 100;
		var r = 100;
		for(var i = 0; i < this._modules.length; i++) {
			var module = this._modules[i];
			module.style.zIndex = 100;
			var leftcolumn = toInt(module.style.left) < 173;
			if(leftcolumn) {
				module.style.left = '10px';
				module.style.top = l + 'px';
				l += module.offsetHeight;
			} else {
				module.style.left = '336px';
				module.style.top = r + 'px';
				r += module.offsetHeight;
			}
		}
	},

	_moveModule : function(module, x, y)
	{
		module.style.left = module.o.lastMouseX < 336 ? '10px' : '336px';
		module.style.top = toInt(module.style.top) - 1 + 'px';
		this._sortModules();
	},

	_toggleModule : function(span) {
		var body = span.parentNode.parentNode.nextSibling;
		var module = span.parentNode.parentNode.parentNode;
		var doopen = body.style.display == 'none';
		span.innerHTML = doopen ? '_' : '^';
		if(doopen) {
			if(module.onOpen) module.onOpen();
		} else {
			if(module.onClose) module.onClose();
		}

		body.style.display = doopen ? 'block' : 'none';
		this._sortModules();
	},

	_deleteModule : function(span) {
		var module = span.parentNode.parentNode.parentNode;
		document.body.removeChild(module);
		this._sortModules();
		window.location = window.location;	
	},

	_focusModule : function(module)
	{
		module.style.zIndex = 101;
	},

	createModule : function(name, caption, body, right)
	{
		
		var module = document.createElement('div');
		module.id = name;
		module.className = 'module';		
		module.innerHTML = '<div id="' + name + '_caption" class="caption"><div style="float: right"><span onclick="Modules._toggleModule(this)">^</span><span onclick="Modules._deleteModule(this)">X</span></div><span>' + caption + '</span></div><div style="display: none;" id="' + name + '_body">' + body + '</div>';
		module.style.top = (Modules.counter++) + 'px'; 
		if(right) module.style.left = '336px';
		document.body.appendChild(module);
		this._modules[this._modules.length] = module;
		module.body = module.firstChild.nextSibling;
		module.caption = module.firstChild.firstChild.nextSibling;
		module.firstChild.firstChild.firstChild.module = module;
		module.toggle = function() { Modules._toggleModule(module.firstChild.firstChild.firstChild) };
		module.isOpen = function() { return this.firstChild.firstChild.firstChild.innerHTML == '_'; };
		module.setCaption = function(text) { this.caption.innerHTML = text; };
		module.fireAction = function(action, data) { 
			if(action == 'setCaption') this.setCaption(data);
		};
		
		return module;
	},
	
	initModules : function()
	{
		for(var i = 0; i < this._modules.length; i++) {
			var r = this._modules[i];
			var h = r.firstChild;
			Drag.init(h, r, 10, 336, 100);
			r.onDragStart = function(x, y) { Modules._focusModule(this); };
			r.onDragEnd = function(x, y) { Modules._moveModule(this, x, y); };
		}
		this._sortModules();
	},

	sortModules : function()
	{
		this._sortModules();
	},
	
	saveState : function()
	{
		var state = '';
		for(var i = 0; i < this._modules.length; i++) {
			var m = this._modules[i];
			if(i) state += '|';
			state += m.id + '&' + (m.isOpen() ? 1 : 0) + '&' + toInt(m.style.left) + '&' + toInt(m.style.top);
		}
		return state;
	},
	
	loadState : function(state)
	{
		if(state == null) return;
		var statearray = state.split('|');
		for(var i = 0; i < statearray.length; i++) {
			var item = statearray[i].split('&');
			var module = document.getElementById(item[0]);
			if(module) {
				if(module.isOpen() != item[1]) module.toggle();
				module.style.left = item[2] + 'px';
				module.style.top = item[3] + 'px';
			}
		}
		this.sortModules();
	}
}

function saveState()
{
	createCookie('state', Modules.saveState(), 365);
}

function loadState()
{
	Modules.loadState(readCookie('state'));
}

function isDefaultState()
{
	return readCookie('state') == null;
}

function setHomepage(obj){
	if(document.all){
		obj.style.behavior="url(#default#homepage)";
		obj.setHomePage("http://www.wooha.se");
	}else{
		alert("Drag Jordgloben från vänsterkanten av adressfältet till huset till vänster om adressfältet, för att sätta www.wooha.se till din startsida.");
	}
}
