/*
		constants
 */
var MAX_LINES = 15;
var MAX_CHARPERLINE = 50;
var MAX_CHAR = MAX_LINES * MAX_CHARPERLINE; // bei 13 und 40 = 520
var _gc_text = "";

MyWindow = null;
/*
 * create preview window
 * 
 */
function Preview() {
	MyWindow = openPopupWindow('preview.html', 'Vorschau', 517, 550, 'no');
}

/*
 * update previews
 * 
 */
function ChangeListerner() {
	var Ergebnis = cleanUp(getText(getSaveElementById(this.document, 'Eingabe')));
	if (MyWindow != null && !MyWindow.closed) {
		setText(getSaveElementById(MyWindow.document, 'Text'), Ergebnis);
	} else {
		setText(getSaveElementById(this.document, 'Text'), Ergebnis);
	}

}

/*
 * This function is cleaning the text to get a valid html preview
 * 
 */
function cleanUp(text) {
	if (typeof (text) == 'string')
		return text.replace(/^[\s(&nbsp;)]+/g, '').replace(/[\s(&nbsp;)]+$/g,
				'').replace(/(\r\n)|(\n\r)|\r|\n/g, '<br/>');
	else
		return text;
}

/*
 * get value of an element
 * 
 */
function getText(MyElement) {
	return MyElement.value;
}

/*
 * set text value of an element
 * 
 */
function setText(MyElement, Content) {
	MyElement.innerHTML = "<p>" + Content + "</p>";
}

/*
 * get elmenet for every browser type
 * 
 */
function getSaveElementById(MyDocument, ElementId) {
	if (document.getElementById) {
		return MyDocument.getElementById(ElementId);
	} else if (document.all) {
		return MyDocument.all(ElementId);
	} else if (document.layers) {
		return MyDocument.layers(ElementId);
	} else return null;
}

/*
 * function to open popup window with no scrolling, toolbar or locationbar
 */
function openPopupWindow(url, name, w, h, scrollbars) {
	var MeinFenster = null;
	var _w = w;
	var _h = h;
	var _l = (screen.width - w) / 2;
	var _t = (screen.height - h) / 2;

	/* check left and right offset */
	if (_w > screen.width) {
		_w = screen.width;
		_l = 0;
	}

	if (_h > screen.height) {
		_h = screen.height;
		_t = 0;
	}

	/* create popup window */
	var params = (typeof (document.layers) != "undefined" ? "scrollbars="
			+ scrollbars + ",toolbar=no,locationbar=no,statusbar=no,pageX="
			+ String(_l) + ",pageY=" + String(_t) + ",width=" + String(_w)
			+ ",height=" + String(_h) : "scrollbars=" + scrollbars
			+ ",toolbar=no,locationbar=no,statusbar=no,left=" + String(_l)
			+ ",top=" + String(_t) + ",width=" + String(_w) + ",height="
			+ String(_h));
	MeinFenster = window.open(url, name, params);
	return MeinFenster;
}

function ChangeView() {
	var myElement = getSaveElementById(this.document, 'Form');
	myElement.style.display = "block";
	var myElement2 = getSaveElementById(this.document, 'Text');
	myElement2.style.display = "none";
}

function toTop() {
	var objTagForm = document.Grusskarte;
	var myElement = objTagForm.elements['greetingCardMessage'];
	myElement.style.zIndex = '5';
	var myElement2 = getSaveElementById(this.document, 'Text');
	myElement2.style.zIndex = '2';
	myElement2.style.display = "none";
	var myElement3 = getSaveElementById(this.document, 'Text');
	myElement3.style.zIndex = '2';
	myElement3.style.display = "none";
	myElement.style.display = "block";
}
function toBack() {
	var objTagForm = document.Grusskarte;
	var myElement = objTagForm.elements['greetingCardMessage'];
	myElement.style.zIndex = '2';
	var myElement2 = getSaveElementById(this.document, 'Text');
	myElement2.style.zIndex = '5';
	var myElement3 = getSaveElementById(this.document, 'txt');
	myElement.style.display = "none";
	myElement2.style.display = "block";
	myElement3.style.display = "block";
	var Ergebnis = cleanUp(getText(objTagForm.elements['greetingCardMessage']));
	setText(myElement3, Ergebnis);
}

function ReplaceView() {
	var myContainer = getSaveElementById(this.document, 'Container');
	// var Knoten = myContainer.firstChild;
	var Knoten = getSaveElementById(this.document, 'Text');
	alert(Knoten.nodeName);
	if (Knoten.nodeName == "DIV") {
		myContainer.removeChild(Knoten);
		myContainer.appendChild(createTextElement());
	} else if (Knoten.nodeName == "FORM") {
		myContainer.removeChild(Knoten);
		myContainer.appendChild(createPreviewElement());
	}

}

function createPreviewElement() {
	// element
	var preview = document.createElement("div");
	// attribute
	var Style = document.createAttribute("style");
	Style.nodeValue = "background-image:url(bg_gc_preview.jpg); font-size:1.4em;font-family:Monotype Corsiva; src:url(garamond.eot), url(garamond.pfr); width:517px; height:339px;";
	// attribute
	var id1 = document.createAttribute("id");
	id1.nodeValue = "Text";
	var Textknoten = document.createTextNode("Du darfst!");
	// attribute
	var Oc = document.createAttribute("onclick");
	Id1.nodeValue = "ReplaceView()";
	preview.setAttributeNode(Style);
	preview.appendChild(Textknoten);
	preview.setAttributeNode(Oc);
	return preview;
}

function createTextElement() {
	// Formular
	var Formular = document.createElement("form");
	// attribute
	var Name = document.createAttribute("name");
	Name.nodeValue = "Formular";
	// attribute
	var Action = document.createAttribute("action");
	Action.nodeValue = "";
	// attribute
	var Id1 = document.createAttribute("id");
	Id1.nodeValue = "Text";
	// attribute
	var Oc = document.createAttribute("onclick");
	Id1.nodeValue = "ReplaceView()";
	// attribute
	var Ob = document.createAttribute("onblur");
	Id1.nodeValue = "ReplaceView()";
	Formular.setAttributeNode(Name);
	Formular.setAttributeNode(Action);
	Formular.setAttributeNode(Id1);
	// Formular.setAttributeNode(Oc);
	Formular.setAttributeNode(Ob);
	// --------------------------
	// Textarea
	var TextareaX = document.createElement("textarea");
	// attribute
	var Cols = document.createAttribute("cols");
	Cols.nodeValue = "35";
	// attribute
	var Rows = document.createAttribute("rows");
	Rows.nodeValue = "4";
	// attribute
	var Name2 = document.createAttribute("name");
	Name2.nodeValue = "Eingabe";
	// attribute
	var Id = document.createAttribute("id");
	Id.nodeValue = "Eingabe";
	// attribute
	var Oku = document.createAttribute("onkeyup");
	Oku.nodeValue = "ChangeListerner()";
	TextareaX.setAttributeNode(Cols);
	TextareaX.setAttributeNode(Rows);
	TextareaX.setAttributeNode(Name2);
	TextareaX.setAttributeNode(Id);
	TextareaX.setAttributeNode(Oku);
	Formular.appendChild(TextareaX);

	return Formular;
}
function ChangeBack() {
	var myElement = getSaveElementById(this.document, 'Editor');
	myElement.style.display = "none";
	var myElement2 = getSaveElementById(this.document, 'Text');
	myElement2.style.display = "block";
}

function removeElement(divNum) {
	var d = document.getElementById('myDiv');
	var olddiv = document.getElementById(divNum);
	d.removeChild(olddiv);
}

function countLines() {
	// ##################
	var detect = navigator.userAgent.toLowerCase();
	var dist = 2;
	if (detect.indexOf('firefox') + 1) {// not internet explorer
		dist = 1;
	}
	// ##################
	var objTagDiv = null; // div: message of lines
	var objTagForm = document.Grusskarte; // form

	// if divObjCounter is not defined - exit
	if (typeof (document.getElementById('divObjCounter').innerHTML) == 'undefined') {
		return false;
	} else {
		objTagDiv = document.getElementById('divObjCounter');
	}

	var originalText = objTagForm.elements['greetingCardMessage'].value; // unchanged
																			// text
	var text = originalText.replace(/\r/, ""); // changed text
	var arrTextSplits = text.split('\n'); // aufgesplitteter Text
	var intTextSplitLength = arrTextSplits.length; // Anzahl an Splits = Anzahl
													// an userbreaks

	var intLines = 0; // Anzahl geschriebener Zeilen
	var i = 0; // runningVar for while
	var intCharLength = 0; // number of characters between two \n
	var index = 0; // index to get substrings of lines
	var strSubStr = ''; // substring of lines
	var intLastBlank = 0; // position of last blankspace in substring
	// Iteration of Splits
	if (intTextSplitLength <= MAX_LINES) {
		// Durchlaufen aller Splits
		while (i < intTextSplitLength) {
			arrTextSplits[i] = arrTextSplits[i].replace(/\r/, "");
			intCharLength = arrTextSplits[i].length;
			if (intCharLength != 0) {
				intLines++;
				if (intCharLength > MAX_CHARPERLINE) {
					index = 0;
					// more than MAX_CHARPERLINE characters
					while (intCharLength > MAX_CHARPERLINE) {
						strSubStr = arrTextSplits[i].substr(index,
								MAX_CHARPERLINE); // substring of 40
													// characters starting with
													// index
						intLastBlank = strSubStr.lastIndexOf(" ") + 1; // last
																		// index
																		// of
																		// blank
																		// in
																		// substring
						if (intLastBlank <= 1) {
							// no blank or blank on first position found
							intLastBlank = MAX_CHARPERLINE;
						}
						index += intLastBlank; // set new index to last index
												// of blank +1
						strSubStr = arrTextSplits[i].substr(index); // get new
																	// substring
																	// of
																	// characters
																	// starting
																	// from new
																	// index to
																	// check if
																	// still too
																	// long
						intCharLength = strSubStr.length;
						intLines++;
					}
				}
			} else {
				// it was only a \n
				intLines++;
			}
			i++;
		}
	}

	if (intLines > MAX_LINES
			|| intTextSplitLength > MAX_LINES
			|| (originalText.length - intTextSplitLength * dist + dist) > MAX_CHAR) {
		// if more lines than allowed - get old text
		getSaveElementById(this.document, 'txt').innerHTML = _gc_text;
		objTagDiv.innerHTML = 'Sie k&ouml;nnen noch 1 Zeile eingeben.<br/><span class="textSmall error">(maximal '
				+ MAX_LINES
				+ ' Zeilen � '
				+ MAX_CHARPERLINE
				+ ' Zeichen)</span>\n';
		return false;
	}
	_gc_text = objTagForm.elements['greetingCardMessage'].value;
	var myLength = MAX_CHAR - text.length;
	var strLine = (intLines == MAX_LINES) ? ' Zeile' : ' Zeilen';
	objTagDiv.innerHTML = 'Sie k&ouml;nnen noch '
			+ String(MAX_LINES - intLines + 1) + strLine + ' und ' + myLength
			+ ' Zeichen eingeben.<br/>(maximal ' + MAX_LINES + ' Zeilen � '
			+ MAX_CHARPERLINE + ' Zeichen)';// <span class="textSmall{if
											// $view->txt_err}Error{/if}"><br>(maximal
											// '+MAX_LINES+' Zeilen)</span>\n

	return true;
}

function setBreaks() {
	var objTagForm = document.getElementById('eBann')

	var originalText = objTagForm.value; // unchanged text
	var text = originalText; // changed text

	var arrTextSplits = text.split('\n');
	var intTextSplitLength = arrTextSplits.length;

	var i = 0; // runningVar for while
	var intCharLength = 0; // number of characters between two \n
	var index = 0; // index to get substrings of lines
	var strSubStr = ''; // substring of lines
	var intLastBlank = 0; // position of last blankspace in substring
	var strToArray = '' // substring which will be inserted into array

	// Iteration of Splits
	while (i < intTextSplitLength) {
		arrTextSplits[i] = arrTextSplits[i].replace(/\r/, "");
		intCharLength = arrTextSplits[i].length; // number of characters
													// between two \n
		if (intCharLength != 0) {
			if (intCharLength > MAX_CHARPERLINE) {
				// more than MAX_CHARPERLINE characters
				index = 0;
				while (intCharLength > MAX_CHARPERLINE) {
					strSubStr = arrTextSplits[i].substr(index, MAX_CHARPERLINE); // substring
																					// of
																					// 40
																					// characters
																					// starting
																					// with
																					// 0
					intLastBlank = strSubStr.lastIndexOf(" ") + 1; // last
																	// index of
																	// blank in
																	// substring
					if (intLastBlank <= 1) {
						// no blank or blank on first position found
						intLastBlank = MAX_CHARPERLINE;
					}
					strToArray = arrTextSplits[i].substr(index, intLastBlank);
					// add string to array
					arrTextSplits.splice(i, 0, strToArray);
					i++;
					index += intLastBlank; // set new index to last index of
											// blank +1
					strSubStr = arrTextSplits[i].substr(index); // get new
																// substring of
																// 40 characters
																// starting from
																// new index
					intCharLength = strSubStr.length;
				}
				// Ersetzen des originalen arraySplitElements
				arrTextSplits.splice(i, 1, strSubStr);
				intTextSplitLength = arrTextSplits.length;
			}
		}
		i++;
	}
	objTagForm.value = arrTextSplits.join('\n');
}

function clearGreetingMessage(){
	document.getElementById('eBann').value = "";
	Zaehlen();
}

var aform = null;
var set = false;
var setplus = false;

var intv = null;
var intv2 = null;
var intv3 = null;
var maxChar = 500;
var maxLines = 11;
var popupshown = false;
var pattern = "{CHAR} Zeichen";
var pattern2 = "{CHAR} Zeilen";
function Zaehlen() {
	var textfield = getObject("eBann");
	var length = textfield.value.length;
	var value = textfield.value;
	var newContent = "";
//	var count = value.split("\n");
//	var count2 = value.split("\r");
//	var lines = count.length;
//	if (lines == 10) {
//		pattern2 = "{CHAR} Zeile";
//	}

//	if (lines > 10) {
//
//		if (lines == 11 && !set) {
//			set = true;
//			setplus = false;
//		} else if (lines > 11) {
//
//			if (!setplus) {
//				set = false;
//				setplus = true;
//			}
//
//		}
//
//	} else {
//		maxChar = 500;
//		set = false;
//		setplus = false;
//	}

	var left = maxChar - length;

	if (left < 0) {
		newContent = value.substr(0, maxChar);
	}
//	if (lines > 11) {
//		if (!popupshown) {
//			alert("Bitte maximal 11 Zeilen eingeben.");
//			popupshown = true;
//		}
//	} else {
//		popupshown = false;
//	}
//
//	if (lines == 13) {
//		popupshown = false;
//	}
//
//	if (lines > 11 || left < 0) {
//		left = 0;
//	}
//	var leftLines = 11;
//	if (left < 499) {
//		leftLines = maxLines - lines;
//	}
//	if (leftLines < 0) {
//		leftLines = 0;
//	}

//	document.getElementById("sBann2").innerHTML = pattern2.replace("{CHAR}",
//			leftLines);
	document.getElementById("sBann").innerHTML = pattern
			.replace("{CHAR}", left);
}

// Grusstext-Zaehler Zeilen

function CountMax() {

	var greetingObject = document.getElementById("eBann");

	var words = greetingObject.value.split("\n");
	var lines = 0;
	var maxlines = 11;
	var textlength = 0;
	/*
	 * if (document.Grusskarte.greetingCardMessage.value.length > 500) {
	 * alert("Bitte geben Sie nicht mehr als 500 Zeichen ein.");
	 * document.Grusskarte.greetingCardMessage.value =
	 * document.Grusskarte.greetingCardMessage.value.substr(0,500); } else {
	 */
	if (words) {
		for (k = 0; (k < words.length); k++) {
			if (k != 0)
				textlength += 1;
			inLines = Math.ceil(words[k].length / 50);
			lines += inLines;
			if (lines > maxlines) {
				greetingObject.value = greetingObject.value.substr(0,
						textlength + ((inLines - 1) * 50));
				if (greetingObject.value
						.charCodeAt(greetingObject.value.length - 1) == 10) {
					greetingObject.value = greetingObject.value.substr(0,
							greetingObject.value.length - 2);
				}
				lines = maxlines;
				break;
			} else {
				textlength += words[k].length;
			}
		}
	}
}

//	
//	function click (e) {
//	  if (!e)
//	    e = window.event;
//	  if ((e.type && e.type == "contextmenu") || (e.button && e.button == 2) || (e.which && e.which == 3)) {
//	    return false;
//	  }
//	}
//	if (document.layers)
//	  document.captureEvents(Event.MOUSEDOWN);
//
//	document.onmousedown = click;
//	document.oncontextmenu = click;
	
