//
// Quicklink for AfpWiki
// (c) 2004,2005 Jochen Kirstätter <joki@afpfaq.de>
// You can copy/modify and distribute this code under the conditions
// of the GNU GENERAL PUBLIC LICENSE Version 2.
//

var isID=0;
var isDHTML=0;
var isAll=0;
var isLayers=0;

// initialize environment.
function infoinit()
{
  if (document.getElementById) {
    isID=1; IsDHTML=1; }
  else {
    if (document.all) {
      isAll=1; isDHTML=1; }
    else {
      browserVersion = parseInt(navigator.appVersion);
      if ((navigator.appName.indexOf('Netscape') != -1) &&
          (browserVersion == 4)) {
        isLayers=1; isDHTML=1;
      }
    }
  }
}

function findDOM(objectID, withStyle) {
  if (withStyle == 1) {
    if (isID) {
      return (document.getElementById(objectID).style);
    } else {
      if (isAll) {
        return (document.all[objectID].style);
      } else {
        if (isLayers) {
          return (document.layers[objectID]);
        }
      }
    }
  } else {
    if (isID) {
      return (document.getElementById(objectID));
    } else {
      if (isAll) {
        return (document.all[objectID]);
      } else {
        if (isLayers) {
          return (document.layers[objectID]);
        }
      }
    }
  }
}

function tbinput() {
	return findDOM('TopicBarInputBox');
}

function IsEditing() {
  if (isAll || isID
            && (navigator.appName.indexOf('Opera') != 0
            || (navigator.appName.indexOf('Opera') == 0
            && parseInt(navigator.appVersion.substring(0,1)) > 6))) {
	var domDynamic = findDOM('DynamicTopicBar',1);
    return (domDynamic.display == 'block')?true:false;
  }
}

function SetEditing(flag) {
	var isEditing = IsEditing();
	if (isEditing == flag) {
		return; 
	}

	isEditing = flag;
	var domStatic = findDOM('StaticTopicBar',1);
	var domDynamic = findDOM('DynamicTopicBar',1);
	if (isEditing) {
      domStatic.display = 'none';
      domDynamic.display = 'block';
    } else {
      domStatic.display = 'block';
      domDynamic.display = 'none';
    }
}

function BodyClick() {
	if (IsEditing()) {
		SetEditing(false);
	}
}

function TopicBarClick() {
//	window.event.cancelBubble = 'true';
	if (IsEditing()) {
		return;
	}

	var domStatic = findDOM('StaticTopicBar');
	var domDynamic = findDOM('DynamicTopicBar');
	var domTopic = findDOM('TopicBar');

	// Grab these dimensions before SetEditing() to get them before the control is hidden (thus h=0;w=0!)
	var staticWide = domStatic.offsetWidth;
	var staticHigh = domStatic.offsetHeight;

	SetEditing(true);

	domDynamic.left = domTopic.offsetLeft;
	domDynamic.top = domTopic.offsetTop;
	domDynamic.width = domTopic.width;
	domDynamic.height = domTopic.height;

	var tbi = tbinput();
	tbi.left = domDynamic.left;
	tbi.top = domDynamic.top;
	tbi.width = staticWide;
	tbi.height = staticHigh;
	tbi.value = '';
	tbi.focus();
	tbi.select();
}

// future purpose...
function doLoad()
{
	// Initialize after loading the page
	infoinit();
}

// (c) 2005 Jochen Kirstätter <joki@afpfaq.de>
// this method resizes the edit section, if available, to a more
// comfortable size. actually this was reported as a feature request
// by one of my collegues. now the edit.afp provides a more useable
// editor handling than before.
function doResize()
{
	var height;
	var editsection = findDOM("EditSection",1);
	var edittopic = findDOM("edtTopic",1);

	// first, we need the available height to calculate the max.
	// value of our editing section.
	height = document.documentElement.clientHeight
	height -= 192; // ~editsection.offsetTop but has to be constant due to preview.

	// then we adjust height values of both: div and textarea
	// the value of 95 is derived from the controls below the
	// textarea (roughly guessed.)
	if(!IsInternetExplorer())
	{
		editsection.height = height + "px";
		edittopic.maxHeight = height - 125 + "px";
	}
}

var strEmailString = "";
function getContentWnd() { return parent; }

function onEmail() {
	var oWnd = getContentWnd();
	var oDoc = oWnd.document;
	var oDescription = oDoc.getElementById("description");
	var strDescription = ( (oDescription == null) || (oDescription.content == "") ) ? oDoc.title : oDescription.content;	
	if( oDoc.title == "" )
		oWnd.location.href = "mailto:?body="+BuildEmailDescription(strDescription, AddParamToURL(oWnd.location.href, strEmailString));
	else
		oWnd.location.href = "mailto:?subject="+escape(oDoc.title)+"&body="+BuildEmailDescription(strDescription, AddParamToURL(oWnd.location.href, strEmailString));
//	return true;
	return false;
}
function BuildEmailDescription(strDescription,hRef){
	return escape("Here's a great article you might be interested in:" +
				String.fromCharCode(13) + String.fromCharCode(10) + String.fromCharCode(13) + String.fromCharCode(10) + strDescription + String.fromCharCode(13) + String.fromCharCode(10) + "URL: " + hRef);
}
function AddParamToURL(strLoc,strParam){
	var i = strLoc.lastIndexOf("?");
	if(strLoc.indexOf(strParam, i) >= 0)
		return strLoc;
	
	strLoc += ((i >= 0) && (i > strLoc.lastIndexOf("/"))) ? "&" : "?";
	return strLoc + strParam;
}

//
// User handler to create a new topic for AfpWiki, (c) 2004,2005 Jochen Kirstätter <quicklink@afpfaq.de>
// You can copy/modify and distribute this code under the conditions
// of the GNU GENERAL PUBLIC LICENSE Version 2.
//
function createNewTopic() {
return true;
	var oWnd = getContentWnd();
	var defaultTopic = 'AfpWiki';
	var newTopic = prompt('Titel für neuen Beitrag', defaultTopic);
	var result = false;
	
	if(newTopic == null) {
		// User pressed 'Cancel', so leave it as-is.
	}
	else if(!newTopic == defaultTopic || newTopic == '' || newTopic == ' ') {
		// User pressed 'OK', but either default topic or no text was entered.
	}
	else {
		// Everything seems to be fine, so we are processing user's
		// input and redirect him to the edit page with the newly
		// specified topic.
		// Obviously there seems to be a patch for Internet Explorer that prevents
		// any way to set a new location URL. So, currently there is no known way
		// to me to solve this problem. Sorry!
		oWnd.location.href = location.protocol+"//"+location.host+"/new.afp?id="+escape(newTopic);
		result = true;
	}
	return result;
}

function __doPostBack(eventTarget, eventArgument) {
//	var theform = findDOM('afpwiki');
	var theform;
	if (window.navigator.appName.toLowerCase().indexOf("netscape") > -1) {
		theform = document.forms["afpwiki"];
	}
	else {
		theform = document.afpwiki;
	}
	theform.__EVENTTARGET.value = eventTarget.split("$").join(":");
	theform.__EVENTARGUMENT.value = eventArgument;
	theform.submit();
}

//
// Form validator for AfpWiki
// (c) 2004,2005 Jochen Kirstätter <joki@afpfaq.de>
// You can copy/modify and distribute this code under the conditions
// of the GNU GENERAL PUBLIC LICENSE Version 2.
//
var prompts = new Object();
     prompts['edtTopic'] = 'Artikelinhalt';
     prompts['user'] = 'Bearbeitung durch';
     prompts['txtUsername'] = 'Bearbeitung durch';
     prompts['txtName'] = 'Benutzername';
     prompts['txtPassword'] = 'Passwort';

//
// Form validation
//
function checkform(oForm) {
	var domButton = (findDOM('cmdSave') || findDOM('cmdLogin'));
	var staticCaption = domButton.value;

	domButton.value = 'Vielen Dank';
	domButton.disabled = true;

	var el, focus_el, i = 0, msg = '\nDie folgenden Eingabefelder wurden nicht ausgefüllt:\n\n';
	while (el = oForm.elements[i++])
		if (/^\s*$/.test(el.value) && el.className == 'mandatory') {
			msg += '\t' + prompts[el.name] + '\n';
			if (!focus_el) focus_el = el;
		}

	if (focus_el) {
		msg += '\nBitte tragen Sie einen Wert ein und senden Ihre Eingaben erneut. Danke.\n';
		alert(msg);

		domButton.value = staticCaption;
		domButton.disabled = false;

		focus_el.focus();
		focus_el.select();
		return false;
	}
	domButton.disabled = false;
	return true;
}

//
// JavaScript code borrowed from WikiPedia.org to realize similar editor
// functionality
//
// Wikipedia JavaScript support functions
// if this is true, the toolbar will no longer overwrite the infobox when you move the mouse over individual items
var noOverwrite=false;
var alertText;
var clientPC = navigator.userAgent.toLowerCase(); // Get client info
var is_gecko = ((clientPC.indexOf('gecko')!=-1) && (clientPC.indexOf('spoofer')==-1)
                && (clientPC.indexOf('khtml') == -1) && (clientPC.indexOf('netscape/7.0')==-1));
var is_safari = ((clientPC.indexOf('AppleWebKit')!=-1) && (clientPC.indexOf('spoofer')==-1));
var is_khtml = (navigator.vendor == 'KDE' || ( document.childNodes && !document.all && !navigator.taintEnabled ));
if (clientPC.indexOf('opera')!=-1) {
    var is_opera = true;
    var is_opera_preseven = (window.opera && !document.childNodes);
    var is_opera_seven = (window.opera && document.childNodes);
}

function addEngine()
{
  if ((typeof window.sidebar == "object") && (typeof
  window.sidebar.addSearchEngine == "function"))
  {
    window.sidebar.addSearchEngine(
      "http://www.afpwiki.de/afpwiki.src",
      "http://www.afpwiki.de/afpwiki.png", 
      "AfpWiki",
      "Information");
  }
}    

// this function generates the actual toolbar buttons with localized text
// we use it to avoid creating the toolbar where javascript is not enabled
function addButton(imageFile, speedTip, tagOpen, tagClose, sampleText) {

	speedTip=escapeQuotes(speedTip);
	tagOpen=escapeQuotes(tagOpen);
	tagClose=escapeQuotes(tagClose);
	sampleText=escapeQuotes(sampleText);
	var mouseOver="";

	// we can't change the selection, so we show example texts
	// when moving the mouse instead, until the first button is clicked
	if(!document.selection && !is_gecko) {
		// filter backslashes so it can be shown in the infobox
		var re=new RegExp("\\\\n","g");
		tagOpen=tagOpen.replace(re,"");
		tagClose=tagClose.replace(re,"");
		mouseOver = "onMouseover=\"if(!noOverwrite){document.infoform.infobox.value='"+tagOpen+sampleText+tagClose+"'};\"";
	}

	document.write("<a href=\"javascript:insertTags");
	document.write("('"+tagOpen+"','"+tagClose+"','"+sampleText+"');\">");
        document.write("<img src=\""+imageFile+"\" border=\"0\" alt=\""+speedTip+"\" title=\""+speedTip+"\""+mouseOver+">");
	document.write("</a>");
	return;
}

function addInfobox(infoText,text_alert) {
	alertText=text_alert;
	var clientPC = navigator.userAgent.toLowerCase(); // Get client info

	var re=new RegExp("\\\\n","g");
	alertText=alertText.replace(re,"\n");

	// if no support for changing selection, add a small copy & paste field
	// document.selection is an IE-only property. The full toolbar works in IE and
	// Gecko-based browsers.
	if(!document.selection && !is_gecko) {
 		infoText=escapeQuotesHTML(infoText);
	 	document.write("<form name='infoform' id='infoform'>"+
			"<input size=80 id='infobox' name='infobox' value=\""+
			infoText+"\" READONLY></form>");
 	}

}

function escapeQuotes(text) {
	var re=new RegExp("'","g");
	text=text.replace(re,"\\'");
	re=new RegExp('"',"g");
	text=text.replace(re,'&quot;');
	re=new RegExp("\\n","g");
	text=text.replace(re,"\\n");
	return text;
}

function escapeQuotesHTML(text) {
	var re=new RegExp('"',"g");
	text=text.replace(re,"&quot;");
	return text;
}

// apply tagOpen/tagClose to selection in textarea,
// use sampleText instead of selection if there is none
// copied and adapted from phpBB
function insertTags(tagOpen, tagClose, sampleText) {

	var txtarea = findDOM('edtTopic');
	// IE
	if(document.selection  && !is_gecko) {
		var theSelection = document.selection.createRange().text;
		if(!theSelection) { theSelection=sampleText;}
		txtarea.focus();
		if(theSelection.charAt(theSelection.length - 1) == " "){// exclude ending space char, if any
			theSelection = theSelection.substring(0, theSelection.length - 1);
			document.selection.createRange().text = tagOpen + theSelection + tagClose + " ";
		} else {
			document.selection.createRange().text = tagOpen + theSelection + tagClose;
		}

	// Mozilla
	} else if(txtarea.selectionStart || txtarea.selectionStart == '0') {
 		var startPos = txtarea.selectionStart;
		var endPos = txtarea.selectionEnd;
		var scrollTop=txtarea.scrollTop;
		var myText = (txtarea.value).substring(startPos, endPos);
		if(!myText) { myText=sampleText;}
		if(myText.charAt(myText.length - 1) == " "){ // exclude ending space char, if any
			subst = tagOpen + myText.substring(0, (myText.length - 1)) + tagClose + " ";
		} else {
			subst = tagOpen + myText + tagClose;
		}
		txtarea.value = txtarea.value.substring(0, startPos) + subst +
		  txtarea.value.substring(endPos, txtarea.value.length);
		txtarea.focus();

		var cPos=startPos+(tagOpen.length+myText.length+tagClose.length);
		txtarea.selectionStart=cPos;
		txtarea.selectionEnd=cPos;
		txtarea.scrollTop=scrollTop;

	// All others
	} else {
		var copy_alertText=alertText;
		var re1=new RegExp("\\$1","g");
		var re2=new RegExp("\\$2","g");
		copy_alertText=copy_alertText.replace(re1,sampleText);
		copy_alertText=copy_alertText.replace(re2,tagOpen+sampleText+tagClose);
		var text;
		if (sampleText) {
			text=prompt(copy_alertText);
		} else {
			text="";
		}
		if(!text) { text=sampleText;}
		text=tagOpen+text+tagClose;
		document.infoform.infobox.value=text;
		// in Safari this causes scrolling
		if(!is_safari) {
			txtarea.focus();
		}
		noOverwrite=true;
	}
	// reposition cursor if possible
	if (txtarea.createTextRange) txtarea.caretPos = document.selection.createRange().duplicate();
}

// (c) 2004,2005 Jochen Kirstätter <joki@afpfaq.de>
// Changes input dialog for database information depending
// on the specified dbms. Currently this method only supports
// two types - vfp and odbc - but this will be enhanced by 
// AJaX technology to get the needed option dialog directly
// from the server. This way we are also able to realize L18N.
function toogleDatabase(oSelect) 
{
	if(oSelect != null)
	{
		var dbtype = oSelect.value;
		var optionsection = findDOM("dboptions");
		var odbc = findDOM("odbc",1);
		var vfp = findDOM("vfp",1);

		switch (dbtype)
		{
			case "vfp":	
				odbc.display = 'none';
				vfp.display = 'block';
				break;
			default:
				odbc.display = 'block';
				vfp.display = 'none';
		}		
	}
	return true;
}

// The method IsInternetExplorer checks whether the current browser is the
// Microsoft Internet Explorer or not.
function IsInternetExplorer()
{
	// Check whether the official application name contains the string
	// "Microsoft Internet Explorer" and return the result.
	return (navigator.appName == "Microsoft Internet Explorer");
}

function getXmlHttp()
{
// Internet Explorer
	try {
	    xmlHttp  = new ActiveXObject("Msxml2.XMLHTTP");
	} catch(e) {
	    try {
	        xmlHttp  = new ActiveXObject("Microsoft.XMLHTTP");
	    } catch(e) {
	        xmlHttp  = false;
	    }
	}          
	// Mozilla, Opera und Safari
	if (!xmlHttp  && typeof XMLHttpRequest != 'undefined') {
	    xmlHttp = new XMLHttpRequest();
	}
	return xmlHttp;
}

function getXml(cMethod, cParameter)
{
	var xmlHttp = getXmlHttp();
	if (xmlHttp) {
	    xmlHttp.open('GET', 
	    	'ajax.afp?action=' + cMethod + 
	    	'&parameter=' + cParameter, 
	    	true);
	    xmlHttp.onreadystatechange = function () {
	        if (xmlHttp.readyState == 4) {
				var tooltipcaption = findDOM("tooltipcaption");
				var tooltiptext = findDOM("tooltiptext");
	            if(tooltipcaption)
	            {
		            tooltipcaption.innerHTML = cParameter;
		            tooltiptext.innerHTML = xmlHttp.responseText;
		            settip('tooltip');
	            }
	        }
	    };
	    xmlHttp.send(null);
	}
}

function postXml(cMethod, cParameter)
{
	var xmlHttp = getXmlHttp();
	if (xmlHttp)
	{
		xmlHttp.open('GET',
			'ajax.afp?action=' + cMethod + 
			'&parameter=' + escape(cParameter),
			true);
		xmlHttp.onreadystatechange = function()
		{
			if (xmlHttp.readyState == 4)
			{
				var previewSection = findDOM('preview');
				if (previewSection)
				{
					previewSection.innerHTML = xmlHttp.responseText;
					togglepreview();
				}
			}
	    };
	    xmlHttp.send(null);
	}
}
// bind global events of window / document.
window.onload = (IsInternetExplorer()) ? doLoad : doLoad();

// EOF

