var form = 'post';
var textarea = 'message';

/* credits: Torsten Anacker 		*
 * fügt dem markierten Text aTag	*
 * an den Anfang an und ans Ende	*
 * eTag								*/
 
function AddTag(aTag, eTag, cTag) {
	var input = document.forms[form].elements[textarea];
	input.focus();
	/* für Internet Explorer */
	if(typeof document.selection != 'undefined') {
		/* Einfügen des Formatierungscodes */
		var range = document.selection.createRange();
		if(cTag == '') var insText = range.text;
		else insText = cTag;
		range.text = aTag + insText + eTag;
		/* Anpassen der Cursorposition */
		range = document.selection.createRange();
		if (insText.length == 0) {
			range.move('character', -eTag.length);
		}
		else {
			range.moveStart('character', aTag.length + insText.length + eTag.length);      
		}
		range.select();
	}
	/* für neuere auf Gecko basierende Browser */
	else if(typeof input.selectionStart != 'undefined') {
		/* Einfügen des Formatierungscodes */
		var start = input.selectionStart;
		var end = input.selectionEnd;
		if(cTag == '') var insText = input.value.substring(start, end);
		else insText = cTag;
		input.value = input.value.substr(0, start) + aTag + insText + eTag + input.value.substr(end);
		/* Anpassen der Cursorposition */
		var pos;
		if (insText.length == 0) {
			pos = start + aTag.length;
		} 
		else {
			pos = start + aTag.length + insText.length + eTag.length;
		}
		input.selectionStart = pos;
		input.selectionEnd = pos;
	}
	/* für die übrigen Browser */
	else {
		/* Abfrage der Einfügeposition */
		var pos;
		var re = new RegExp('^[0-9]{0,3}$');
		while(!re.test(pos)) {
			pos = prompt("Einfügen an Position (0.." + input.value.length + "):", "0");
		}
		if(pos > input.value.length) {
			pos = input.value.length;
		}
		/* Einfügen des Formatierungscodes */
		if(cTag == '') var insText = prompt("Bitte geben Sie den zu formatierenden Text ein:");
		else insText = cTag;
		input.value = input.value.substr(0, pos) + aTag + insText + eTag + input.value.substr(pos);
	}
}

// fügt den [IMG] tag hinzu
function AddImg() {
	inserttext = prompt("Enter the URL to the Image:" + "\n[IMG]xxx[/IMG]", "http://");
	if((inserttext != "http://") && (inserttext != "") && (inserttext != null)) AddTag('[IMG]', '[/IMG]', inserttext);
}

// fügt den [yt] tag hinzu
function AddYt() {
	inserttext = prompt("Enter the Youtube.com Movie ID:" + "\n[yt]xxx[/yt] (Youtube.com ID)", "");
	if((inserttext != "") && (inserttext != null)) AddTag('[yt]', '[/yt]', inserttext);
}

// fügt den [st6_4:3] tag hinzu
function AddSt643() {
	inserttext = prompt("Enter the stage6.com Movie ID:" + "\n[st6_4:3]xxx[/st6_4:3] (Format 4:3 Stage6.com ID)", "");
	if((inserttext != "") && (inserttext != null)) AddTag('[st6_4:3]', '[/st6_4:3]', inserttext);
}

// fügt den [st6_16:9] tag hinzu
function AddSt6169() {
	inserttext = prompt("Enter the Stage6.com Movie ID:" + "\n[st6_16:9]xxx[/st6_16:9] (Format 16:9 Stage6.com ID)", "");
	if((inserttext != "") && (inserttext != null)) AddTag('[st6_16:9]', '[/st6_16:9]', inserttext);
}

// fügt den [flv] tag hinzu
function AddFlv() {
	inserttext = prompt("Enter the full flv address:", "");
	insertwidth = prompt("Enter the video width(max 600):", "");
	insertheight = prompt("Enter the video height(max 400):", "");
	if(insertwidth > 600) insertwidth=600;
	if(insertheight > 400) insertheight=400;
	if((inserttext != "") && (inserttext != null) && (insertwidth != "") && (insertwidth != null) && (insertheight != "") && (insertheight != null)) AddTag('[flv='+insertwidth+'x'+insertheight+']', '[/flv]', inserttext);
	else alert('Need all Infos, Please try again!');
}

// fügt den [divx] tag hinzu
function AddDivx() {
	inserttext = prompt("Enter the full DivX Video address:", "http://");
	insertthumb = prompt("Enter the full Preview Image address (.png, .jpg, .gif):", "http://");
	insertwidth = prompt("Enter the video WIDTH (max 600):\n 4:3 = 600x450\n16:9 = 600x337", "");
	insertheight = prompt("Enter the video HEIGHT (max 450):\n 4:3 = 600x450\n16:9 = 600x337", "");
	if(insertwidth > 600) insertwidth=600;
	if(insertheight > 450) insertheight=450;
	if((inserttext != "http://") && (inserttext != "") && (inserttext != null) && (insertthumb != "http://") && (insertthumb != "") && (insertthumb != null) && (insertwidth != "") && (insertwidth != null) && (insertheight != "") && (insertheight != null)){
	 	insert = inserttext+'thumb='+insertthumb+'width='+insertwidth+'height='+insertheight;
	  	AddTag('[divx]', '[/divx]', insert);
	  }	else alert('Need all Infos, Please try again!');
}

// fügt [URL] oder [EMAIL] ein
function AddLink(thetype) {
	linktext = prompt("Enter a Linkname (optional)", "");
	var prompttext;
	if(thetype == "URL") linkurl = prompt("Enter the URL", "http://");
	else linkurl = prompt("Enter the E-Mail Address", "");
	
	if((linkurl != "http://") && (linkurl != "") && (linkurl != null)) {
		if((linktext != null) && (linktext != "")) {
			AddTag("[" + thetype + "=" + linkurl + "]", "[/" + thetype + "]", linktext);
		}
		else {
			AddTag("[" + thetype + "]", "[/" + thetype + "]", linkurl);
		}
	}
}

// fügt eine HTML-Liste ein
function AddList() {
	type = prompt("enter '1' for a numbered List, 'a' for an alphabetic List or '' for a pointed List", "");
	if((type == "a") || (type == "1")) {
		list = "[LIST=" + type + "]\n";
		listend = "[/LIST=" + type + "]";
	}
	else {
		list = "[LIST]\n";
		listend = "[/LIST]";
	}
	entry = "start";
	while ((entry != "") && (entry != null)) {
		entry = prompt("Enter a List-Point. Enter nothing or click 'Cancel' to finish the list.", "");
		if ((entry != "") && (entry != null))
			list = list + "[*]" + entry + "[/*]\n";
	}
	addtext = list + listend;
	
	AddTag('', '', addtext);
}

// fügt code eines andern fensters ein
function AddCodeFromWindow(thecode) {
	var input = opener.document.forms[form].elements[textarea];
	input.focus();
	/* für Internet Explorer */
	if(typeof opener.document.selection != 'undefined') {
		/* Einfügen des Formatierungscodes */
		var range = opener.document.selection.createRange();
		range.text = thecode;
		/* Anpassen der Cursorposition */
		range = opener.document.selection.createRange();
		range.moveStart('character', thecode.length);      
		range.select();
	}
	/* für neuere auf Gecko basierende Browser */
	else if(typeof input.selectionStart != 'undefined') {
		/* Einfügen des Formatierungscodes */
		var start = input.selectionStart;
		var end = input.selectionEnd;
		input.value = input.value.substr(0, start) + thecode + input.value.substr(end);
		/* Anpassen der Cursorposition */
		var pos;
		pos = start + thecode.length;
		input.selectionStart = pos;
		input.selectionEnd = pos;
	}
	/* für die übrigen Browser */
	else {
		/* Abfrage der Einfügeposition */
		var pos;
		var re = new RegExp('^[0-9]{0,3}$');
		while(!re.test(pos)) {
			pos = prompt("Einfügen an Position (0.." + input.value.length + "):", "0");
		}
		if(pos > input.value.length) {
			pos = input.value.length;
		}
		/* Einfügen des Formatierungscodes */
		input.value = input.value.substr(0, pos) + thecode + input.value.substr(pos);
	}
}


// fügt den [B] tag hinzu
function AddB() {
	AddTag('[B]', '[/B]', '');
}
// fügt den [rating] tag hinzu
function AddRating() {
	AddTag('[rating]', '[/rating]', '');
}

// fügt den [U] tag hinzu
function AddU() {
	AddTag('[U]', '[/U]', '');
}
// fügt den [tm_col] tag hinzu
function AddTmcol() {
	AddTag('[tm_col]', '[/tm_col]', '');
}

// fügt den [I] tag hinzu
function AddI() {
	AddTag('[I]', '[/I]', '');
}

// fügt den [quote] tag hinzu
function AddQuote() {
	AddTag('[quote]', '[/quote]', '');
}

// fügt den [quote] tag hinzu
function AddCodetag() {
	AddTag('[code]', '[/code]', '');
}

// fügt den [Toggle] tag hinzu
function AddToggle() {
	inserttext = prompt("Enter toggle name:" + "\n[toggle=xxx][/toggle]");
	inserttext1 = prompt("Enter text:" + "\nxxxx");
	if((inserttext != "") && (inserttext1 != "") && (inserttext != null) && (inserttext1 != null)) AddTag("[toggle="+inserttext+"]", "[/toggle]", inserttext1);
}

// toggle funktion - read more
function Toggle(id) {

  spanid1 = "ToggleRow_"+id;
  spanid2 = "ToggleImg_"+id;
  val = document.getElementById(spanid1).style.display;
  if (val == "none")
  {
    document.getElementById(spanid1).style.display = "block";
    document.getElementById(spanid2).src = "images/icons/collapse.gif";
    document.getElementById(spanid2).alt = "read more";
  }
  else
  {
    document.getElementById(spanid1).style.display = "none";
    document.getElementById(spanid2).src = "images/icons/expand.gif"
    document.getElementById(spanid2).alt = "hide";
  }
}





// function addRow() ** this adds a new row to the table, containing mapname, mapresult_home, mapresult_opponent
function addRow(action)
{
	var theAction = action;
  var table = document.getElementById('maplist');
  var theRows = table.rows.length;
  var inkrement = theRows;
  var row = table.insertRow(theRows);
	
	// gibt nen text wie "map #1" aus
	var cell0 = row.insertCell(0);
	var textNode = document.createTextNode('map #' + inkrement);
	if(theAction=='edit') {
		var ele0 = document.createElement('input');
			ele0.setAttribute('type', 'hidden');
			ele0.setAttribute('name', 'map_id[]');
			ele0.setAttribute('value', inkrement);
		cell0.appendChild(ele0);
	}
	cell0.appendChild(textNode);
	// mapname
  var cell1 = row.insertCell(1);
  var ele1 = document.createElement('input');
		ele1.setAttribute('type', 'text');
		ele1.setAttribute('name', 'map_name[]');
		ele1.setAttribute('id', 'map_name_' + inkrement);
		ele1.setAttribute('size', '35');
		ele1.className='form_off';
  cell1.appendChild(ele1);
	// results: home
  var cell2 = row.insertCell(2);
  var ele2 = document.createElement('input');
		ele2.setAttribute('type', 'text');
		ele2.setAttribute('name', 'map_result_home[]');
		ele2.setAttribute('id', 'map_result_home_' + inkrement);
		ele2.setAttribute('size', '3');
		ele2.className='form_off';
	cell2.appendChild(ele2);
	// results: opponent
	var cell3 = row.insertCell(3);
	var ele3 = document.createElement('input');
		ele3.setAttribute('type', 'text');
		ele3.setAttribute('name', 'map_result_opp[]');
		ele3.setAttribute('id', 'map_result_opp_' + inkrement);
		ele3.setAttribute('size', '3');
		ele3.className='form_off';
	cell3.appendChild(ele3);
	// create delete-selection for edit-function
	if(theAction=='edit') {
		var cell4 = row.insertCell(4);
		var ele4 = document.createElement('input');
			ele4.setAttribute('type', 'checkbox');
			ele4.setAttribute('name', 'delete[]');
			ele4.setAttribute('value', inkrement);
			ele4.className='form_off';
		cell4.appendChild(ele4);
	} else {
		var cell4 = row.insertCell(4);
	}
}

// function removeRow() ** removes the last row of a table
function removeRow()
{
  var table = document.getElementById('maplist');
  var theRows = table.rows.length;
  if (theRows != 1) table.deleteRow(theRows - 1);
}

function MM_jumpMenu(targ,selObj,restore){ //v3.0
  eval(targ+".location='"+selObj.options[selObj.selectedIndex].value+"'");
  if (restore) selObj.selectedIndex=0;
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_jumpMenuGo(selName,targ,restore){ //v3.0
  var selObj = MM_findObj(selName); if (selObj) MM_jumpMenu(targ,selObj,restore);
}

function MM_confirm(msg, url) { //v1.0
  if(confirm(msg)) location.replace(url);
}

function MM_openBrWindow(theURL,winName,features) { 
  window.open(theURL,winName,features);
}

function MM_goToURL() { //v3.0
  var i, args=MM_goToURL.arguments; document.MM_returnValue = false;
  for (i=0; i<(args.length-1); i+=2) eval(args[i]+".location='"+args[i+1]+"'");
}

function SelectAll() {
	for(var x=0;x<document.form.elements.length;x++) {
		var y=document.form.elements[x];
		if(y.name!='ALL') y.checked=document.form.ALL.checked;
	}
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

function messageconfirm(messages) {
        if(confirm("You have "+messages+" new message(s). Do you want to read them now?"))
          document.location.href="index.php?site=messenger";
}

function checkSize(name, xmax, ymax) {

	var xsize, ysize;
  xsize=document.getElementById("ws_image_" + name).width;
  ysize=document.getElementById("ws_image_" + name).Height;

  if(ysize>ymax) {
  	document.getElementById("ws_image_" + name).height=ymax;
  	document.getElementById("ws_imagediv_" + name).style.display = "block";
  }

  if(xsize>xmax) {
  	document.getElementById("ws_image_" + name).width=xmax;
  	document.getElementById("ws_imagediv_" + name).style.display = "block";
  }

}
	
// tooltip
wmtt = null;

function updateWMTT(e) {
	x = (document.all) ? window.event.x + document.body.scrollLeft : e.pageX;
	y = (document.all) ? window.event.y + document.body.scrollTop  : e.pageY;
	if (wmtt != null) {
		wmtt.style.left = (x + 20) + "px";
		wmtt.style.top 	= (y -20) + "px";
	}
}

function showWMTT(id) {
	document.onmousemove = updateWMTT;
	wmtt = document.getElementById(id);
	wmtt.style.display = "block";
	wmtt.style.zIndex = 3000;
}

function hideWMTT() {
	wmtt.style.display = "none";
	document.onmousemove = "none";
}
//basic ajax request
function postRequest(strURL,id,action) {
  var xmlHttp;
  if (window.XMLHttpRequest) { // Mozilla, Safari, ...
    var xmlHttp = new XMLHttpRequest();
  }
  else if (window.ActiveXObject) { // IE
    var xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
  }
  xmlHttp.open('POST', strURL, true);
  xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  xmlHttp.onreadystatechange = function() {
    if (xmlHttp.readyState == 4) {
      updatepage(xmlHttp.responseText,id,action);
    }
  }
  xmlHttp.send(strURL);
}
function updatepage(str,id,action){
 	if (action == "add"){
    document.getElementById(id).innerHTML +=str;
 	}
 	else if (action == "replace"){
 		document.getElementById(id).innerHTML =str;
 	}
}
function eventfetch(url,id,action){
 	postRequest(url,id,action);
}
function timefetch(url,id,action,milliseconds) {
 	eventfetch(url,id,action)
  setTimeout(function () { timefetch(url,id,action,milliseconds); },milliseconds);
}
//generic fetch function, accepts 5 parameters (first 4 mandatory).
//url = script to access on the server
//id = html id (for example of a div, a form field etc.., works with all tags which accept an id)
//action = add or replace, add adds up content at the end of the original content in the id element, replace replaces the complete content in the id element
//base = time or event, time based means script will autoexecute itself every amount of milliseconds specified via the 5th (millisecdons) parameter, event based means you are calling the funtion with something like onclick, onchange, onmouseover etc....
//milliseconds = time in milliseconds till the script should autoexecute itself again (only needed when base==time)
function fetch(url,id,action,base,milliseconds){
 	if(base == "event"){
 		eventfetch(url,id,action);
 	}
 	else if(base == "time"){
 		timefetch(url,id,action,milliseconds);
 	}
}
//search & overlay functions
function search(table,column,identifier,search,searchtemp,id,action){
  searchrequest="../asearch.php?table="+table+"&column="+column+"&identifier="+identifier+"&search="+search+"&searchtemp="+searchtemp+"&div="+id;
  eventfetch(searchrequest,id,action);
}
function getposOffset(overlay, offsettype){
  var totaloffset=(offsettype=="left")? overlay.offsetLeft : overlay.offsetTop;
  var parentEl=overlay.offsetParent;
  while (parentEl!=null){
    totaloffset=(offsettype=="left")? totaloffset+parentEl.offsetLeft : totaloffset+parentEl.offsetTop;
    parentEl=parentEl.offsetParent;
  }
  return totaloffset;
}
function overlay(curobj, subobjstr, opt_position){
  if (document.getElementById){
    var subobj=document.getElementById(subobjstr)
    subobj.style.display="block"
    var xpos=getposOffset(curobj, "left")+((typeof opt_position!="undefined" && opt_position.indexOf("right")!=-1)? -(subobj.offsetWidth-curobj.offsetWidth) : 0)
    var ypos=getposOffset(curobj, "top")+((typeof opt_position!="undefined" && opt_position.indexOf("bottom")!=-1)? curobj.offsetHeight : 0)
    subobj.style.left=xpos+"px"
    subobj.style.top=(ypos+15)+"px"
    return false
  }
  else
    return true
}
function overlayclose(subobj){
	document.getElementById(subobj).style.display="none"
}

function AddText(addtext) {
	var current = document.post.message.value;
	var newtext = current + addtext;
	document.post.message.value = newtext;
	document.post.message.focus();
}

function AddCode(code) {
	AddText(code);
}