/*
		constants
	*/
	var MAX_LINES = 10;
	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);
     }
}

/* 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;
		}
		else {
			objTagDiv = document.getElementById('divObjCounter');
		}
		
		
		var originalText = (document.getElementById('text')).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
//			_gc_text = document.getElementById("additionalPuzzleProductMsg"+productId).value;
//			getSaveElementById(this.document,'txt').innerHTML = _gc_text;
			var text = '<span id="error" class="textSmall error" style="padding-left:0px;">Der Text ist zu lang!</span>\n';
		    objTagDiv.innerHTML = text;
			return false;
		}
//		_gc_text = objTagForm.elements['greetingCardMessage'].value;
		var myLength = MAX_CHAR -text.length;
		var strLine = (intLines==MAX_LINES-1)?' Zeile':' Zeilen';
		objTagDiv.innerHTML = 'Sie k&ouml;nnen noch '+ String(MAX_LINES-intLines)+ strLine +' und ' + myLength + ' Zeichen eingeben.';// <span class="textSmall{if $view->txt_err}Error{/if}"><br>(maximal '+MAX_LINES+' Zeilen)</span>\n
		return true;
	}
		
//		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 &agrave; '+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 &agrave; '+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.Grusskarte; //form
		
		var originalText = objTagForm.elements['greetingCardMessage'].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.elements['greetingCardMessage'].value = arrTextSplits.join('\n');
	}
