// Umschalter WYSIWYG / HTML
var isHTMLMode					= false;

var editWindow					= null;
var tybase						= "/tycon/";
var editPage;
var imgId;
var divs						= new Array();
var html						= 'off';
var siteMode					= false;
var tempValue					= new Array();
var contentSaved				= false;
var tmp_allowedTags				= new Array('tb_function_link','tb_function_anchor','tb_function_picture','tb_content_table','tb_content_htmlmode','tb_function_cleaner','tb_font_clear','tb_font_css_char','tb_font_css_para','tb_font_bold','tb_font_italic','tb_font_underline','tb_font_strike','tb_font_signs','tb_font_up','tb_font_down','tb_valign_left','tb_valign_right','tb_content_numberedlist','tb_content_dottedlist','tb_content_increase','tb_content_decrease')
var tyAutoSaveInterval			= null;
var contentModified				= false;
var staticbarnr					= null;
var richtextMenues				= new Array();
var contentValuesFetched		= false;
var globalInterval				= null;
var template_id 				= 0;
var colors_defined 				= false;
var fetchedFields 				= [];
var defaultParagraphFormat		= false;

var editingEnabled				= false;
var contentFormat				= "html";

var oDiv						= {
	id : "",
	getAttribute : function() { return ""; },
	setAttribute : function() { }
};

var blockNodes = new Array('p','blockqoute','div','ul','ol','h1','h2','h3','h4','h5','h6');

var tybase="/tycon/";
var siteMode="";
var mytyToolbar = null;
var mytyDevBar = null;
var d=null;
var OP,IE,NS4,NS6,NS;
var tyMouseLeft=0,tyMouseTop=0;
var allowedTag=new Array();
var ixed_pretop=-1;
var globalTimeout = null;
var showTbBarMenu = 'block';
var click_counter = 0;
var saveContentSuccessFunction = null;// insertAdjacentHTML(), insertAdjacentText() and insertAdjacentElement()
// for Netscape 6/Mozilla by Thor Larholm thor@jscript.dk
// Usage: include this code segment at the beginning of your document
// before any other Javascript contents.
if(typeof HTMLElement != "undefined" && !HTMLElement.prototype.insertAdjacentElement){
    HTMLElement.prototype.insertAdjacentElement = function (where,parsedNode)
    {
        switch (where){
        case 'beforeBegin':
                this.parentNode.insertBefore(parsedNode,this)
                break;
        case 'afterBegin':
                this.insertBefore(parsedNode,this.firstChild);
                break;
        case 'beforeEnd':
                this.appendChild(parsedNode);
                break;
        case 'afterEnd':
                if (this.nextSibling) this.parentNode.insertBefore(parsedNode,this.nextSibling);
                else this.parentNode.appendChild(parsedNode);
                break;
        }
    }

    HTMLElement.prototype.insertAdjacentHTML = function (where,htmlStr)
    {
        var r = this.ownerDocument.createRange();
        r.setStartBefore(this);
        var parsedHTML = r.createContextualFragment(htmlStr);
        this.insertAdjacentElement(where,parsedHTML);
    }


    HTMLElement.prototype.insertAdjacentText = function (where,txtStr)
    {
        var parsedText = document.createTextNode(txtStr);
        this.insertAdjacentElement(where,parsedText);
    }
}

function wechsel(imgId, src) {
	document.images(imgId).src = src;
}

function nextBlock(elem) {
	if (elem == "" ||elem == null) {
		elem = "1";
	}
	
	sel = window.getSelection();
	
	selNode = sel.anchorNode;

	while ( selNode ) {
		if (selNode.nodeType == elem && in_array(selNode.nodeName.toLowerCase(),blockNodes)) {
			break;
		}
		selNode = selNode.parentNode;
	}
	return selNode;
}

function nextBlockIE(elem,startNode) {
	if (elem == "" || elem == null) {
		var elem = "1";
	}
	var sel = document.selection.createRange();
	
	var selNode = (typeof startNode == 'undefined'?sel.parentElement():startNode);
	while ( selNode ) {
		if (selNode.nodeType == elem && in_array(selNode.nodeName.toLowerCase(),blockNodes)) {
			break;
		}
		selNode = selNode.parentNode;
	}
	return selNode;
}

function nextBlockByName(elem,startNode) {
	if (elem == "" || elem == null) {
		var elem = "div";
	}
	
	if(navigator.userAgent.indexOf('MSIE') < 0) {
		sel = window.getSelection();
		selNode = sel.anchorNode;
	} else {
		var sel = document.selection.createRange();
		var selNode = (typeof startNode == 'undefined'?sel.parentElement():startNode);
	}

	while ( selNode ) {
		if (selNode.nodeName.toLowerCase() == elem) {
			break;
		}
		selNode = selNode.parentNode;
	}
	return selNode;
}

function getContentDiv() {
	return oDiv;
}

//hide richTextMenues
function hideRichTextMenues(){
	var i=0;
	var elem = null;
	if (richtextMenues.length>0) {
		for(i=0;i<richtextMenues.length;i++)
			richtextMenues[i].style.display='none';
	} else {
		divs = document.getElementsByTagName("div");
		for(i=0;i<divs.length;i++) {
			elem = document.getElementById('menue_'+divs[i].getAttribute("tyCONid"));
			if(elem) {
				elem.style.display='none';
				richtextMenues.push(elem);
			}
		}
	}
}

function tyHideToolbar() {
	var elem = document.getElementById('tyTbBarMenu');
	if (elem) {
		if (elem.style.display == 'block') {
			tyChangeDisplay('tyTbBarMenu');
		}
	}
}

function tyShowToolbar() {
	var elem = document.getElementById('tyTbBarMenu');
	if (elem) {
		if (elem.style.display == 'none') {
			tyChangeDisplay('tyTbBarMenu');
		}
	}
}

function checkSetupForm() {
	var ret = true;
	var subject = document.getElementById('enableAutoSave');
	if (subject) {
		if (
			document.getElementById('enableAutoSave').checked == true &&
			( document.getElementById('autoSaveInterval').value == "" || 
			  parseFloat(document.getElementById('autoSaveInterval').value) <= 0.2)
		) {
			if (parseFloat(document.getElementById('autoSaveInterval').value) <= 0.2)
				alert("Bitte geben Sie für das Intervall einen größeren Wert als 0.2 Minuten an.");
			else
				alert("Bitte geben Sie ein Intervall für automatisches Speichern an.");
			ret = false;
		}
	}
	return ret;
}

function getFieldsById(id) {
	if (typeof id != 'undefined') {
		if (typeof fetchedFields[id] != 'undefined') {
			return fetchedFields[id];
		} else {
			var divs = document.getElementsByTagName('div');
			for (var i=0; i<divs.length; i++) {
				if (divs[i].id==id) {
					if (typeof fetchedFields[id] == 'undefined') fetchedFields[id] = [];
					fetchedFields[id].push(divs[i]);
				}
			}
			if (typeof fetchedFields[id] != 'undefined')
				return fetchedFields[id];
		}
	}
	return null;
}/**
 * initiiert die Werkzeugleiste
 */
function initToolbarHelper() {
	if (typeof window == 'undefined') return false;
	if (typeof document == 'undefined' || typeof navigator == 'undefined') window.setTimeout('initToolbarHelper()',100);
	mytyToolbar = document.getElementById('editMenue');
	mytyDevBar = document.getElementById('mytyWhooohaBar');
	if (typeof mytyToolbar == 'undefined') window.setTimeout('initToolbarHelper()',100);
	else initToolbar();
}
function initToolbar() {
	d = document;
	OP=window.opera?true:false;
	IE=(navigator.userAgent.indexOf('MSIE')>0?true:false);
	NS4=d.layers?true:false;
	NS6=(!IE && !OP && d.getElementById);
	NS=(NS4||NS6);
	editWindow = top.frames['tyNaviContent'] ? top.frames['tyNaviContent'] : window;

	addEvent(document, "keyup", countChars, false);
	makeDocumentUnselectable();
	document.onmousemove = getMousePos;
	getposition();
	MM_dragLayer('editMenue','',0,0,0,0,true,false,-1,-1,-1,-1,false,false,0,'',false,'');
	setTimeout('ixed_timer()',500);
	mytyAlert.init();
	globalTimeout = window.setInterval('AJAXrefreshServerSession()',1000000);
	getContentValues();
	}

function makeDocumentUnselectable() {
	if(navigator.userAgent.indexOf('MSIE')>0) {
		var all = document.all;
		var l = all.length;
		var divIds = new Array();
		var j = 0;

		for (var i = 0; i < l; i++) {
			if( all[i].tagName == "DIV" && all[i].tyCONid){
				divIds[j] = all[i].id;
				j++;
			}
			if(!(all[i].tagName == "DIV" && all[i].tyCONid) && all[i].tagName != "INPUT" && all[i].tagName != "TEXTAREA"){
				all[i].unselectable = "on";
			}
		}
		for (var i = 0; i < divIds.length; i++) {
			var Elementknoten = document.getElementById(divIds[i]);
			var divText = Elementknoten.innerHTML;
			Elementknoten.innerHTML = divText.replace(/unselectable=\"on\"/ig,"");
		}
	}
}

function setFormat(format) {
	contentFormat = format;
	var elem = document.getElementById('tb_remove_paragraph_style');
	if (elem) {
		if (format=='xsl') {
			elem.style.display='none';
		} else {
			elem.style.display='';
		}
	}
}

function setTemplateId(tid) {
	template_id = (parseInt(tid)>0?parseInt(tid):0);
}

// An- bzw. Abschalten von Formatierungen
function enableAllowedTags(allowedTags,count){
	var w = window;
	w.allowedTag = new Array();
	var at = allowedTags.split(",");
	var btn = null;
	count=count?count:'';

	//Tags aktivieren
	for(i=0;i<at.length;i++){
		w.allowedTag[at[i]]=true;
		btn = document.getElementById('tb_'+count+'_disabled_'+at[i]);
		if(btn) btn.style.display='none';
	}

	//deaktivierte Tags ausblenden
	for(i=0;i<tmp_allowedTags.length;i++){
		if(w.allowedTag[tmp_allowedTags[i]]!=true){
			btn = document.getElementById('tb_'+count+'_disabled_'+tmp_allowedTags[i]);
			if(btn) btn.style.display='block';
		}
	}
}

// Blendet nur die Stylesheets ein, die erlaubt sind (CSS-Modul)
function compStyles(charStyles,paraStyles,count) {
	if (contentFormat) {
		charStyles = charStyles+',';
		paraStyles = paraStyles+',';

		acs = charStyles.split(",");
		aps = paraStyles.split(",");
		count=count?count:'';
		if (document.getElementById('tyCharStylesTable'+count)) {
			if (contentFormat == "xsl") {
				// Alles ausblenden
				for (var x=0;x<document.getElementById('tyCharStylesTable'+count).lastChild.childNodes.length;x++) {
					if (document.getElementById('tyCharStylesTable'+count).lastChild.childNodes[x].id) {
						document.getElementById('tyCharStylesTable'+count).lastChild.childNodes[x].style.display='none';
					}
				}
				// erlaubte einblenden
				for (var i=0;i<acs.length;i++) {
					if (acs[i] != "" && document.getElementById('xslCompat_'+acs[i])) {
						document.getElementById('xslCompat_'+acs[i]).style.display = '';
					}
				}
			// HTML
			} else {
				for (var x=0;x<document.getElementById('tyCharStylesTable'+count).lastChild.childNodes.length;x++) {
					if (document.getElementById('tyCharStylesTable'+count).lastChild.childNodes[x].id) {
						document.getElementById('tyCharStylesTable'+count).lastChild.childNodes[x].style.display='none';
					}
				}
				for (var x=0;x<document.getElementById('tyCharStylesTable'+count).lastChild.childNodes.length;x++) {
					if (document.getElementById('tyCharStylesTable'+count).lastChild.childNodes[x].id) {
						if (document.getElementById('tyCharStylesTable'+count).lastChild.childNodes[x].id.match(/htmlCompat/i)) {
							document.getElementById('tyCharStylesTable'+count).lastChild.childNodes[x].style.display='';
						}
					}
				}
			}
		}

		// Paragraphen
		if (document.getElementById('tyParaStylesTable'+count)) {
			if (contentFormat == "xsl" || contentFormat == "flash") {
				// Alles ausblenden
				for (var x=0;x<document.getElementById('tyParaStylesTable'+count).lastChild.childNodes.length;x++) {
					if (document.getElementById('tyParaStylesTable'+count).lastChild.childNodes[x].id) {
						document.getElementById('tyParaStylesTable'+count).lastChild.childNodes[x].style.display='none';
					}
				}
				// erlaubte ausblenden
				for (var i=0;i<aps.length;i++) {
					if (aps[i] != "" && document.getElementById('xslParaCompat_'+aps[i])) {
						document.getElementById('xslParaCompat_'+aps[i]).style.display = '';
					}
				}
			// HTML
			} else {
				for (var x=0;x<document.getElementById('tyParaStylesTable'+count).lastChild.childNodes.length;x++) {
					if (document.getElementById('tyParaStylesTable'+count).lastChild.childNodes[x].id) {
						document.getElementById('tyParaStylesTable'+count).lastChild.childNodes[x].style.display='none';
					}
				}
				for (var x=0;x<document.getElementById('tyParaStylesTable'+count).lastChild.childNodes.length;x++) {
					if (document.getElementById('tyParaStylesTable'+count).lastChild.childNodes[x].id) {
						if (document.getElementById('tyParaStylesTable'+count).lastChild.childNodes[x].id.match(/htmlParaCompat/i)) {
							document.getElementById('tyParaStylesTable'+count).lastChild.childNodes[x].style.display='';
						}
					}
				}
			}
		}
	}
}

function getContentValues(id) {
	// Anker-Ersetzung wieder zu Link
	if (typeof mozileEditor != "undefined") mozileEditor.restoreAnchors();

	if (typeof id == 'undefined') {
		if(top.frames['tyNaviContent'])
			divs=top.frames['tyNaviContent'].document.getElementsByTagName("div");
		else
			divs=document.getElementsByTagName("div");

		for(var i=0;i < divs.length;i++)
			if (divs[i].getAttribute("tyCONid")) {
				tempValue[divs[i].id.substring(4,divs[i].id.length)] = divs[i].innerHTML;
			}
	} else {
		if (obj = document.getElementById(id)) {
			tempValue[id] = obj.innerHTML;
		}
	}

	//Anker wieder in Ordnung bringen
	if (typeof mozileEditor != "undefined" && oDiv.id!="") mozileEditor.replaceAnchors(oDiv);

	contentValuesFetched = true;
}

//aktuelle Texte mit gesicherten Texten vergleichen
function compareContentValues() {
	var changed=false;

	if(top.frames['tyNaviContent'])
		divs=top.frames['tyNaviContent'].document.getElementsByTagName("div");
	else
		divs=document.getElementsByTagName("div");

	// Anker-Ersetzung wieder zu Link
	if (typeof mozileEditor != "undefined")
		mozileEditor.restoreAnchors();

	for (var i=0;i < divs.length;i++) {
		if (divs[i].getAttribute("tyCONid")){
			id = divs[i].id.substring(4,divs[i].id.length);
			newValue=trim(divs[i].innerHTML);

			if (typeof tempValue[id] != 'undefined') {
				tempValue[id] = trim(tempValue[id]);
				if (newValue != tempValue[id]) {
					divs[i].setAttribute('changed','true');
					changed=true;
				} else {
					if (divs[i].style.color!="" || divs[i].style.backgroundColor!="") {
						colors_defined = true;
						divs[i].setAttribute("changed","true");
					} else if (divs[i].getAttribute("changed")=='true')
						divs[i].setAttribute('changed','false');
				}
			}
		}
	}

	//Anker ersetzen
	if (typeof mozileEditor != "undefined" && oDiv.id!="")
		mozileEditor.replaceAnchors(oDiv);

	if (changed==true) contentModified = true;
	else contentModified = false;
	showStatusModified();
	return changed;
}

// aktualisiert ModifiedImage
function showStatusModified() {
	if (contentModified==true) {
		if (document.getElementById('imgSave')) document.getElementById('imgSave').src='/tycon/themes/spiron/images/toolbar/tb_content_not_saved_on.gif';
	} else {
		if (document.getElementById('imgSave')) document.getElementById('imgSave').src='/tycon/themes/spiron/images/toolbar/tb_content_save_off.gif';
	}
}

//warnung beim verlassen der seite, wenn geänderte texte vorhanden
function leaveSite(){
	if(contentSaved==false) {
		if(compareContentValues()) {
			if (
				confirm("Sie haben ungespeicherte geänderte Texte!\nDrücken Sie: \n  Ok zum Speichern oder \n  Abbrechen, um die Änderungen nicht zu speichern.")
			){
				fnSaveAJAX();
			}
		}
		contentSaved = true;
	}
}

function tyInitAutoSave(time) {}
function tyClearAutoSave() {}
//die geänderten texte werden in versteckte felder gespeichert (deprecated)
function fnSave(para){
	var inhalt = null;
	var nohtml = null;
	var html = null;
	var breaks = null;
	var content_description = null;
	var changedContent = false;

	if(para=="text"){
		divs=document.getElementsByTagName("div");
		for(i=0; i < divs.length; i++){
			id=divs[i].getAttribute("tyCONid");
			if(id && divs[i].getAttribute("changed")=='true'){
				changedContent = true;
				document.getElementById(id).value = divs[i].innerHTML;
			}
		}
	} else if (compareContentValues() || contentValuesFetched==false || colors_defined == true){
		if(top.frames['tyNaviContent']){
			divs = top.frames['tyNaviContent'].document.getElementsByTagName("div");
		}else{
			divs=document.getElementsByTagName("div");
		}

		//Anker wieder in Ordnung bringen
		if (typeof mozileEditor != "undefined") mozileEditor.restoreAnchors();

		for(i=0;i < divs.length;i++) {
			tyid=divs[i].getAttribute("tyCONid");
			if(tyid && divs[i].getAttribute("changed")=='true'){
				changedContent = true;
				inhalt = prepareInhalt(divs[i].innerHTML);
				nohtml = divs[i].getAttribute("nohtml");
				html = divs[i].getAttribute("html");
				breaks = divs[i].getAttribute("break");
				content_description = divs[i].getAttribute("title");

				//WYSIWIG-Eingabe der Datensätze
				if(	divs[i].getAttribute("tydbid") &&
					divs[i].getAttribute("tytable") &&
					divs[i].getAttribute("tycol") &&
					divs[i].getAttribute("globalTopic")=='db'){

					table=divs[i].getAttribute("tytable");
					col=divs[i].getAttribute("tycol");
					id=divs[i].getAttribute("tydbid");

					text="<input type='hidden' name='tyDBTexts["+table+"]["+id+"]["+col+"]' value='"+inhalt+"' />";

					//wenn kein HTML erlaubt
					if(nohtml=='true' || html=='false'){
						text+="<input type='hidden' name='HTML["+table+"]["+id+"]["+col+"]' value='false' />";
					}
					//wenn weiche Umbrüche erlaubt
					if(breaks=='true'){
						text+="<input type='hidden' name='break["+table+"]["+id+"]["+col+"]' value='true' />";
					}
				}else{
					//normales content-Feld
					text="<input type='hidden' name='templateid["+tyid+"]' value='"+divs[i].getAttribute("id")+"' />\
					<input type='hidden' name='template_description["+tyid+"]' value='"+content_description+"' />\
					<input type='hidden' name='globalTopic["+tyid+"]' value='"+divs[i].getAttribute("globalTopic")+"' />\
					<input type='hidden' name='md5["+tyid+"]' value='"+divs[i].getAttribute("md5")+"' />\
					<input type='hidden' name='refid["+tyid+"]' value='"+inhalt+"' />";

					//wenn kein HTML erlaubt
					if(nohtml=='true' || html=='false'){
						text+="<input type='hidden' name='HTML["+tyid+"]' value='false' />";
					}
					//wenn weiche Umbrüche erlaubt
					if(breaks=='true'){
						text+="<input type='hidden' name='break["+tyid+"]' value='true' />";
					}
					if (contentFormat=="xsl") {
						// Wenn farben zugewiesen sind
						if (divs[i].getAttribute('color_id')!=null && divs[i].getAttribute('colorset')!=null) {
							text+="<input type='hidden' name='color["+tyid+"]' value='"+divs[i].getAttribute('color_id')+"' style=\"display: none;\"/>";
							text+="<input type='hidden' name='colorset["+tyid+"]' value='"+divs[i].getAttribute('colorset')+"' style=\"display: none;\"/>";
						}
						if (divs[i].getAttribute('bgcolor_id')!=null && divs[i].getAttribute('bgcolorset')!=null) {
							text+="<input type='hidden' name='bgcolor["+tyid+"]' value='"+divs[i].getAttribute('bgcolor_id')+"' style=\"display: none;\"/>";
							text+="<input type='hidden' name='bgcolorset["+tyid+"]' value='"+divs[i].getAttribute('bgcolorset')+"' style=\"display: none;\"/>";
						}
					}
				}
				document.getElementById("saveInhalt").insertAdjacentHTML("beforeEnd",text);
			}
		}
	}
	if (changedContent == true) {
		contentSaved = true;
	}
}
// die texte werden vorbereitet fuer das verstecken und spaeter das speichern
function prepareInhalt(inhalt){
	inhalt=inhalt.replace(/'/g,'&##ty##;');
	inhalt=inhalt.replace(/€/g,'&euro;');
	return inhalt;
}

// IE: Eingefuegtes in nur Text umwandeln (z.B. Word)
var eObj_global = "";

function clean_pasted_content() {
	eObj_global.innerHTML = cleanHTML(eObj_global.innerHTML);
	getContentValues();
}

function no_word(eObj) {
	eObj_global = eObj;
	setTimeout("clean_pasted_content()",1);
}

function activeElement() {
	if (document.getElementById('nodeinfo')) {
		if (editingEnabled) {
			sel = window.getSelection();
			if (sel.anchorNode) {
				if (sel.anchorNode.nodeType==1) {
					document.getElementById('nodeinfo').innerHTML = '&lt;'+sel.anchorNode.parentNode.nodeName+'&gt;';
					document.getElementById('nodeinfo').innerHTML += ' | ';
					document.getElementById('nodeinfo').innerHTML += '&lt;'+sel.anchorNode.nodeName+'&gt;';
				} else {
					document.getElementById('nodeinfo').innerHTML = '&lt;'+sel.anchorNode.parentNode.parentNode.nodeName+'&gt;';
					document.getElementById('nodeinfo').innerHTML += ' | ';
					document.getElementById('nodeinfo').innerHTML += '&lt;'+sel.anchorNode.parentNode.nodeName+'&gt;';
				}
			}
		} else {
			document.getElementById('nodeinfo').innerHTML = '';
		}
	}
}

function updateContentClasses(tmpDiv) {
	if (tmpDiv) {
		// tyShowTable tyEditable tyContentGloabl-fe-active
		var classStr = "tyShowTable";
		var labelClassStr = "";
		var oLabel = document.getElementById("label_"+tmpDiv.id);

		// Editierbar?
		if (tmpDiv.editable == 1) {
			classStr += " tyEditable";
		}
		// Textfeld-Typ
		switch (tmpDiv.fieldtype) {
			case 2: {
				classStr += " tyContentGlobal";
				labelClassStr += " tyContentGlobalLabel";
				break;
			}
			case 3: {
				classStr += " tyContentCheckedOut";
				labelClassStr += " tyContentCheckedOutLabel";
				break;
			}
			case 4: {
				classStr += " tyContentDB";
				labelClassStr += " tyContentDBLabel";
				break;
			}
			case 1:
			default: {
				classStr += " tyContent";
				labelClassStr += " tyContentLabel";
			}
		}
		if (tmpDiv.frontend == 1) {
			classStr += "-fe";
			labelClassStr += "-fe";
		}
		if (tmpDiv.active == 1) {
			classStr += "-active";
			labelClassStr += "-active";
		}
		if (tmpDiv.additional != '') {
			classStr += " "+tmpDiv.additional;
		}

		tmpDiv.className = classStr;
		if (oLabel != null) oLabel.className = labelClassStr;
	}
}

// Zählt die Sekunden runter
function countdownSeconds(container,until) {
	if (container!=null) {
		var jetzt = new Date();
		if (until > jetzt.getTime()) {
			container.innerHTML = Math.floor((until-jetzt.getTime())/1000);
		} else {
			window.clearInterval(globalInterval);
		}
	}
}

function unsetEditing(event) {
	elem = event.target;
	while (elem.nodeName.toLowerCase() != 'html') {
		if (elem.getAttribute('CONTENTEDITABLE')) {
			if (elem.getAttribute('CONTENTEDITABLE')=="true") {
				editingEnabled = true;
				return true;
			}
		} else if (elem.getAttribute('id')) {
			if (elem.getAttribute('id')=="editMenue") {
				editingEnabled = true;
				return true;
			} else {
				elem = elem.parentNode;
			}
		} else {
			elem = elem.parentNode;
		}
	}
	editingEnabled = false;
	activeElement();
}

// sperrt Contentfeld vor Ajax Abfrage
function prepareCheckoutAjax(contentCheckout, dbCheckout) {
	if (((oDiv.getAttribute('globaltopic') == 'db' && dbCheckout) || (oDiv.getAttribute('globaltopic') != 'db' && contentCheckout)) && oDiv.getAttribute('tyCONid').indexOf('NotInDatabase')==-1) {
		if (oDiv && navigator.userAgent.indexOf('MSIE')>=0) oDiv.setAttribute('contentEditable', 'false');
		else oDiv.editable = 0;
		oDiv.active = 0;
		oDiv.fieldtype = 3;
	 	updateContentClasses(oDiv);
	}
}

// aktiviert Contentfeld nach Ajax Abfrage
function concludeCheckoutAjax(tmpDiv) {
	if (tmpDiv && navigator.userAgent.indexOf('MSIE')>=0) tmpDiv.setAttribute('contentEditable', 'true');
	else mozile.setCurrentEditor(tmpDiv);
}// Zeigt das HTML-Modus-Fenster
function showHTMLDialog() {
	if (oDiv){
		tyCONid = oDiv.getAttribute("tyCONid");
		htmlWin = window.open(tybase + 'modules/frames.php?frame1=HTML-Modus&frame2=content/html_mode.php%3FdivId%3D'+oDiv.id.replace('tyep','')+'%26tyCONid%3D'+tyCONid,'htmlWin','width=500,height=600,screenX=0,screenY=0,resizable=yes');
		htmlWin.focus();
	}
}

// Fkt. zum einfügen eines Bildes in der WYSIWYG Ansicht
function showDialog(){
    bild = window.open(tybase+'modules/frames.php?frame1=Bild+einf%FCgen&frame2=content/bild.php','bild','width=450,height=600,left=0,top=0,scrollbars=no,resizable=yes');
    bild.focus();
}

// Fkt. zum einfügen eines Bildes in der WYSIWYG Ansicht - Bild Light
function showPictureLightDialog(){
    
    if (oDiv){
		var imageWidth = oDiv.getAttribute("myty-image-width");
   		var imageHeight = oDiv.getAttribute("myty-image-height");
   		var imageResizeMode = oDiv.getAttribute("myty-image-resizemode");
   		
	    bildLight = window.open(tybase+'modules/frames.php?frame1=Bild+einf%FCgen+-+Light&frame2=content/bild_light.php%3FimageMaxWidth%3D'+imageWidth+'%26imageMaxHeight%3D'+imageHeight+'%26resizemode%3D'+imageResizeMode,'bild','width=450,height=400,screenX=0,screenY=0,scrollbars=no,resizable=yes');
	    bildLight.focus();
    }
}

// Fkt. zum einfügen einer Datei in der WYSIWYG Ansicht
function showFileDialog(){
  datei = window.open(tybase + 'modules/content/file.php','datei','width=500,height=600,screenX=0,screenY=0,resizable=yes');
  datei.focus();
}

// Fkt. zum einfügen eines Links in der WYSIWYG Ansicht
function showLinkDialog(){
	if(document.all){
		// in Link-Dialog link.php verlagert, da sonst keine Wiederbearbeitung des Links möglich ist
		//fnFormat('unlink');
	}
	linkWin = window.open(tybase+'modules/frames.php?frame1=Verweis&frame2=content/link.php','file','width=500,height=515,screenX=0,screenY=0,scrollbars=no,status=no,resizable=yes');
	linkWin.focus();
}

// Fkt. zum einfügen eines Links in der WYSIWYG Ansicht - Link light
function showLinkLightDialog(){
	linkWinLight = window.open(tybase+'modules/frames.php?frame1=Verweis - Light&frame2=content/link_light.php','file','width=450,height=320,screenX=0,screenY=0,scrollbars=no,status=no,resizable=yes');
	linkWinLight.focus();
}

// Fkt. zum einfügen eines Ankers in der WYSIWYG Ansicht
function showAnchorDialog(topic){
	anch = window.open(tybase + 'modules/frames.php?frame1=Anker&frame2=content/anchor.php%3Ftopic%3D'+topic,'anch','width=400,height=200,screenX=0,screenY=0,scrollbars=no,status=no,resizable=yes');
	anch.focus();
}

// Fkt. zum einfügen eines Sonderzeichens in der WYSIWYG Ansicht
function showSpecialCharDialog(topic){
	spChar = window.open(tybase + 'modules/frames.php?frame1=Sonderzeichen&frame2=content/sel_special_char.php%3Ftopic%3D'+topic,'specialChar','width=480,height=560,screenX=0,screenY=0,scrollbars=no,status=no,resizable=no');
	spChar.focus();
}

// Funktion zum einfügen von Sprachdefinitionen
function showLanguageDialog(topic){
	langDef = window.open(tybase + 'modules/frames.php?frame1=Sprachdefinitionen&frame2=content/sel_language.php%3Ftopic%3D'+topic,'specialChar','width=480,height=400,screenX=0,screenY=0,scrollbars=no,status=no,resizable=no');
	langDef.focus();
}

// Funktion zum einfügen Formatspezifischen Optionen
function showFormatExtrasDialog(){
	var format = contentFormat;
	var query_string = '?format='+format;
	if (format == "xsl") {
		if (oDiv) {
			if (oDiv.getAttribute('color_id') != null) query_string += '&amp;color='+oDiv.getAttribute('color_id');
			if (oDiv.getAttribute('bgcolor_id') != null) query_string += '&amp;bgcolor='+oDiv.getAttribute('bgcolor_id');
		}
		if (template_id>0) query_string += '&amp;template_id='+template_id;
	}
	query_string = encodeURIComponent(query_string);
	var extrasWin = window.open(tybase + 'modules/frames.php?frame1=Formatspezifische Einstellungen&frame2=content/sel_formatextras.php'+query_string,'formatextras','width=300,height=300,screenX=0,screenY=0,scrollbars=no,status=no,resizable=yes');
	extrasWin.focus();
}

//showTableDialog
function showTableDialog(type){
	if(type=='newTable')
		tableWin = window.open(tybase + 'modules/frames.php?anz1=2&anz3=1&frame1=Tabellen erstellen&frame2=content/tyTableNew.php','table','width=490,height=660,screenX=0,screenY=0,resizable=yes');
	else if(type=='newRow')
		tableWin = window.open(tybase + 'modules/frames.php?anz1=2&anz3=1&frame1=Tabellenzeile erstellen&frame2=content/tyTableRowNew.php','table','width=490,height=330,screenX=0,screenY=0,resizable=yes');
	else if(type=='newCell')
		tableWin = window.open(tybase + 'modules/frames.php?anz1=2&anz3=1&frame1=Tabellenzelle erstellen&frame2=content/tyTableCellNew.php','table','width=500,height=490,screenX=0,screenY=0,resizable=yes');
	else if(type=='table')
		tableWin = window.open(tybase + 'modules/frames.php?anz1=2&anz3=1&frame1=Tabelle bearbeiten&frame2=content/tyTable.php','table','width=490,height=640,screenX=0,screenY=0,resizable=yes');
	else if(type=='row')
		tableWin = window.open(tybase + 'modules/frames.php?anz1=2&anz3=1&frame1=Tabellenzeile bearbeiten&frame2=content/tyTableRow.php','table','width=490,height=330,screenX=0,screenY=0,resizable=yes');
	else if(type=='cell')
		tableWin = window.open(tybase + 'modules/frames.php?anz1=2&anz3=1&frame1=Tabellenzelle bearbeiten&frame2=content/tyTableCell.php','table','width=540,height=510,screenX=0,screenY=0,resizable=yes');
		
	if(tableWin)
		tableWin.focus();
}

function showSnippet(){
	snip = window.open(tybase + 'modules/frames.php?anz1=2&anz3=1&frame1=HTML Schnipsel&frame2=snippets/index.php','snipped','width=490,height=560,screenX=0,screenY=0,resizable=yes');
	snip.focus();
}

//öffnet Farbfenster
function foreColor(){
	arr = window.open(tybase+'modules/frames.php?frame1=Farbauswahl&frame2=content/selcolor.php','selcolor','width=300,height=370,status=no,resizable=no');
	arr.focus();
}

// öffnet fenster zum editieren der news (oder der texte [wenn browser älter MSIE 5.5])
function openEditWindow(id,topic,template_id,width,height){
	adWin = window.open(tybase+"modules/content/edit.php?id=" + id +"&topic="+topic+"&template_id="+template_id,"adminWin","width="+ width +",height="+ height +",screenX=0,screenY=0,dependent=yes,scrollbars,resizable=yes");
	adWin.focus();
}

// weiß nicht, was die machen soll?
function openEditWindowProdukte(id,topic,template_id,width,height){
	adWin = window.open(tybase+"produkt_create.php?id=" + id +"&topic="+topic+"&template_id="+template_id,"adminWin","width="+ width +",height="+ height +",screenX=0,screenY=0,dependent=yes,scrollbars,status=yes,resizable=yes");
	adWin.focus();
}

// entfernt HTML-Tags / Attribute entsprechend Konfiguration in tyClean (tyConfig[modules][content][clean])
function cleanHTML(content) {
	if (typeof content == "undefined") {
		var elem = oDiv;
		if (elem) {
			var content = elem.innerHTML;
		}
	}
	content = content.replace(/^\s*?/ig,"");
	content = content.replace(/\s*?$/ig,"");
	content = content.replace(/\r?\n/igm,' ');
	
	if (content.length>0) {
		for (var s=0; s<5; s++) {
			for(var i=0;i<(tyClean.length-1);i++){
				if(tyClean[i][0]=="") tyClean[i][0]='\\w*';
		
				if(tyClean[i][1]==""){
					re=new RegExp("<"+tyClean[i][0]+" ?[^>]*>(.*?)</"+tyClean[i][0]+">","gim");
					content=content.replace(re,"$1");
				}else if(tyClean[i][2]==""){
					re=new RegExp("(<"+tyClean[i][0]+"[^>]*)"+tyClean[i][1]+'=("[^"]*"|\'[^\']*\'|[^ >]*)([^>]*>.*?</'+tyClean[i][0]+">)","gim");
					content=content.replace(re,"$1$3");
				}else{
					re=new RegExp("(<"+tyClean[i][0]+"[^>]*)"+tyClean[i][1]+'=("[^"]*'+tyClean[i][2]+'[^"]*"|\'[^\']*'+tyClean[i][2]+'[^\']*\'|[^ >]*'+tyClean[i][2]+'[^ >]*)([^>]*>.*?</'+tyClean[i][0]+">)","gim");
					content=content.replace(re,"$1$3");
				}
			}
		}

		// zusätzliche WordCleaning Aktion
		content = content.replace(/<\/?SPAN[^>]*>/gi, "");
		content = content.replace(/<\/?DEL[^>]*>/gi, "");
		content = content.replace(/<\/?INS[^>]*>/gi, "");
		content = content.replace(/ CLASS=\"?[^\"]*\"?/gi, "");
		content = content.replace(/ STYLE=\"?[^\"]*\"?/gi, "");
		content = content.replace(/<\/?PMARGIN[^>]*>/gi, "");
		content = content.replace(/<\/?DIR>/gi, "");
		content = content.replace(/<\/?FONT[^>]*>/gi, "");
		content = content.replace(/ class=\"?Mso[A-Za-z]*\"?/gi, "");
		content = content.replace(/<\/?o:[^>]*>/gi, "");
		content = content.replace(/<\/?st1:[^>]*>/gi, "");
		content = content.replace(/\–/g,'-'); //long -
		content = content.replace(/[‘’]/g, "'"); //single smartquotes ‘’
		content = content.replace(/[“”]/g, '"'); //double smartquotes “”
		content = content.replace(/<TD v>/g, '<TD>'); //double smartquotes “”
		content = content.replace(/<(TABLE|TD)(.*)WIDTH[^A-Za-z>]*/gi, "<$1$2"); //no fixed width tables
		content = content.replace(/<([^>]+)><\/\1>/gi, ""); //empty tag
		content = content.replace(/<\/?H[1-6][^>]*>/gi, "");
		content = content.replace(/<!\-\-.*\-\->/gi, "");
	
		if (elem) elem.innerHTML = content;
		else return content;
	}
}

function showPreviewBorder(image_id, id) {
	if (document.getElementById(image_id)) {
		for (i=0;i<document.getElementById(image_id).childNodes.length;i++) {
			if (document.getElementById(image_id).childNodes[i].nodeName.toLowerCase() == 'div') {
				document.getElementById(image_id).childNodes[i].style.display = 'none';
			}
		}
		if (document.getElementById(id)) {
			document.getElementById(id).style.display = 'block';
		}
	}
}

/**
 * entfernt unerlaubte Zeichen aus StyleString
 *
 **/
function cleanStyleString(strStyle){
	strStyle = strStyle.replace(/\./,'');
	strStyle = strStyle.replace('ß','ss');
	strStyle = strStyle.replace('ä','ae');
	strStyle = strStyle.replace('Ä','ae');
	strStyle = strStyle.replace('ö','oe');
	strStyle = strStyle.replace('Ö','oe');
	strStyle = strStyle.replace('ü','ue');
	strStyle = strStyle.replace('Ü','ue');
	return strStyle;
}

/**
 * sucht nach den markierten Absätzen und vergibt den übergebenen Klassennamen
 *
 **/
function styleParagraphsIE(strStyle){
	strStyle = cleanStyleString(strStyle);
	var firstRng = document.selection.createRange();
	var lastRng = document.selection.createRange();
	var completeRng = document.selection.createRange();
	firstRng.collapse(true);
	lastRng.collapse(false);
	var ancestor = completeRng.parentElement();
	var firstNode = firstRng.parentElement();
	var lastNode = lastRng.parentElement();
	var currNode = firstNode;
	if (currNode.nodeName && currNode.nodeName.toLowerCase()!='p' && currNode.nodeName.toLowerCase()!='li') {
		currNode = nextBlockIE('1',currNode);
	}
	var lastCurrNode = lastNode;
	if (lastCurrNode.nodeName && lastCurrNode.nodeName.toLowerCase()!='p' && lastCurrNode.nodeName.toLowerCase()!='li') {
		lastCurrNode = nextBlockIE('1',lastCurrNode);
	}
	var pList = null;
	do {
		if (currNode.nodeName && currNode.nodeName.toLowerCase()=="p") {
			if (strStyle!='') currNode.className = strStyle;
			else currNode.removeAttribute('className');
		} else {
			pList = currNode.getElementsByTagName("p");
			for (var i=0; i < pList.length; i++) {
				if (strStyle!='') pList[i].className = strStyle;
				else pList[i].removeAttribute('className');
			}
		}
		if (currNode == lastCurrNode) break;
	} while (currNode = currNode.nextSibling);
}

function styleParagraphs(strStyle){
	if(navigator.userAgent.indexOf('MSIE')<0) {
		fnStylesheet(strStyle,true);
	} else {
		styleParagraphsIE(strStyle);
	}
}

// Fügt Stylesheetformatierung ein
function fnStylesheet(strStyle, para){
	if(strStyle==null || strStyle=='' || typeof strStyle=='undefined') strStyle='..cleaner';

	var objSelection;
	var obj;
	var elem;
	var content;
	var parts = new Array();
	
	elem=oDiv;
	obj=document;

	if(navigator.userAgent.indexOf('MSIE')<0)
		objSelection=obj;
	else
		objSelection=obj.selection.createRange();

	parts[0] = "span";
	parts[1] = "class";
	parts[2] = cleanStyleString(strStyle);

	if(strStyle=="..cleaner"){
		if(navigator.userAgent.indexOf('MSIE')<0){
			sel = window.getSelection();
			if (para) {
				nextBlockNode = nextBlock();
				if (nextBlockNode.nodeName.toLowerCase() == "p" || nextBlockNode.nodeName.toLowerCase() == "ul" || nextBlockNode.nodeName.toLowerCase() == "ol") {
					nextBlockNode.removeAttribute('class');
				}
			}
		} else {
			if (para) {
				nextBlockNode = nextBlockIE();
				if (nextBlockNode.nodeName.toLowerCase() == "p" || nextBlockNode.nodeName.toLowerCase() == "ul" || nextBlockNode.nodeName.toLowerCase() == "ol") {
					nextBlockNode.removeAttribute('className');
				}
			}
		}
	}else{
		if(navigator.userAgent.indexOf('MSIE')<0){
			sel = window.getSelection();
			if (para) {
				nextBlockNode = nextBlock();
				if (nextBlockNode.nodeName.toLowerCase() == "p" || nextBlockNode.nodeName.toLowerCase() == "ul" || nextBlockNode.nodeName.toLowerCase() == "ol") {
					existClasses = nextBlockNode.getAttribute(parts[1]);
					nextBlockNode.setAttribute(parts[1], parts[2]);
					return true;
				}
			} else {
				var rng = sel.getRangeAt(0);
				var tmpRng = rng.cloneRange();
				var ancestorContainer = rng.commonAncestorContainer
				tmpRng.selectNodeContents(ancestorContainer);
				if (sel.anchorNode == sel.focusNode || ((ancestorContainer.nodeName.toLowerCase()=='p' || ancestorContainer.nodeName.toLowerCase()=='li') && sel.anchorNode.inRange(tmpRng) && sel.focusNode.inRange(tmpRng))) {
					var span = document.createElement(parts[0]);
					span.setAttribute(parts[1],parts[2]);
					span.appendChild(rng.cloneContents());
					rng.deleteContents();
					rng.insertNode(span);
					sel.selectAllChildren(span);
				} else {
					mytyAlert.show('<p>Zeichenformate können nur innerhalb eines einzelnen Absatzes gesetzt werden.</p>','error');
				}
			}
		} else {
			if (para) {
				var nextBlockNode = nextBlockByName("p");
				if (nextBlockNode == null) nextBlockNode = nextBlockByName("ol");
				if (nextBlockNode == null) nextBlockNode = nextBlockByName("ul");
				if (nextBlockNode == null) nextBlockNode = nextBlockIE();
				
				if (nextBlockNode && (nextBlockNode.nodeName.toLowerCase() == "p" || nextBlockNode.nodeName.toLowerCase() == "ul" || nextBlockNode.nodeName.toLowerCase() == "ol")) {
					if (nextBlockNode.getAttribute(parts[1]) != null) {
						nextBlockNode.removeAttribute(parts[1]);
					}
					parts[1] = "className";
					if (nextBlockNode.getAttribute(parts[1]) != null) {
						nextBlockNode.removeAttribute(parts[1]);
					}
					nextBlockNode.setAttribute(parts[1], parts[2]);
					objSelection.select();
					return true;
				}
			} else {
				var startRng = document.selection.createRange();
				var endRng = document.selection.createRange();
				var ancestorContainer = objSelection.parentElement();
				startRng.collapse(true);
				endRng.collapse(false);
				var startContainer = startRng.parentElement();
				var endContainer = endRng.parentElement();

				if (startContainer == endContainer ||
					(
						(ancestorContainer.nodeName.toLowerCase()=='p' || ancestorContainer.nodeName.toLowerCase()=='li') &&
						ancestorContainer.contains(startContainer) &&
						ancestorContainer.contains(endContainer)
					)
				) {
					if(parts[2]!="") parts[2]=" "+parts[1]+"='"+parts[2]+"'";
					// teste mit regulärem Ausdruck, ob p-Tag innerhalb
					if (objSelection.htmlText.search(/<\/?P/i) < 0 && objSelection.htmlText.search(/<\/?li/i) < 0 && objSelection.htmlText.search(/<\/?(ol|ul)/i) < 0) {
						var tmpRange = startRng.duplicate();
						tmpRange.moveToElementText(startContainer);
						if (tmpRange.compareEndPoints('EndToEnd',objSelection)==0) {
							objSelection.moveEnd('character',-1);
						}
						if (objSelection.htmlText.indexOf(' ')==0) {
							objSelection.moveStart('character',1);
						}
						objSelection.pasteHTML("<"+parts[0]+parts[2]+"> " + objSelection.htmlText + "</"+parts[0]+">");
						objSelection.select();
					} else {
						ancestorContainer.innerHTML = "<"+parts[0]+parts[2]+">" + ancestorContainer.innerHTML + "</"+parts[0]+">";
						objSelection.select();
					}
				} else {
					mytyAlert.show('<p>Zeichenformate können nur innerhalb eines einzelnen Absatzes gesetzt werden.</p>','error');
				}
			}
		}
	}
}

function tyInsertTag(htmltag){
	var objSelection;
	objSelection=document;
	if(!document.all) {
		var sel = window.getSelection();
		sel.spanText(htmltag);
	} else {
		objSelection=objSelection.selection.createRange();			
		objSelection.pasteHTML("<"+ htmltag +">" + objSelection.htmlText + "</"+ htmltag +"> ");
		objSelection.select();
 	}
}

// Führt Formatierungsanweisungen aus
function fnFormat(strCommand, strOption){
	if(navigator.userAgent.indexOf("MSIE")==-1) document.execCommandMoz(strCommand,strOption);
	else {
		if (strCommand == 'removeFormat') {
			document.execCommand('removeFormat',false , null);
			// span-Tags manuell entfernen
	  		var txtRng = document.selection.createRange();
			var parentElem = txtRng.parentElement();
			if (parentElem && parentElem.tagName.toLowerCase() == 'span') parentElem.outerHTML = parentElem.innerHTML;
			var spanList = parentElem.getElementsByTagName("span");
			while (spanList.length > 0) spanList[0].outerHTML = spanList[0].innerHTML;
		} else if (strCommand == 'insertorderedlist' || strCommand == 'insertunorderedlist') {
			//entferne alle class-Attribute aus P-Tags
			var firstRng = document.selection.createRange();
			var lastRng = document.selection.createRange();
			var completeRng = document.selection.createRange();
			firstRng.collapse(true);
			lastRng.collapse(false);
			var ancestor = completeRng.parentElement();
			var firstNode = firstRng.parentElement();
			var lastNode = lastRng.parentElement();
			var currNode = firstNode;
			if (currNode.nodeName && currNode.nodeName.toLowerCase()!='p' && currNode.nodeName.toLowerCase()!='li') {
				currNode = nextBlockIE('1',currNode);
			}
			var lastCurrNode = lastNode;
			if (lastCurrNode.nodeName && lastCurrNode.nodeName.toLowerCase()!='p' && lastCurrNode.nodeName.toLowerCase()!='li') {
				lastCurrNode = nextBlockIE('1',lastCurrNode);
			}
			var pList = null;
			do {
				if (currNode.nodeName && currNode.nodeName.toLowerCase()=="p" && currNode.getAttribute('className').length > 0) {
					currNode.removeAttribute('className');
				} else {
					pList = currNode.getElementsByTagName("p");
					for (var i=0; i < pList.length; i++) {
						if (pList[i].getAttribute('className').length > 0) pList[i].removeAttribute('className');
					}
				}
				if (currNode == lastCurrNode) break;
			} while (currNode = currNode.nextSibling);
			document.execCommand(strCommand,'',strOption);
		} else if (strCommand == 'formatparagraph') {
			var nextList = nextBlockByName('ol');
			if (nextList && nextList.tagName.toLowerCase() == 'ol') document.execCommand('insertorderedlist','',strOption);
			else {
				nextList = nextBlockByName('ul');
				if (nextList && nextList.tagName.toLowerCase() == 'ul') document.execCommand('insertunorderedlist','',strOption);
			}
		} else document.execCommand(strCommand,'',strOption);
	}
}

// fügt Bild an
function fnInsertImage(bildname) {
	editPage.document.execCommand("InsertImage",false,bildname);
}

//font-family
function tyInsertFont(font){
	if(!document.all){
  		var s=window.getSelection();   
  		s.spanText('span','style','font-family:'+font);		
	} else{
		var s=document.selection.createRange();		
		var text = s.text;
		s.pasteHTML('<span style="font-family:' + font + ';">' + text + '</span>');
	}
}

//font-size
function tyInsertFontSize(fontsize){
	if(!document.all){
  		var s=window.getSelection();
    	s.spanText('span','style','font-size:'+fontsize+'px');
	}else{
		var s=document.selection.createRange();		
		var text = s.text;		
		s.pasteHTML('<span style="font-size:' + fontsize + ';">' + text + '</span>');
	}
}

function tyInsertHeadline(h){	
	if(navigator.userAgent.indexOf('MSIE')<0){
		var s=window.getSelection();
		var rng = s.getRangeAt(0);
		if (!s.isCollapsed && rng.inNode("h[0-9]{1}",true,true)) return false;
		else if (!s.isCollapsed) {
			s.collapseToStart();
			rng = s.getRangeAt(0);
		}
		// Wenn wir uns in einer Liste befinden
		if (rng.inNode("li",true,false)) {
			// Dann muss untersucht werden, in welchem Typ von Liste
			var cont = rng.commonAncestorContainer;
			var subj = null;
			if (cont.nodeName) {
				if (cont.nodeName.toLowerCase() == "li") {
					subj = cont.parentNode;
				} else {
					cont = cont.getParentBlock();
					if (cont.nodeName.toLowerCase() == "li") {
						subj = cont.parentNode;
					}
				}
			}
			if (subj==null) return false;
			s.toggleList(subj.nodeName.toLowerCase());
		}
		for(var i=1;i<=6;i++){
			s.removeSpanText('h'+i);
		}
		mozile.executeCommand("Mozile-XHTMLBasic-Heading"+h,null);
	} else {
		var txtRng = document.selection.createRange();
		var parentElem = txtRng.parentElement();
		if (parentElem.tagName.match(/^H[1-6]/g) || parentElem.tagName.toLowerCase() == 'p') {
			if (txtRng.text == parentElem.innerText) {
				parentElem.removeNode();
				txtRng.pasteHTML('<h'+h+'>' + txtRng.htmlText + '</h'+h+'>');
			} else {
				var newNode = document.createElement('h'+h);
				newNode.innerHTML = parentElem.innerHTML;
				parentElem.replaceNode(newNode);
			}	
		} else {
			txtRng.pasteHTML('<h'+h+'>' + txtRng.htmlText + '</h'+h+'>');
		}
	}
}

function tyInsertBlock(tag){
	if(navigator.userAgent.indexOf('MSIE')<0){
		var s=window.getSelection();
		var rng = s.getRangeAt(0);
		if (tag.toLowerCase()=="blockquote" && !rng.collapsed) {
			// Sonderbehandlung bei Blockquote auf markierten Bereich
			rangeAncestor = rng.commonAncestorContainer;
			if (rangeAncestor.nodeName.toLowerCase() == "blockquote") {
				// prüfe ob gesamter Blockquote markiert
				ancChildren = rangeAncestor.childNodes;
				markAll = true;
				for (var i = 0; i < ancChildren.length; i++) {
					if(!s.containsNode(ancChildren[i], true)) {
						markAll = false;
						break;
					}
				}
				if (markAll) {
					// Blockquote-Tag entfernen und return
					ancParent = rangeAncestor.parentNode;
					while (rangeAncestor.hasChildNodes()) {
						ancParent.insertBefore(rangeAncestor.firstChild.cloneNode(true), rangeAncestor);
						rangeAncestor.removeChild(rangeAncestor.firstChild);
					}
					var IP=rangeAncestor.previousSibling.getFirstInsertionPoint();
					ancParent.removeChild(rangeAncestor);
					if(IP)IP.select();
					return true;
				}
			}
			// markierten Bereich in Blockquote verschieben
			newNode = document.createElement("blockquote");
			newNode.appendChild(rng.extractContents());
			rng.deleteContents();
			rng.insertNode(newNode);
			// entferne leere p- und li-Tags an den Schnittpunkten des Blockquote
			prev = newNode.previousSibling;
			if ((prev.nodeName.toLowerCase() == "p" || prev.nodeName.toLowerCase() == "li") && prev.textContent.length == 0)
				prev.parentNode.removeChild(prev);				
			next = newNode.nextSibling;
			if ((next.nodeName.toLowerCase() == "p" || next.nodeName.toLowerCase() == "li") && next.textContent.length == 0)
				next.parentNode.removeChild(next);
			first = newNode.firstChild;
			if ((first.nodeName.toLowerCase() == "p" || first.nodeName.toLowerCase() == "li") && first.textContent.length == 0)
				first.parentNode.removeChild(first);
			last = newNode.lastChild;
			if ((last.nodeName.toLowerCase() == "p" || last.nodeName.toLowerCase() == "li") && last.textContent.length == 0)
				last.parentNode.removeChild(last);

			var IP=newNode.getFirstInsertionPoint();
			if(IP)IP.select();
		} else {
			// Wenn wir uns in einer Liste befinden
			if (rng.inNode("li",true,false)) {
				// Dann muss untersucht werden, in welchem Typ von Liste
				var cont = rng.commonAncestorContainer;
				var subj = null;
				if (cont.nodeName) {
					if (cont.nodeName.toLowerCase() == "li") {
						subj = cont.parentNode;
					} else {
						cont = cont.getParentBlock();
						if (cont.nodeName.toLowerCase() == "li") {
							subj = cont.parentNode;
						}
					}
				}
				s.toggleList(subj.nodeName.toLowerCase());
				rng = s.getRangeAt(0);
			}
			if (rng.inNode(tag,true,false)) {
				if (!s.isCollapsed) {
					s.collapseToStart();
				}	
				s.removeSpanText(tag);
				mozile.executeCommand("Mozile-XHTMLBasic-Paragraph",null);
				return true;
			} else if (!s.isCollapsed) {
				s.collapseToStart();
			}
			if (tag=="p") {
				for(var i=1;i<=6;i++){
					s.removeSpanText('h'+i);
				}
				s.removeSpanText('blockquote');
				s.removeSpanText('div');
				s.removeSpanText(tag);
	
				mozile.executeCommand("Mozile-XHTMLBasic-Paragraph",null);
			} else {
				s.removeSpanText(tag);
				mozile.executeCommand("Mozile-XHTMLBasic-"+tag,null);
			}
		}
	} else {
		var txtRng = document.selection.createRange();
		var parentElem = txtRng.parentElement();
		if (parentElem.tagName.match(/^H[1-6]/g)) {
			if (txtRng.text == parentElem.innerText) {
				parentElem.removeNode();
				txtRng.pasteHTML('<p>' + txtRng.htmlText + '</p>');
			} else {
				var newNode = document.createElement('p');
				newNode.innerHTML = parentElem.innerHTML;
				parentElem.replaceNode(newNode);
			}	
		} else {
			txtRng.pasteHTML('<p>' + txtRng.htmlText + '</p>');
		}
 	}
}

function pasting_done() {
	var oIFrame = document.getElementById('pasteframe');
	if (oIFrame == null)
		oIFrame = document.getElementById('pasteframe_'+staticbarnr);
	if (oIFrame != null) {
		var pastedContent = "";
		window.focus();
		oIFrame.contentWindow.document.designMode = 'off';
	
		sel = window.getSelection();
		rng = sel.getRangeAt(0);
		
		helpnode = document.createElement("div");
		helpnode.setAttribute("mytyhelpernode","true");
		pastedContent = oIFrame.contentWindow.document.body.innerHTML;
		if (pastedContent.indexOf('tyEditable')>0) {
			mytyAlert.show('Sie versuchen ein komplettes Textfeld einzufügen. Dieser Vorgang ist nicht möglich. Bitte markieren Sie nur Teile des Quell-Textfeldes und kopieren dies erneut.');
			oIFrame.contentWindow.document.body.innerHTML = '';
			if (oDiv!=null) oDiv.focus();
			sel.collapse(rng.startContainer,rng.startOffset);
		} else {
			rng.deleteContents();
						pastedContent = cleanHTML(pastedContent);
									helpnode.innerHTML = pastedContent;
			oIFrame.contentWindow.document.body.innerHTML = '';
			rng.insertNode(helpnode);
			
			rng.selectNodeContents(helpnode);
			var docFragment = rng.extractContents();
			helpnode.parentNode.insertBefore(docFragment,helpnode);
			if (oDiv!=null) oDiv.focus();
			rng.setStartBefore(helpnode);
			rng.setEndAfter(helpnode);
			rng.collapse(true);
			sel.collapse(rng.startContainer,rng.startOffset);
			helpnode.parentNode.removeChild(helpnode);
			if (contentModified==false && pastedContent.length > 0) {
				contentModified = true;
				showStatusModified();
				if (oDiv && oDiv.getAttribute('changed')=='false') oDiv.setAttribute('changed', 'true');
			}
		}
	}
	countChars();
}

function fnPaste(click) {
	var oIFrame = document.getElementById('pasteframe');
	if (oIFrame == null)
		oIFrame = document.getElementById('pasteframe_'+staticbarnr);
	if (oIFrame != null) {
		oIFrame.contentWindow.document.designMode = 'on';
		oIFrame.contentWindow.focus();
	    /*
	    if (click == true) {
			var event = oIFrame.contentWindow.document.createEvent("KeyboardEvent");
			event.initKeyEvent("keypress", true, true, null, true, false, false, false, 118, 118);
 			var erg = oIFrame.contentWindow.document.dispatchEvent(event);
		}
		*/
		window.setTimeout("pasting_done()",1);
	}
}

function countChars() {
	var ie = (navigator.userAgent.indexOf('MSIE')<0?false:true);
	if (oDiv)	
		var counter = document.getElementById('charCounterCount_'+oDiv.id.replace(/tyep/ig,''));
	if (counter) {
		if (!ie) {
			var len = oDiv.textContent.length;
		} else {
			var len = oDiv.innerText.length;
		}
		
		counter.innerHTML = len;
		if (len > parseInt(oDiv.getAttribute('maxCharCount')))
			counter.className = 'charCountError';
		else
			counter.className = '';
	}
}

function checkPastedLength() {
	if (tyBrowser && tyBrowser.isIE()) {
		var clipBoardData = window.clipboardData.getData('Text');
		if (contentModified==false && clipBoardData.length > 0) {
			contentModified = true;
			showStatusModified();
			if (oDiv && oDiv.getAttribute('changed')=='false') oDiv.setAttribute('changed', 'true');
		}
	}
}

function fnUnFocusCurrentContentField(){
	var ie = (navigator.userAgent.indexOf('MSIE')<0?false:true);
	if(	oDiv ){
		if(ie){
			oDiv.blur();
		}else{
			mozile.stopEditing();
		}
		
		oDiv.active = 0;
		updateContentClasses(oDiv);
		tyClearAutoSave();
		
		oDiv = {
			id : "",
			getAttribute : function() { return ""; },
			setAttribute : function() { }
		};
	}
}
function findFirstElementById(id) {
	var elements = document.getElementsByTagName('div');
	for (var i=0;i<elements.length;i++) {
		if (elements[i].id && elements[i].id.indexOf(id)>=0) {
			return elements[i];
		}
	}
	var element = document.getElementById(id);
	if (element!=null) return element;
	return oDiv;
}

function toolbarContentBackButton(divId,contentid){
	AJAXupdateContent("historyBack", divId, contentid, oDiv.getAttribute('globalTopic'), contentModified);
}

function toolbarContentForwardButton(divId,contentid){
	AJAXupdateContent("historyForward", divId, contentid, oDiv.getAttribute('globalTopic'), contentModified);
}

function toolbarContentCurrentButton(divId,contentid, refresh, autosave) {
	var elem = findFirstElementById(divId);
	AJAXupdateContent("historyCurrentBackend", divId, contentid, elem.getAttribute('globalTopic'), contentModified, oDiv.getAttribute('tytable'), oDiv.getAttribute('tyconid'), oDiv.getAttribute('tycol'), oDiv.getAttribute('timestamp'), refresh, autosave);
}

function toolbarContentPublishedButton(divId,contentid){
	AJAXupdateContent("historyCurrentFrontend", divId, contentid, oDiv.getAttribute('globalTopic'), contentModified);
}

function toolbarContentPublishToPublisherButton(divId,contentid){
	AJAXupdateContent("historyPublishCurrentToPublisher", divId, contentid, oDiv.getAttribute('globalTopic'), contentModified);
}

function toolbarContentPublishButton(divId,contentid){
	AJAXupdateContent("historyPublishCurrent", divId, contentid, oDiv.getAttribute('globalTopic'), contentModified);
}

function toolbarContentPublishPageButton( topic ){
	AJAXPublishPage("historyPublishAll", topic);
}

function toolbarContentOnClick(divId,contentid){
	AJAXupdateContent("contentOnClick", divId, contentid, oDiv.getAttribute('globalTopic'), contentModified, oDiv.getAttribute('tytable'), oDiv.getAttribute('tyconid'), oDiv.getAttribute('tycol'), oDiv.getAttribute('timestamp'),true,true);
}

function toolbarContentDeleteButton(divId,contentid) {
	AJAXupdateContent("deleteThisVersion", divId, contentid, oDiv.getAttribute('globalTopic'), contentModified);
}

function AJAXPublishPage(action, topic) {
	var xmlobj;
	var post;
	var uri;
	xmlobj = false;
		uri = "http://www.gewo-freital.de/tycon/modules/content/ajax.updatecontent.php";
	post = "PHPSESSID=0ruuhbekkkv4rdd6ttgqj4d584&topic=" + topic + "&action=" + action;
	try {
		xmlobj = new ActiveXObject( "Msxml2.XMLHTTP" );
	} catch (e) {
		try {
	  		xmlobj = new ActiveXObject( "Microsoft.XMLHTTP" );
		} catch (oc) {
	  		xmlobj = null;
		}
	}
	if(!xmlobj && typeof XMLHttpRequest != "undefined")
		xmlobj = new XMLHttpRequest();
	if(xmlobj){
		xmlobj.open("POST", uri, true);
		xmlobj.setRequestHeader("Method", "POST " + uri + " HTTP/1.1");
		xmlobj.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		xmlobj.onreadystatechange = function() {
			if (xmlobj.readyState != 4)
				return;
			eval(xmlobj.responseText);
		}
		xmlobj.send( post );
	}
	return xmlobj;
}

function AJAXContentComment(action, textid, comment, feedback) {
	var xmlobj;
	var post;
	var uri;
	xmlobj = false;
		uri = "http://www.gewo-freital.de/tycon/modules/content/ajax.updatecontent.php";
	post = "PHPSESSID=0ruuhbekkkv4rdd6ttgqj4d584&topic=" + oDiv.getAttribute('globalTopic') + "&comment=" + escape(comment) + "&textid=" + escape(textid) + "&action=" + escape(action) + "&feedback=" + (feedback?"1":"0");
	try {
		xmlobj = new ActiveXObject( "Msxml2.XMLHTTP" );
	} catch (e) {
		try {
	  		xmlobj = new ActiveXObject( "Microsoft.XMLHTTP" );
		} catch (oc) {
	  		xmlobj = null;
		}
	}
	if(!xmlobj && typeof XMLHttpRequest != "undefined")
		xmlobj = new XMLHttpRequest();
	if(xmlobj){
		xmlobj.open("POST", uri, true);
		xmlobj.setRequestHeader("Method", "POST " + uri + " HTTP/1.1");
		xmlobj.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		xmlobj.onreadystatechange = function() {
			if (xmlobj.readyState != 4)
				return;
			eval(xmlobj.responseText);
		}
		xmlobj.send( post );
	}
	return xmlobj;
}

function AJAXupdateContent(action, divId, contentid, topic, contentModified, tableName, tyconId, columnName, timeStamp, refresh, autosave) {
	var xmlobj;
	var post;
	var uri;
	xmlobj = false;
		uri = "http://www.gewo-freital.de/tycon/modules/content/ajax.updatecontent.php";
	post = "PHPSESSID=0ruuhbekkkv4rdd6ttgqj4d584&divId=" + divId + "&contentid=" + contentid + "&topic=" + topic + "&action=" + action + "&contentModified=" + (contentModified===true?"true":"false") + "&refresh=" + (typeof refresh == 'undefined' || refresh == false?"false":"true") + "&autosave=" + (typeof autosave == 'undefined' || autosave == false?"false":"true") + "&tableName=" + (typeof tableName == 'undefined' || tableName == null?"false":tableName) + "&tyconId=" + tyconId + "&columnName=" + columnName + "&timeStamp=" + timeStamp;
	try {
		xmlobj = new ActiveXObject( "Msxml2.XMLHTTP" );
	} catch (e) {
		try {
	  		xmlobj = new ActiveXObject( "Microsoft.XMLHTTP" );
		} catch (oc) {
	  		xmlobj = null;
		}
	}
	if(!xmlobj && typeof XMLHttpRequest != "undefined")
		xmlobj = new XMLHttpRequest();
	if(xmlobj){
		xmlobj.open("POST", uri, true);
		xmlobj.setRequestHeader("Method", "POST " + uri + " HTTP/1.1");
		xmlobj.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		xmlobj.onreadystatechange = function() {
			if (xmlobj.readyState != 4)
				return;
			eval(xmlobj.responseText);
		}
		xmlobj.send( post );
	}
	return xmlobj;
}


var mytyToolbarContentCommentId = false;
var mytyToolbarContentCommentToPublisherArg1 = false;
var mytyToolbarContentCommentToPublisherArg2 = false;

function mytyToolbarShowContentCommentToPublish( contentId, text, arg1, arg2 ){
	mytyToolbarContentCommentToPublisherArg1 = arg1;
	mytyToolbarContentCommentToPublisherArg2 = arg2;

	mytyToolbarShowContentComment(contentId, text, true, false);
}

function mytyToolbarShowContentCommentToFeedback( contentId, text, arg1, arg2 ){
	mytyToolbarContentCommentToPublisherArg1 = arg1;
	mytyToolbarContentCommentToPublisherArg2 = arg2;

	mytyToolbarShowContentComment(contentId, text, false, true);
}

function mytyToolbarShowContentComment( contentId, text, toPublisher, toFeedback, toMe ){
	var message = "";

	if(document.getElementById('mytyToolbarContentComment') && mytyToolbarContentCommentId>0){
		text = document.getElementById('mytyToolbarContentComment').value;
	}

	mytyToolbarContentCommentId = contentId;
	message = 'Kommentar :<br/><textarea id="mytyToolbarContentComment" style="width:215px;height:90px;font-family:Verdana, Arial, Helvetica, sans-serif;font-size:10px;color:#000;">' + text + '</textarea>';
	if(toMe == true){
		message+= '<input type="button" value="Bearbeitung übernehmen" style="margin-top:5px;background-color:#782D38;font-size:10px;color:#fff;border:1px solid #000;width:215px;" onclick="toolbarContentSetMeForEditButton();"/>';
	}else{
		if(toPublisher == true){
			message+= '<input type="button" value="Zur veröffentlichung weitergeben" style="margin-top:5px;background-color:#782D38;font-size:10px;color:#fff;border:1px solid #000;width:215px;" onclick="mytyToolbarSaveContentComment(false);toolbarContentPublishToPublisherButton(mytyToolbarContentCommentToPublisherArg1,mytyToolbarContentCommentToPublisherArg2);"/>';
		}else{
			if( toFeedback ){
				message+= '<input type="button" value="Zurück zum Redakteur" style="margin-top:5px;background-color:#782D38;font-size:10px;color:#fff;border:1px solid #000;width:110px;" onclick="mytyToolbarSaveContentComment(true);"/>';
			}else{
				message+= '<input type="button" value="Speichern" style="margin-top:5px;background-color:#782D38;font-size:10px;color:#fff;border:1px solid #000;" onclick="mytyToolbarSaveContentComment(false);"/>';
			}
		}
	}

	mytyAlert.show(message,'speaker');
}

function mytyToolbarSetMeForEdit( contentId, text ){
	mytyToolbarShowContentComment( contentId, text, false, false, true );
}

function toolbarContentSetMeForEditButton(){
	AJAXContentComment("contentSetMeForEdit",mytyToolbarContentCommentId, document.getElementById('mytyToolbarContentComment').value);
	mytyAlert.hide();
}

function mytyToolbarSaveContentComment( feedback ){
	AJAXContentComment("contentComment",mytyToolbarContentCommentId, document.getElementById('mytyToolbarContentComment').value, feedback);
	mytyAlert.hide();
}
