/*
* Utility stuff that used to be in wizard.js and statemachine.js
*
*/

function createDocument(rootname) {
	if(!rootname)  {
		throw new Error("[statemachine createDocument()] no rootname specified");
	}
	var doc;
	if (document.implementation && document.implementation.createDocument) {
		doc = new DOMParser().parseFromString("<?xml version='1.0' encoding='UTF-8'?><" + rootname + "/>","text/xml");
	} else if (window.ActiveXObject) {
		doc = new ActiveXObject("Microsoft.XMLDOM");   // Create doc
		var root = doc.createElement(rootname);
		doc.appendChild(root);
	}
	return doc;
}

yesNoCancelBox = function(title, msg, callback) {
	callback = (callback || null);
	var url = beng_widget_uri("/beng/res/html/error/confirm.html", getTopWindow().urlSessionId);
	var popupWnd = getTopWindow().createNewPopup();
	popupWnd.setTitle(title);
	popupWnd.arguments = {
						message     : msg,
						callback    : callback,
						yesNoCancel : true
					};
	popupWnd.load(url, 350, 150);
};

/* Ok Button only */
messageBox = function(title, msg, callback, width, height) {
	width = width || 350;
	height = height || 150;
	callback = (callback || null);
	var url = beng_widget_uri("/beng/res/html/error/confirm.html", getTopWindow().urlSessionId);
	var popupWnd = getTopWindow().createNewPopup();
	popupWnd.setTitle(title);
	popupWnd.arguments = {
						message  : msg,
						callback : callback,
						ok       : true
					};
	popupWnd.load(url, width, height);
};

confirmBox = function(title, msg, callback) {
	confirmBoxExtended(title, msg, callback, 350, false);
};


/* Ok / Cancel Buttons */
confirmBoxExtended = function(title, msg, callback, width, warningImg, height) {
	callback = (callback || null);
	var url = beng_widget_uri("/beng/res/html/error/confirm.html", getTopWindow().urlSessionId);
	var popupWnd = getTopWindow().createNewPopup();
	popupWnd.setTitle(title);
	popupWnd.arguments = {
						message  : msg,
						callback : callback,
						okCancel : true,
						warning  : warningImg
					};
	popupWnd.load(url, width, height || 150);
};

confirmReset = function(callback) {
	confirmBox(
	    I18N.xlate(/* "Zurücksetzen" */ "beng.editor", "Reset"),
		I18N.xlate(/* "Wollen Sie alle Änderungen verwerfen?" */ "beng.editor", "Undo all changes?"),
        function(button) {
		    if (button == "OK") {
	            callback();
	        }
	    }
	);
};


form2XML = function (form) {
	var doc = createDocument("FORMULAR");
	var root = doc.documentElement;

	for (var i=0; i < form.elements.length; i++) {
		var elem 		= form.elements[i];
		if(elem.nodeName == "OBJECT" || !elem.name)
			continue;
		var isCDATA 	= (elem.nodeName == "TEXTAREA" || elem.nodeName == "INPUT" && elem.type == "TEXT");
		var nameToSet	= elem.name;
		var valueToSet	= elem.value;

		if (elem.nodeName == "INPUT" && elem.type == "checkbox") {
			if ( !elem.checked ) {
				valueToSet = "" + elem.checked;// means: "false"

			} else if ( elem.value == "on" || elem.value=="" ) {
				// value == on <-> value attribute has not been defined for this checkbox
				// value == "" <-> value is set to empty string, which is the default , see controls.xsl, match="CHECKBOX"
				// If checkbox has no "value" attribute set, "on" seems to be
				// the default value of the "value" attribute ( tested in IE6+7, FF2+3, Opera 9.2, Safari 3.1 on Win
				// for not to break backwards compatibility, we set it to "true" of "false"
				valueToSet = "" + elem.checked;
			} else {
				// otherwise the checkbox has a value which we set the value to
				// if the checkbox is checked
				isCDATA = true; // the value may be weird character data. See "Beschreibungsbegriffe"
				valueToSet = elem.value;
			}

		}

		if (elem.nodeName == "INPUT" && elem.type == "radio" && !elem.checked) {
			continue;
		}

		// this is a marker, add an attribute t the root node. wizard js sees this as a flag not to
		// dissmiss saving and post the form anyway . See wizard.doSave(),
		if ( nameToSet == "alwayssave" ) {
			root.setAttribute("alwayssave" , "true");
			continue;
		}

		var elemToCreate = doc.createElement(nameToSet);
		root.appendChild( elemToCreate );

		if (true || isCDATA) {
			var cdata = doc.createCDATASection(valueToSet);
			elemToCreate.appendChild(cdata);
		} else {
			var text = doc.createTextNode(valueToSet);
			elemToCreate.appendChild(text);
		}

	}
	return doc;
};

//for developing only, get the exceptions, which prototypjs catches
Ajax.Responders.register({
  onException: function(req, e) {

	if (Object.isString(e)) {
		alert(e);
		return;
	}
    //throw klappt hier leider nicht, weil das auch wieder abgefangen wird
	var message = "Exception: " + e.name + "\n";
	message += "Request: " + req.url + "\n";
	message += "Message: " + e.message + "\n";
	message += "File: " + e.fileName + " (" + e.lineNumber + ")\n\n";
	message += "Stack:\n" + e.stack + "\n";
	alert(message);
  }
});


var jdecode = function(s) {
	var re = /\+/g;
	s = s.replace(re, "%20");
	return decodeURIComponent(s);
};

BlindDownIEFix = function() {
	this.vhide();
	this.vshow();
};

compareDom = function(elem1, elem2) {
	// Hier wird brutal getestet, ob wir uns ein save sparen koennen
	// wer mag, kann die Funktion rekursiv auf dem DOM arbeitend programmieren.
	var str1 = Ajax.Document.toString(elem1);
	var str2 = Ajax.Document.toString(elem2);
	return (str1 == str2);
};

ContentHelper = {
	loadSite : function(options) {
		options.method = "get";
        var url = createBengRequestUrl(
                        "/beng/coma/ContentHelper",
                        { action : "getSite" }
                  );

        return new Ajax.Request(url, options);
	},
	loadPage : function(options, pageId) {
		options.method = "get";

		var url = createBengRequestUrl(
                        "/beng/coma/ContentHelper",
                        { action : "getPage" }
                  );
        return new Ajax.Request(url, options);
	}
};



SelectBox = {
	removeAllOptions : function(selectBox) {
		selectBox = $(selectBox);
		if (!selectBox)
			return null;

		var nlOptions = selectBox.getElementsByTagName("option");

		while (nlOptions.length > 0) {
			selectBox.removeChild(nlOptions.item(0));
		}

		return selectBox;
	},

	addOption : function(selectBox, value, text) {
		selectBox = $(selectBox);
		if (!selectBox)
			return null;
		var option = OPTION({attributes : {value : value}}, text);
		selectBox.appendChild(option);

		return option;
	},

	getSelectedValue : function(selectBox) {
		selectBox = $(selectBox);
		if (!selectBox || selectBox.selectedIndex < 0)
			return null;
		return selectBox.options[selectBox.selectedIndex].value;
	},

	select :  function(selectBox, idx) {
		selectBox = $(selectBox);
		if (!selectBox)
			return null;
		selectBox.selectedIndex = idx;
	}

};



// Setzt die Hoehe eines Iframes entsprechend der Hoehe der beinhalteten Seite
window.updateIframeHeight = function(wnd) {
    if (!wnd || wnd.parent == wnd)
        return;

    var doc = wnd.document;
    try {
        var nl = wnd.parent.document.getElementsByTagName("iframe");
        for (var i=0; i < nl.length; i++) {
            var iframe = nl.item(i);
            if (iframe.contentWindow.document == doc) {
                iframe.style.height = (doc.body.clientHeight + 10) + "px";
            }
        }
    } catch (e) {}
};


// email checks are used in popup_emailedit.html and popup_userAddEdit.html

var utils_illegalChars = new RegExp("[^A-Za-z0-9.!#$%&'*+-/=?^_`{|}~]"); // http://de.wikipedia.org/wiki/E-Mail-Adresse
var utils_EMPTY = 1, utils_TOOSHORT = 2, utils_ILLEGALCHARS = 3, utils_ILLEGALFORMAT = 4, utils_ILLEGALDOMAINNAME = 5;
// TODO : i18n
var utils_emailFormatErrors = ["ok", "Der Wert ist leer", "Adresse ist zu kurz", "Die Adresse enthält ungültige Zeichen",
			"Die Adresse ist in einem ungültigen Format", "Die Adresse enthält einen ungültigen Domainnamen" ];

utils_checkEmail = function( email ) {
	if ( !email || email == "" ) {
		return utils_EMPTY; // name empty
	} else if ( email.length < 6 ) {
		return utils_TOOSHORT; // too short
	} else {
		var arr = email.split("@");
		if ( arr.length != 2 ) {
			return utils_ILLEGALFORMAT;
		}
		var check = utils_checkEmailName( arr[0] );
		if ( check != 0 )
			return check;

		var arr2 = arr[1].split("."); // domain name
		if ( arr2.length < 2 || arr2[0].length < 2 || arr2[1].length < 2 ) // at least something like "ct.de"
			return utils_ILLEGALDOMAINNAME;
	}

	return 0;
}

utils_checkEmailName = function ( name ) {
	if ( !name || name == "" ) {
		return utils_EMPTY;
	} else if ( name.length < 1 ) {
		return utils_TOOSHORT;
	} else if ( utils_illegalChars.exec(name) ) {
		return utils_ILLEGALCHARS;
	}
	return 0;
}



