var myDomain = 'http://trial.me-blogs-it.com/'; // write your domain here
var myDomainSearch = /trial\.me-blogs-it\.com/; // for regex
var myThemePath = myDomain+'/wp-content/themes/JS-OS-theme/';



function fobj(id) { if (document.getElementById) {return(document.getElementById(id));} else if (document.all) {return(document.all.id);} }
function fstyle(id) { return(fobj(id).style); }

$(document).ready(function() {
	if($.browser.msie) {
		Check = confirm("Warning: The browser you use to enter this site is very crappy. Do you really want to continue?");
		if(!Check) window.location.href='http://browsehappy.com';
	} else if(!$.browser.safari) {
		alert("This site currently only runs on WebKit-Browsers. Please use Safari or Google Chrome to access this site.");
	}
	createAllElements();

	// Get all the GET-variables
	GET = new Object();
	if(window.location.search) {
		// thx to selfhtml.org for explaining how to get the GET-variables
		// read the full article here: http://forum.de.selfhtml.org/archiv/2003/1/t33748/
		GETparameters = window.location.search.substr(1).split('&'); // removes the questionmark at the beginning and split the rest at the '&'
		for(var i=0; i<GETparameters.length; ++i) {
			var parameter = GETparameters[i].split('=');
			parameter[1]=parameter[1].replace(/\+/g," ");   // replaces '+' with ' '
			GET[parameter[0]] = unescape(parameter[1]);
		}
	}
	place('laden', 50, 50);
	$("#laden").fadeIn(1200, function() {
	$('#middle').load(myDomain+'?content=only', function() {
		$("#front").fadeIn(1000);
		$("#laden").fadeOut(1200);
		catchLinks();

	   if(document.cookie) {
		var COOKIE = document.cookie.split(/\[[0-2]\]/);
		var PostData = COOKIE[1].split(/\$/);
		for(var i=1; i<PostData.length; i++) {
			var saved = PostData[i].split(/%/);
			PostData[i] = saved;
		}
		var ExternalData = COOKIE[2].split(/\$/);
		for(var i=1; i<ExternalData.length; i++) {
			var saved = ExternalData[i].split(/%/);
			ExternalData[i] = saved;
		}
		PostData.splice(0,1);
		ExternalData.splice(0,1);
		var leftAt = COOKIE[0].substr(COOKIE[0].lastIndexOf("=")+1);
		var Check = confirm('You left this site on '+leftAt+'. Do you want to continue with your session?');
		if(Check) reloadOldPage(PostData, ExternalData);
	   }
		var ToLaunch=22;
		if(GET['post']) {
			ToLaunch = parseInt(GET['post']);
			if(!ToLaunch) ToLaunch = 22;
		}
		launchWindow(ToLaunch);

	});
	});
	
	Post = new Array();
	External = new Array();
	BackTie = new Object();
	BackTieExternal = new Object();
	Display = new Array(fobj('displayPostNumber').firstChild, fobj('displayExternalNumber').firstChild);
	current = new Array('', 0, 40, 40); // 1. id des aktiven Fensters, 2. zIndex des aktiven Fensters, 3. top 4. left
	var homeSite = 'http://www.google.de/'; // The "Home"-website which is opened when you launch a new Pseudo-Browser 
});


function createAllElements() {

	var middle = '<!-- middle --><div id="middle" style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; z-index: 0; display: block;">  </div><!-- middle Ende -->';

	var Logo = '<!-- Logo --><div id="logo" style="position: absolute; top:0; left:0; margin: 10px; width: 181px; height: 33px;"><img src="'+myThemePath+'logo.gif" alt="" /></div>';

	var Menu = '<!-- Menu --><div style="position: absolute; width: 100%; height: 100px; bottom: 0; left: 0; text-align: center;" id="menu"><table style="width: 600px; height: 100px; background-color: white; margin: auto; border-spacing: 0px; table-layout: fixed; color: #808080;" id="dock"><tr id="dockcol"><td style="text-align: center; vertical-align: bottom;" onclick="showElement(\'subscriptions\');"><div style="background-position-x: -2px; width: 64px;" class="menuicons" id="RSSIcon"></div><div class="menuiconlabels">Subscribe</div></td><td onclick="showElement(\'about\', \'place\');"><div style="background-position-x: -112px; width: 64px;" class="menuicons" id="AboutIcon"></div><div class="menuiconlabels">About</div></td><td onclick="DisplayPostOverview();"><div style="background-position-x: -221px; width: 100px; text-align: right;" class="menuicons" id="PostsIcon"><span style="padding: 2px 3px; margin: 0; background-color: red; color: white; font-size: 10px;" id="displayPostNumber"> </span></div><div class="menuiconlabels">Posts&Pages</div></td><td onclick="showElement(\'searchInterface\');"><div style="background-position-x: -376px; width: 63px;" class="menuicons" id="SearchIcon"></div><div class="menuiconlabels">Search</div></td><td onclick="DisplayExternalOverview();"><div style="background-position-x: -524px; width: 64px; text-align: right;" class="menuicons" id="ExternalIcon"><span style="padding: 2px; margin: 0; background-color: red; color: white; font-size: 10px;" id="displayExternalNumber"> </span></div><div class="menuiconlabels">External</div></td></tr></table></div>';

	var PostOverview = '<!-- Post Ueberblick --><table id="PostOverview" class="tabletype"></table>';

	var ExternalOverview = '<!-- External Ueberblick --><div id="ExternalOverviewWrapper"><table id="ExternalOverview" class="tabletype"></table><div style="clear: both; display: block; margin:0; padding: 0;"><input type="text" id="ManualWebsiteCall" value="Enter website URL" onfocus="this.value=\'\';" onkeyup="ManualWebsiteCall();" /></div></div>';

	var front = '<!-- front --><div id="front" style="position: fixed; width: 100%; height: 100%; z-index: 100; display: none;">' + middle + Logo + Menu + PostOverview + ExternalOverview + '</div>';

	var subscribe = '<!-- Subscribe --><table class="tabletype" id="subscriptions"><tr><td onclick="window.open(\'http://feeds2.feedburner.com/JSOStheme\');"><div class="subscribeIcon" style="background-position-y: 0px;"> </div> RSS-Feed</td></tr><tr><td><div class="subscribeIcon" style="background-position-y: -12px;"> </div> <span onclick="showElement(\'subscribeMail\');">Mail-Feed</span><div id="subscribeMail" style="display: none; margin: 5px 0 0 0; clear: both; padding: 0;"><input type="text" value="your@email and Enter" style="border: 1px solid #808080; margin: 0; font-size: 10px; color: #808080; padding: 2px; background-image: url(mailInvalid.png); background-position: center right; background-repeat: no-repeat;" onfocus="this.value=\'\';" onkeyup="checkEmail(this); if(window.event.keyCode==13 && checkEmail(this)) launchBrowser(\'http://feedburner.google.com/fb/a/mailverify?uri=JSOStheme&email=\'+this.value);" /></div></td></tr><tr><td><span onclick="showElement(\'subscribeComments\');"><div class="subscribeIcon" style="background-position-y: -36px;"> </div> Comment-Feed</span><div id="subscribeComments" style="display: none; margin-top: 5px;"><img src="'+myThemePath+'comments_mail.png" alt="" /> via RSS <span onclick="showElement(\'subscribeComments\'); showElement(\'subscribeCommentsMail\');"><img src="'+myThemePath+'comments_rss.png" alt="" /> via mail</span></div><div id="subscribeCommentsMail" style="display: none; margin: 5px 0 0 0; clear: both; padding: 0;"><input type="text" value="your@email and Enter" style="border: 1px solid #808080; margin: 0; font-size: 10px; color: #808080; padding: 2px; background-image: url(mailInvalid.png); background-position: center right; background-repeat: no-repeat;" onfocus="this.value=\'\';" onkeyup="checkEmail(this);" /></div></td></tr></table>';

	var SearchResults = '<!-- Search Results --><div style="position: fixed; bottom: 100px; left: 56%; display: none; background-color: white; border: 1px solid #808080; z-index: 101; -webkit-border-radius: 5px;" id="searchInterface"><div id="searchResults"> </div><div style="clear: both; margin: 0; padding: 1px;"><input type="text" value="Enter a keyword" id="searchEnter" style="border: none; float: left;" onfocus="this.value=\'\';" onkeyup="getSearchResults();" /><img src="'+myThemePath+'load.gif" id="searchLoad" style="visibility: hidden; display: inline; margin: 3px 3px -3px 3px;" alt="" /></div></div>';

	var About = '<!-- About --><table id="about" class="tabletype" style="bottom:0; left:0;"><tr><td style="padding: 5px; text-align: center;"> About <div class="navibutton" style="background-position-x: -70px; width: 10px; height: 10px; float: right; margin: 2px;" onclick="showElement(\'about\');"></div></td></tr><tr><td style="padding: 8px; vertical-align: top; border-top: 1px solid #808080;"> This Blog-Theme is a trial. My intention was to create a theme that is so damn stuffed with JavaScript that every single element is loaded dynamically. When you open this site, there\'s nothing but space between the &lt;body&gt;-Tags. Furthermore I wanted to abolish needless site views: You don\'t need to leave the site - the posts are loaded in something that looks and behaves like a window on your desktop (but in fact isn\'t). I also added a browser-like thing for external sites. So this website has the nature of an operating system. Somehow. However, you can download all files and edit them if you want to.</td></tr></table>';

	var Alert = '<!-- Alert --><table id="alert" class="tabletype" style="bottom:0; left:0;"><tr><td style="padding: 5px; text-align: center;"> Alert <div class="navibutton" style="background-position-x: -70px; width: 10px; height: 10px; float: right; margin: 2px;" onclick="showElement(\'alert\');"></div></td></tr><tr><td id="alertMsg">	Currently No Message.	</td></tr></table>';

	var Laden = '<!-- Laden --><div id="laden" style="position: fixed; left: 100px; top: 100px; width: 260px; height: 100px; display: none; background-color: white; z-index: 200; padding: 10px; border: 1px solid #808080; color: #808080; -webkit-border-radius: 10px; -webkit-box-shadow: 1px 5px 25px #C0C0C0;"><div style="margin: 43px 30px; height: 14px;"> <img src="'+myThemePath+'load.gif" alt="" style="margin: 2px 3px -2px 0;" /> Laden... </div></div>';

	var containEverything = '<div id="containEverything">' + front + subscribe + SearchResults + About + Alert + Laden + '</div>';

	document.body.innerHTML = containEverything;
}

function place(id, hPercent, vPercent) {
	var obj = fobj(id);
	var objStyle = obj.style;
	var width, height;
	(obj.offsetWidth!=0)?(width=obj.offsetWidth, height=obj.offsetHeight):(width=parseInt(obj.style.width), height=parseInt(obj.style.height))
	var leftRight = ( (window.innerWidth - width) * (hPercent/100) ) + "px";
	if(objStyle['left']) {
	obj.style.left = leftRight;
	} else {
	obj.style.right = leftRight;
	}
	if(objStyle['top']) {
	obj.style.top = ( (window.innerHeight - 100 - height) * (vPercent/100) ) + "px";
	} else {
	obj.style.bottom = ( (window.innerHeight - 100 - height) * (vPercent/100) + 100) + "px";
	}
}


function catchLinks() {
	$('a').each(function() {
		var obj = this;
		var href = $(obj).attr("href");
		var target = $(obj).attr("target");
		var name = $(obj).attr("name");
		var title = $(obj).attr("title");
		var id = $(obj).attr("id");
		var classAttr = $(obj).attr("class");
		if(!title) title=href;
		var oriStyle = obj.style; // "ori" stands for "original"... 
		if(oriStyle.length>0) {
			var styleString = ' style="';
			for(var i=0; i<oriStyle.length; ++i) {
				styleString = styleString + oriStyle[i] + ": " + oriStyle[oriStyle[i]] + ";";
			}
			styleString = styleString + '"';
		}
		var linkValue = obj.innerHTML;
		var spanLink = '<span class="linklike '+classAttr+'"';
		if(id) spanLink = spanLink + ' id="'+id+'"';
		if(styleString) spanLink = spanLink + styleString;
		if(href) {
			if( href.search(myDomainSearch)!=-1 || href.search(/^\//)!=-1) {
				var PostID = href.substr(href.search(/\?p=/)+3);
				if(typeof parseInt(PostID)!='number') PostID.substr(0, indexOf('&'));
				title=myDomain+'?post='+PostID;
				spanLink = spanLink+' onclick="openLink('+PostID;
			} else {
				spanLink = spanLink+" onclick=\"launchBrowser('"+href+"'";
			}

			if(target && target=='_blank') {
				spanLink = spanLink+', \'blank\');"';
			} else if(target && target=='_self') {
				spanLink = spanLink+', \'self\', \'';
				var objParent = obj;
				while(objParent.parentNode) {
					var parentId = $(objParent.parentNode).attr("id");
					if(parentId && parentId.search(/fenster/)!=-1) {
					  spanLink = spanLink+parentId+'\');"';
					  break;
					}
					objParent = objParent.parentNode;
				}
				if(!parentId) spanLink = spanLink+'\');"';
			} else {
				spanLink = spanLink+');"';
			}
		}
		if(name) spanLink = spanLink+' name="'+name+'"';
		spanLink = spanLink+' title="'+title+'"';
		spanLink = spanLink+'>'+linkValue+'</span>';
		$(obj).replaceWith(spanLink);
	});
}



function myAlert(msg) {
	fobj('alertMsg').innerHTML = msg;
	if(fstyle('alert').display != 'block') showElement('alert', 'place');
}



function getSearchResults() {
   var searchRequest = fobj('searchEnter').value;
   if(searchRequest) {
	if(fstyle('searchLoad').visibility!='visible') fstyle('searchLoad').visibility = 'visible';
	$('#searchResults').load(myDomain+'?s='+searchRequest+' #Results', function() {
		fstyle('searchLoad').visibility = 'hidden';
	});
   }

}

function changeContent(PostID, id) {
  if(!PostID) {myAlert("No further Posts in that direction");}
  else {
  if(fobj('fenster'+PostID)) {
	makeFocus('fenster'+PostID);
	myAlert("The Post is already open!");
  } else {
	actualID = id.substr(7);
	var content = fobj('content'+actualID);
	content.style.verticalAlign = 'middle';
	content.style.textAlign = 'center';
	content.innerHTML = '<img src="'+myThemePath+'load.gif" alt="" />';
	$.get(myDomain+"?p="+PostID+"&title=only", function(getTitleValue) {
		var top, left, width, height;
		var obj = fobj(id);
		top = parseInt(obj.style.top);
		left = parseInt(obj.style.left);
		height = parseInt(obj.style.height);
		width = parseInt(obj.style.width);
		var key = BackTie[id];
		Post[key]['ID'] = "fenster"+PostID;
		Post[key]['title'] = getTitleValue;
		//update BackTie
		for (var i = 0; i < Post.length; ++i) {
			var ObjectIndex=Post[i]['ID'];
			BackTie[ObjectIndex]=i;
		}
		fobj('containing'+actualID).id = 'containing'+PostID;
		if( fstyle('PostOverview').display!='none' ) DisplayPostOverview('update');
		current[0] = 'fenster'+PostID;
		current[1]++;
		$("#containing"+PostID).load(myDomain+"?width="+width+"&height="+height+"&top="+top+"&left="+left+"&zindex="+current[1]+"&p="+PostID+" #fenster"+PostID, function() {
			catchLinks();
		});
	});
  }
  }
}


function openLink(PostID, target, id) {
	if(!parseInt(PostID)) return;
	(target=='self'&&id)?changeContent(PostID, id):launchWindow(PostID);
}


function closeWindow(id, empty) {
	$("#"+id).fadeOut("slow");
	if(!empty) {
	Post.splice(BackTie[id], 1);
	//update BackTie
	for (var i = 0; i < Post.length; ++i) {
		var ObjectIndex=Post[i]['ID'];
		BackTie[ObjectIndex]=i;
	}
	if(Post.length>0) {Display[0].nodeValue = Post.length;} else {Display[0].nodeValue = '';}
	}
	window.setTimeout(function() {
		var obj = fobj(id).parentNode;
		while (obj.firstChild) {
		  obj.removeChild(obj.firstChild);
		}
	}, 300);
	if( fstyle('PostOverview').display!='none' ) DisplayPostOverview('update');
}

function makeFocus(id) {
	var SiteObj = getSiteType(id);
	if(SiteObj['state']=='minimized' && !SiteObj['URL']) toggleMaxiMini(id);
	if(id != current[0] || !current[0]) {
	  fstyle(id).zIndex=current[1]+1;
	  current[0]=id;
	  current[1]++;
	}
}


function toggleMaxiMini(id) {
	var SiteObj = getSiteType(id);
	var state = SiteObj['state'];
	var jQueryID = "#"+id;
	if(state=='minimized') {
		SiteObj['state'] = 'maximized';
		$(jQueryID).fadeIn("slow");
	} else {
		SiteObj['state'] = 'minimized';
		$(jQueryID).fadeOut("slow");
	}
	if( fstyle('PostOverview').display!='none' && !SiteObj['URL']) DisplayPostOverview('update');
	if( fstyle('ExternalOverviewWrapper').display!='none' && SiteObj['URL']) DisplayExternalOverview('update');
}


function showElement(id, further) {
	if(further=='justIn') {
		$('#'+id).animate({opacity: "show", height: "show"});
	} else if(further=='justOut') {
		$('#'+id).animate({opacity: "hide", height: "hide"});
	} else {
		$('#'+id).animate({opacity: "toggle", height: "toggle"});
	}
	if(further=='place' && fstyle(id).display != 'block') place(id, 50, 50);
}


function DisplayPostOverview(update) {
  if(update) {
     var obj = fobj('PostOverview');
     while (obj.firstChild) {
       obj.removeChild(obj.firstChild);
     }
  }
  if(fstyle('PostOverview').display=='none' || update) {
	var MiniMaxi1 = '<div class="navibutton" onclick="toggleMaxiMini(';
	var MiniMaxi2 = ');" style="background-position-x: ';
	var maximizedHTML = '<div class="navibutton" style="background-position-x: -105px"></div>';
	var closeHTML = '<div class="navibutton" style="background-position-x: -70px" onclick="closeWindow(';
	var MiniMaxi, state, title, id, number, colspanOrNot;
    if(Post.length>0) {
	for (var i = 0; i < Post.length; ++i) {
		state = Post[i]['state'];
		title = Post[i]['title'];
		if(title.length > 35) title = title.substr(0, 30) + '...';
		id = "'"+Post[i]['ID']+"'";
		number = i + 1;
		if(state=='minimized') {MiniMaxi = MiniMaxi1 + id + MiniMaxi2 + '-105px" id="MiniMaxi' + i + '"></div>';}
		else {MiniMaxi = MiniMaxi1 + id + MiniMaxi2 + '-51px" id="MiniMaxi' + i + '"></div>';}
		var linkedClose = closeHTML+id+');"></div>';
		var newtr = document.createElement("tr");
		newtr.innerHTML = '<td class="overviewTd1"><span class="zaehler">'+number+'</span></td><td onclick="makeFocus('+id+')\;" class="overviewTd2">'+title+'</td><td class="overviewnavi">'+ MiniMaxi +'</td><td class="overviewnavi">'+ linkedClose +'</td>';
		fobj('PostOverview').appendChild(newtr);
		colspanOrNot =  'colspan="4"';
	}
    } else {
		var newtr = document.createElement("tr");
		newtr.innerHTML = '<td class="overviewTd1">No open Posts or Pages</td>';
		fobj('PostOverview').appendChild(newtr);
    }
	var newtr = document.createElement("tr");
	newtr.innerHTML='<td class="overviewTd1" '+colspanOrNot+'><input type="text" id="ManualPostCall" value="Enter Post ID" onfocus="this.value=\'\';" onkeyup="ManualPostCall();" /></td>';
	fobj('PostOverview').appendChild(newtr);
	showElement('PostOverview', 'justIn');
  } else {
	showElement('PostOverview', 'justOut');
	window.setTimeout(function() {
	   var obj = fobj('PostOverview');
	   while (obj.firstChild) {
	     obj.removeChild(obj.firstChild);
	   }
	}, 500);
  }
}

function ManualPostCall() {
	var PostID = parseInt(fobj('ManualPostCall').value);
	if(window.event.keyCode==13)
		if(!PostID) {myAlert("Enter a Post ID");} else {launchWindow(PostID);}
}

function checkEmail(obj) {
	if(obj.value.match(/^([a-zA-Z0-9\-\.\_]+)(\@)([a-zA-Z0-9\-\.]+)(\.)([a-zA-Z]{2,4})$/)) {
		obj.style.BackgroundImage='url('+myThemePath+'mailValid.png)';
		return true;
	} else {
		obj.style.BackgroundImage='url('+myThemePath+'mailInvalid.png)';
		return false;
	}
	//thx to drweb.de for the RegEx
	//I'm so bad in RegEx I had to google for it
	//here you can read their article: http://www.drweb.de/magazin/falsch-oder-echt-email-check-mit-javascript/
}



function launchWindow(PostID, page, callback) {
	if(typeof page=='function') {callback=page; page=false;}

 // Gucken, ob Fenster womoeglich schon offen ist
 // Check if window is already opened - if so, get it focussed so that the user notices it
 if(fobj('fenster'+PostID) && !callback) {
	makeFocus('fenster'+PostID);
 } else if(fobj('fenster'+PostID) && callback && typeof callback=='function') {
	callback(fobj('fenster'+PostID));
 } else {
	// Fensterinhalt-Rohling wird erzeugt
	current[0]='fenster'+PostID;
	current[1]=current[1]+1;
	current[2]=(current[2]==window.innerHeight-300)?50:current[2]+15;
	current[3]=(current[3]==window.innerHeight-300)?50:current[3]+15;

	//Tabelle wird erzeugt 
	//vor und zurueck Pfeile
	var naviTable = '<table class="tabletype fenster-navi-links"><tr><td><div style="background-position-x: -1px;" class="navibutton navipfeil"></div></td><td><div style="background-position-x: -27px;" class="navibutton navipfeil"></div></td></tr></table>';
	//minimieren und schliessen Pfeile
	var closeTable = '<table style="width: 28px; height: 10px; margin: 1px; border: none;" class="tabletype"><tr><td><div style="width: 10px; height: 10px; background-position-x: -51px;" class="navibutton"></div></td><td><div style="width: 10px; height: 10px; background-position-x: -70px;" class="navibutton"></div></td></tr></table>';
	//erste Zeile (tr)
	var tr1 = '<tr><td class="fenster-menu fenster-links">'+naviTable+'</td><td class="fenster-menu fenster-oben" style="text-align: center; color: #707070; cursor: move;">Bitte warten...</td><td class="fenster-menu fenster-oben" style="width: 30px;">'+closeTable+'</td></tr>';
	//zweite Zeile
	var tr2 = '<tr><td class="fenster-inhalt" style="vertical-align: middle; text-align: center;" colspan="3"><img src="'+myThemePath+'load.gif" alt=""/></td></tr>';
	//dritte Zeile
	var tr3 = '<tr><td class="fenster-menu fenster-unten" colspan="2"></td><td class="fenster-menu fenster-unten resize"><div class="navibutton resize"></div></td></tr>';
	//komplette Tabelle, in der alles gerade definierte zusammengefuegt wird
	var completeTable = '<table id="fenster'+PostID+'" style="top: '+current[2]+'px; left: '+current[3]+'px; width: 300px; height: 200px; z-index: '+current[1]+'; display: none;" class="fenster"><tbody>'+tr1+tr2+tr3+'</tbody></table>';


	if(!fobj('containing'+PostID)) {
		// eigentliches Fenster wird erzeugt
		var newWindow = document.createElement("div");
		var divID = document.createAttribute("id");
		divID.nodeValue = "containing"+PostID;
		newWindow.setAttributeNode(divID);
	} else {
		var newWindow =	fobj('containing'+PostID);
	}
	//die oben definierte Tabelle wird nun in das Div verfrachtet
	newWindow.innerHTML = completeTable;
	fobj('middle').appendChild(newWindow);
	$("#fenster"+PostID).fadeIn();
	var PagePost = 'p';
	if(page) PagePost = 'page_id';
	$.get(myDomain+"?"+PagePost+"="+PostID+"&title=only", function(getTitleValue) {
	    if(getTitleValue && getTitleValue.search(/Es wurde leider kein passender Beitrag gefunden/)==-1) {
		$("#containing"+PostID).load(myDomain+"?width=300&height=200&left="+current[3]+"&top="+current[2]+"&zindex="+current[1]+"&"+PagePost+"="+PostID+" #fenster"+PostID, function() {
			if(!fobj('containing'+PostID).innerHTML) {(!page)?(myAlert("Please wait a moment. The post you requested may be a page."), launchWindow(PostID, 'page')):(myAlert("The post or page you requested seems to be unavailable.")) } else {
		var Postlength = Post.length;
		var newPost = new Object();
		newPost['ID'] = "fenster"+PostID;
		newPost['title'] = getTitleValue;
		newPost['state'] = 'maximized';
		Post[Postlength] = new Object(newPost);
		Display[0].nodeValue = Post.length;
		BackTie["fenster"+PostID] = Postlength;
		if( fstyle('PostOverview').display!='none' ) DisplayPostOverview('update');
		catchLinks();
		if(callback && typeof callback == 'function') callback(fobj('fenster'+PostID));
			}
		});
	    } else {myAlert("The Post you requested seems to be unavailable or doesn't exist at all."); closeWindow('fenster'+PostID, 'empty');}
	});
 }
}

function fenster(action, id) {
  var eve = window.event;
  var obj = fobj(id);

  //Definitionen
  var abx, aby, minX, minY, maxX, maxY;

  if (action == 'move') {
	abx = eve.clientX - parseInt(obj.style.left);
	aby = eve.clientY - parseInt(obj.style.top);
	maxX = window.innerWidth - parseInt(obj.style.width);
	maxY = window.innerHeight - parseInt(obj.style.height);
	minX = 0;
	minY = 0;
  } else if (action == 'resize') {
	abx = eve.clientX - parseInt(obj.style.width);
	aby = eve.clientY - parseInt(obj.style.height);
	maxX = window.innerWidth - parseInt(obj.style.left);
	maxY = window.innerHeight - parseInt(obj.style.top) - 100;
	minX = 250;
	minY = 200;
  }

  var stop, newX, newY, finX, finY, actionX, actionY;

  action=='move'?(actionX='left', actionY='top'):(actionX='width', actionY='height')

  function execute(eve) { if(!stop) {
			newX = eve.clientX - abx;
			newY = eve.clientY - aby;
				newX>minX?(newX<maxX?finX=newX+"px":finX=maxX+"px"):(finX=minX+"px")
				newY>minY?(newY<maxY?finY=newY+"px":finY=maxY+"px"):(finY=minY+"px")
			obj.style[actionX]=finX;
			obj.style[actionY]=finY;
			} }
  function hold() { stop=1; document.onmousemove=''; document.onmouseup='';}

  document.onmousemove = execute;
  document.onmouseup = hold;
}





//--------- Hier kommt jetzt der Abschnitt fuer die External-windows
//--------- This is the section about External-windows


function launchBrowser(URL, callback) {
	var Browser = External.length;
	if(!URL) URL=homeSite;

	// Fensterinhalt-Rohling wird erzeugt
	current[0]='Browser'+Browser;
	current[1]=current[1]+1;
	current[2]=(current[2]==window.innerHeight-300)?50:current[2]+15;
	current[3]=(current[3]==window.innerHeight-300)?50:current[3]+15;

	//Tabelle wird erzeugt 
	//vor und zurueck Pfeile
	var naviTable = '<table class="tabletype fenster-navi-links"><tr><td><div style="background-position-x: -1px;" class="navibutton navipfeil" onclick="jumpInHistory(\'Browser'+Browser+'\', \'backwards\');"></div></td><td><div style="background-position-x: -27px;" class="navibutton navipfeil" onclick="jumpInHistory(\'Browser'+Browser+'\', \'forward\');"></div></td></tr></table>';
	//minimieren und schliessen Pfeile
	var closeTable = '<table style="width: 28px; height: 10px; margin: 1px; border: none;" class="tabletype"><tr><td><div style="width: 10px; height: 10px; background-position-x: -51px;" class="navibutton" onclick="toggleMaxiMini(\'Browser'+Browser+'\');"></div></td><td><div style="width: 10px; height: 10px; background-position-x: -70px;" class="navibutton" onclick="closeBrowser(\'Browser'+Browser+'\');"></div></td></tr></table>';
	//erste Zeile (tr)
	var tr1 = '<tr><td class="fenster-menu fenster-links">'+naviTable+'</td><td class="fenster-menu fenster-oben" style="text-align: center; color: #707070; cursor: move;" onmousedown="fenster(\'move\', \'Browser'+Browser+'\');"><span id="BrowserTitle'+Browser+'"> </span></td><td class="fenster-menu fenster-oben" style="width: 30px;">'+closeTable+'</td></tr>';
	//zweite Zeile
	var tr2 = '<tr><td class="fenster-inhalt" colspan="3"><iframe src="'+URL+'" name="BrowserName'+Browser+'" style="width: 100%; height: 100%; border: none; margin:0;" onmousedown="myAlert(\'Blubb\');"></iframe></td></tr>';
	//dritte Zeile
	var tr3 = '<tr><td class="fenster-menu fenster-unten" colspan="2"><input type="text" value="http://www.google.de" id="BrowserInput'+Browser+'" style="width: 100%; height: 100%; border: none; margin: 0; padding: 2px;" onkeyup="openWebsite(\'Browser'+Browser+'\');" /></td><td class="fenster-menu fenster-unten resize"><div class="navibutton resize" onmousedown="fenster(\'resize\', \'Browser'+Browser+'\');"></div></td></tr>';
	//komplette Tabelle, in der alles gerade definierte zusammengefuegt wird
	var completeTable = '<table id="Browser'+Browser+'" style="top: '+current[2]+'px; left: '+current[3]+'px; width: 670px; height: 400px; z-index: '+current[1]+'; display: none;" class="fenster" onmousedown="makeFocus(\'Browser'+Browser+'\');"><tbody>'+tr1+tr2+tr3+'</tbody></table>';

	// eigentliches Fenster wird erzeugt
	var newWindow = document.createElement("div");
	newWindow.innerHTML = completeTable;
	fobj('middle').appendChild(newWindow);
	$("#Browser"+Browser).fadeIn();
	fobj('BrowserInput'+Browser).value = parent['BrowserName'+Browser].location.href;

	var newBrowser = new Object();
	newBrowser['ID'] = "Browser"+Browser;
	newBrowser['state'] = 'maximized';
	newBrowser['URL'] = URL; //the currently opened URL
	newBrowser['history'] = new Array();
	newBrowser['history'][0] = URL;
	newBrowser['historyLocation'] = 0; //the Arraykey for 'history'
	newBrowser['titleObj'] = fobj('BrowserTitle'+Browser).firstChild;
	newBrowser['urlObj'] = fobj('BrowserInput'+Browser);
	newBrowser['urlObj'].value = URL;
	newBrowser['frameObj'] = parent['BrowserName'+Browser];
	newBrowser['title'] = '';
	External[Browser] = new Object(newBrowser);
	Display[1].nodeValue = External.length;
	BackTieExternal["Browser"+Browser] = Browser;
	getWebsiteData('Browser'+Browser);
	if(callback && typeof callback == 'function') callback(fobj('Browser'+Browser));
	if (document.addEventListener) {
		parent.frames[Browser].addEventListener("click", catchWebsiteData);
	} else if(NS4) {
		parent.frames[Browser].document.captureEvents(Event.CLICK);
		parent.frames[Browser].document.onclick = catchWebsiteData;
	} else {
		parent.frames[Browser].document.body.onclick = catchWebsiteData;
	}
}




// I don't really know why
// but these addEventListener and captureEvents and so on don't work!
// So this is to automatically update all the Externalsite-windows every second
window.setInterval("catchWebsiteData()", 1000);

function catchWebsiteData() {
	if(External && External.length>0) { 
	  for(var i=0; i<External.length; ++i) {
		if(External[i]['URL']!=External[i]['frameObj'].location.href) getWebsiteData(i);
	  }
	}
}




function openWebsite(id) {
	var ArrayKey = BackTieExternal[id];
	var entered = External[ArrayKey]['urlObj'].value;
	if(window.event.keyCode==13 && entered.search(/^(https?:\/\/)?([a-zA-Z0-9\-\.\_]+(\.))*[a-zA-Z0-9\-\.\_]+(\.)([a-zA-Z]{2,4})/)!=-1) {
		var URL=entered;
		if(entered.search(/^(https?:\/\/)/)==-1) URL='http://'+entered;
		changeBrowserContent(ArrayKey, URL);
	}
}

function changeBrowserContent(key, URL) {
	External[key]['frameObj'].location.href = URL;
	External[key]['frameObj'].onload = getWebsiteData(key);
	$(External[key]['frameObj'].document).ready("getWebsiteData(key)");
}

function getWebsiteData(keyOrID) {
	var ArrayKey = parseInt(keyOrID);
	if(typeof ArrayKey!='number') ArrayKey = BackTieExternal[keyOrID]; // if "key" is actually an "id" - so you can pass the key or the id, the function takes both
	window.setTimeout(function() {
	   var currentURL = External[ArrayKey]['frameObj'].location.href;
	   var currentTitle = External[ArrayKey]['frameObj'].document.title;
	   External[ArrayKey]['titleObj'].nodeValue = currentTitle;						//title
	   External[ArrayKey]['title'] = currentTitle
	   if(currentURL != External[ArrayKey]['URL'] && External[ArrayKey]['history'].length==External[ArrayKey]['historyLocation']+1) {
	   External[ArrayKey]['historyLocation']++;								//historyLocation
	   External[ArrayKey]['history'][External[ArrayKey]['historyLocation']] = currentURL;			//history
	   External[ArrayKey]['urlObj'].value = currentURL;							//url
	   }
	   External[ArrayKey]['URL'] = currentURL;								//URL
	   if( fstyle('ExternalOverviewWrapper').display!='none' ) DisplayExternalOverview('update');
	}, 800);
}


function jumpInHistory(id, direction) {
	var ArrayKey = BackTieExternal[id];
	var historyLength = External[ArrayKey]['history'].length;
	var historyLocation =  External[ArrayKey]['historyLocation'];
	var URL;
	if(direction=='forward' && historyLength!=historyLocation+1) {
		historyLocation++;
		External[ArrayKey]['historyLocation'] = historyLocation;
		URL=External[ArrayKey]['history'][historyLocation];
	} else if(direction=='backwards' && historyLocation!=0) {
		historyLocation--;
		External[ArrayKey]['historyLocation'] = historyLocation;
		URL=External[ArrayKey]['history'][historyLocation];
	} else {
		myAlert("The window's history ends here.");
		return;
	}
	changeBrowserContent(ArrayKey, URL);
	External[ArrayKey]['urlObj'].value = URL;
}


function DisplayExternalOverview(update) {
  if(update) {
     var obj = fobj('ExternalOverview');
     while (obj.firstChild) {
       obj.removeChild(obj.firstChild);
     }
  }
  if(fstyle('ExternalOverviewWrapper').display=='none' || update) {
	var MiniMaxi1 = '<div class="navibutton" onclick="toggleMaxiMini(';
	var MiniMaxi2 = ');" style="background-position-x: ';
	var maximizedHTML = '<div class="navibutton" style="background-position-x: -105px"></div>';
	var closeHTML = '<div class="navibutton" style="background-position-x: -70px" onclick="closeBrowser(';
	var MiniMaxi, state, title, id, number, colspanOrNot;
    if(External.length>0) {
	for (var i = 0; i < External.length; ++i) {
		state = External[i]['state'];
		title = External[i]['title'];
		if(title.length > 35) title = title.substr(0, 30) + '...';
		id = "'"+External[i]['ID']+"'";
		number = i + 1;
		if(state=='minimized') {MiniMaxi = MiniMaxi1 + id + MiniMaxi2 + '-105px" id="MiniMaxi' + i + '"></div>';}
		else {MiniMaxi = MiniMaxi1 + id + MiniMaxi2 + '-51px" id="MiniMaxi' + i + '"></div>';}
		var linkedClose = closeHTML+id+');"></div>';
		var newtr = document.createElement("tr");
		newtr.innerHTML = '<td class="overviewTd1"><span class="zaehler">'+number+'</span></td><td onclick="makeFocus('+id+')\;" class="overviewTd2">'+title+'</td><td class="overviewnavi">'+ MiniMaxi +'</td><td class="overviewnavi">'+ linkedClose +'</td>';
		fobj('ExternalOverview').appendChild(newtr);
		colspanOrNot =  'colspan="4"';
	}
    } else {
		var newtr = document.createElement("tr");
		newtr.innerHTML = '<td class="overviewTd1">No open Websites</td>';
		fobj('ExternalOverview').appendChild(newtr);
    }
	showElement('ExternalOverviewWrapper', 'justIn');
  } else {
	showElement('ExternalOverviewWrapper', 'justOut');
	window.setTimeout(function() {
	   var obj = fobj('ExternalOverview');
	   while (obj.firstChild) {
	     obj.removeChild(obj.firstChild);
	   }
	}, 500);
  }
}


function ManualWebsiteCall() {
	var entered = fobj('ManualWebsiteCall').value;
	if(window.event.keyCode==13 && entered.search(/^(https?:\/\/)?([a-zA-Z0-9\-\.\_]+(\.))*[a-zA-Z0-9\-\.\_]+(\.)([a-zA-Z]{2,4})/)!=-1) {
		var URL=entered;
		if(entered.search(/^(https?:\/\/)/)==-1) URL='http://'+entered;
		launchBrowser(URL);
	} else if(window.event.keyCode==13 && entered.search(/^(https?:\/\/)?([a-zA-Z0-9\-\.\_]+(\.))*[a-zA-Z0-9\-\.\_]+(\.)([a-zA-Z]{2,4})/)==-1) {
		launchBrowser('http://www.google.de/search?q='+entered);
	}
}



function closeBrowser(id) {
	$("#"+id).fadeOut("slow");
	External.splice(BackTieExternal[id], 1);
	//update BackTieExternal
	for (var i = 0; i < External.length; ++i) {
		var ObjectIndex=External[i]['ID'];
		BackTieExternal[ObjectIndex]=i;
	}
	if(External.length>0) {Display[1].nodeValue = External.length;} else {Display[1].nodeValue = '';}
	window.setTimeout(function() {
		var obj = fobj(id).parentNode;
		while (obj.firstChild) {
		  obj.removeChild(obj.firstChild);
		}
	}, 300);
	if( fstyle('ExternalOverviewWrapper').display!='none' ) DisplayExternalOverview('update');
}


function getSiteType(id) {
	  var SiteObj = Post[BackTie[id]];
	  if(!SiteObj) SiteObj = External[BackTieExternal[id]];
	  return(SiteObj);
}


//Saves all Data about the windows into a cookie
$(window).unload(function() {
	var now = new Date();
	var nowToString = new Date(now.getTime()).toLocaleString();
	//if there's already a cookie - delete it
	//Already set cookies aren't problematic actually, but deletion is safer
	if(document.cookie) {
	var deleted = new Date(now.getTime() -1234567890); // 14.3 hours ago the cookie expired
	document.cookie = "deleted=cookie; expires=" + deleted.toGMTString() + ";";
	}
	// Now the actual cookie will be created...
 
	// As far as I know cookies are Strings and not Arrays - that makes everything more complicated
	var Cookie = "[0]";
	for(var i=0; i<Post.length; i++) {
		var obj = fobj(Post[i]['ID']);
		var PostID = Post[i]['ID'].substr(7);
		Cookie = Cookie + "$" + PostID + "%" + obj.style.top + "%" + obj.style.left + "%" + obj.style.width + "%" + obj.style.height + "%" + obj.style.zIndex + "%" + Post[i]['state'];
	}
	Cookie = Cookie + "[1]";
	for(var i=0; i<External.length; i++) {
		var obj = fobj(External[i]['ID']);
		Cookie = Cookie + "$" + External[i]['URL'] + "%" + obj.style.top + "%" + obj.style.left + "%" + obj.style.width + "%" + obj.style.height + "%" + obj.style.zIndex + "%" + External[i]['state'];
	}
	var decaysAt = new Date(now.getTime() +1000*60*60*7*8);
	document.cookie = 'savedData='+ nowToString + Cookie + '[2]; expires='+decaysAt.toGMTString()+';';

});


function reloadOldPage(PostData, ExternalData) {
	if(PostData.length>0 || ExternalData.length>0)
	myAlert('Please wait while windows are loading <img src="'+myThemePath+'load.gif" alt="" style="margin: 2px 0 -2px 5px;" />');
	if(ExternalData.length>0)
	for(var i=0; i<ExternalData.length; i++) {
		launchBrowser(ExternalData[i][0], function(obj) {
			obj.style.top = ExternalData[i][1];
			obj.style.left = ExternalData[i][2];
			obj.style.width = ExternalData[i][3];
			obj.style.height = ExternalData[i][4];
			if(ExternalData[i][6]=='minimized') toggleMaxiMini(obj.id);
		});
	}
	if(PostData.length>0) {
		launchNextWindow(parseInt(PostData[0][0]), 0, PostData);
	} else {
		showElement('alert');
	}
}


function launchNextWindow(PostID, i, PostData) {
	launchWindow(PostData[i][0], false, function(obj) {
		obj.style.top = PostData[i][1];
		obj.style.left = PostData[i][2];
		obj.style.width = PostData[i][3];
		obj.style.height = PostData[i][4];
		if(PostData[i][6]=='minimized') toggleMaxiMini(obj.id);
		if(i+1<PostData.length) {
			launchNextWindow(parseInt(PostData[i+1][0]), i+1, PostData);
		} else {
			showElement('alert');
		}
	});
}