
function GetElementByCWId(cwid, pnode)
{
	if(cwid == '')
		return;
	
	var nodes = null;
	if(pnode != null)
	{
		nodes = pnode.getElementsByTagName("*");
	}
	else
	{
		nodes = document.getElementsByTagName("*");
	}
	var object = null;

	for(i = 0; i < nodes.length; i++)
	{
		if(GetCWId(nodes[i]) == cwid)
		{
			object = nodes[i];
			break;
		}
	}

	if(object == null)
		object = document.getElementById(cwid);

	if(object == null)
		object = document.getElementsByName(cwid)[0];
	
	nodes = null;
	
	try {
		return object;
	}
	finally { object = null; }
}
function GetCWId(object)
{
	//TODO: merge - jan 02242009
	if(object && object.attributes && object.attributes['cwid'] == null)
		return object.id;
	return attr.value;
}

String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}
function utf8_decode(data)
{
    var tmp_arr = [], i, ac, c1, c2, c3;
    i = ac = c1 = c2 = c3 = 0;

    data += '';

    while( i < data.length )
    {
        c1 = data.charCodeAt(i);
        if(c1 < 128)
        {
            tmp_arr[ac++] = String.fromCharCode(c1);
            i++;
        }
        else if
        ((c1 > 191) && (c1 < 224))
        {
            c2 = data.charCodeAt(i+1);
            tmp_arr[ac++] = String.fromCharCode(((c1 & 31) << 6) | (c2 & 63));
            i += 2;
        }
        else
        {
            c2 = data.charCodeAt(i+1);
            c3 = data.charCodeAt(i+2);
            tmp_arr[ac++] = String.fromCharCode(((c1 & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
            i += 3;
        }
    }
    
    i = ac = c1 = c2 = c3 = null;
    try {
    	return tmp_arr.join('');
    }
    finally { tmp_arr = null; }
}
function base64_decode(data)
{
    var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
    var o1, o2, o3, h1, h2, h3, h4, bits, i = ac = 0, dec = "", tmp_arr = [];

    data += '';

    do{
        h1 = chars.indexOf(data.charAt(i++));
        h2 = chars.indexOf(data.charAt(i++));
        h3 = chars.indexOf(data.charAt(i++));
        h4 = chars.indexOf(data.charAt(i++));

        bits = h1 << 18 | h2 << 12 | h3 << 6 | h4;

        o1 = bits >> 16 & 0xff;
        o2 = bits >> 8 & 0xff;
        o3 = bits & 0xff;

        if(h3 == 64)
        {
            tmp_arr[ac++] = String.fromCharCode(o1);
        }
        else if(h4 == 64)
        {
            tmp_arr[ac++] = String.fromCharCode(o1, o2);
        }
        else
        {
            tmp_arr[ac++] = String.fromCharCode(o1, o2, o3);
        }
    }while(i < data.length);

    dec = tmp_arr.join('');
    dec = utf8_decode(dec);
    
    o1 = o2 = o3 = h1 = h2 = h3 = h4 = bits = i = ac = tmp_arr = null;
    return dec;
}
function json_encode (mixed_val)
{
    var retVal, json = this.window.JSON;
    try
    {
		if(typeof json === 'object' && typeof json.stringify === 'function')
		{
			retVal = json.stringify(mixed_val);
			if (retVal === undefined)
			{
				throw new SyntaxError('json_encode');
            }
            return retVal;
        }
        var value = mixed_val;
 
        var quote = function (string) {
            var escapable = /[\\\"\u0000-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;
            var meta = {'\t': '\\t','\n': '\\n','\f': '\\f','\r': '\\r','"' : '\\"','\\': '\\\\'};
 
            escapable.lastIndex = 0;
            
            return escapable.test(string) ? '"' + string.replace(escapable, function (a) {
																			var c = meta[a];
																			return typeof c === 'string' ? c :
                                											'\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
                                											}) + '"' : '"' + string + '"';
        };
 
        var str = function (key, holder) {            var gap = '';
            var indent = '    ';
            var i = 0;
            var k = '';
            var v = '';
            var mind = gap;
            var partial = [];
            var value = holder[key];
            
            if (value && typeof value === 'object' &&
                typeof value.toJSON === 'function') {
                value = value.toJSON(key);
            } 
   
            switch (typeof value) {
                case 'string':
                    return quote(value); 
                case 'number':
                    return isFinite(value) ? String(value) : 'null';
                 case 'boolean':
                case 'null':
                    return String(value);
                case 'object':
                    if (!value) {
                        return 'null';
                    }
                    if ((this.PHPJS_Resource && value instanceof this.PHPJS_Resource) ||
                        (window.PHPJS_Resource && value instanceof window.PHPJS_Resource)) {
                        throw new SyntaxError('json_encode');
                    } 
                    gap += indent;
                    partial = [];
                    if (Object.prototype.toString.apply(value) === '[object Array]') {
                         length = value.length;
                        for (i = 0; i < length; i += 1) {
                            partial[i] = str(i, value) || 'null';
                        }
                        v = partial.length === 0 ? '[]' :
                                gap ? '[\n' + gap +
                                partial.join(',\n' + gap) + '\n' +                                mind + ']' :
                                '[' + partial.join(',') + ']';
                        gap = mind;
                        return v;
                    } 
                    for (k in value) {
                        if (Object.hasOwnProperty.call(value, k)) {
                            v = str(k, value);                            if (v) {
                                partial.push(quote(k) + (gap ? ': ' : ':') + v);
                            }
                        }
                    } 
                    v = partial.length === 0 ? '{}' :
                            gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' +                            mind + '}' : '{' + partial.join(',') + '}';
                    gap = mind;
                    return v;
                case 'undefined':
                case 'function':
                    throw new SyntaxError('json_encode');
            }
        };
        return str('', {
            '': value
        });    
    } catch(err) { 
        if (!(err instanceof SyntaxError)) {
            throw new Error('Unexpected error type in json_encode()');        }
        this.php_js = this.php_js || {};
        this.php_js.last_error_json = 4;
        return null;
    }
}
  
function IsControlID(ControlID)
{
	var ControlInfo = base64_decode(ControlID).split('|');
	if(ControlInfo.length >= 4)
	{
		return true;
	}
	return false;
}
function ExpandCommentPanel(imgpath, sender, panel)
{
	if (sender.src == imgpath+'/images/list-add.png')
	{
		sender.src = imgpath+'/images/list-remove.png';
		document.getElementById(panel).style.display = 'block';
	}
	else
	{
		sender.src = imgpath+'/images/list-add.png';
		document.getElementById(panel).style.display = 'none';
	}

}

var CurrentEvent = null;
var CurrentID = null;
var SaveStyle = "";
CurrentInformation = new function()
{
    this.SelectedObject = null;
    this.SelectedAggregationObject = null;
    this.SelectedElementObject = null;

    this.FillingMethod = null;

    this.SelectionMultiElement = new Array();
    this.CtrlMultiElement = new Array();
    
    this.PersistantHighlightControls = new Array();
    this.DataboxDimensions = new Array();

    this.AggregationCallback = null;

    this.IsFillingField = false;

    /*
    * Modes:
    * 1: Regular Select Mode
    * 2: Aggregation Select Mode
    * 3: Element Select Mode
    * 4: Multiselect mode (elements)
    * 5: ?
    * 6: Diagram Select Mode
    * 7: Action Select Mode
    */
    this.Mode = 1;

    this.IsInLockMode = 0;

    this.TextBoxPosition = -1;

    this.SaveStyle = "";
    this.SaveStyleObjects = new Object();

    this.HighlightedActionList = new Array();

    // object, class
    this.CurrentActiveTab = new Array();

    this.ControlIDAlias = new Array();

};
function ResetCurrentInformation (obj)
    {
    	obj.SelectedObject = null;
	    obj.SelectedAggregationObject = null;
	    obj.SelectedElementObject = null;

	    obj.FillingMethod = null;

	    obj.SelectionMultiElement = new Array();

	    obj.PersistantHighlightControls = new Array();
	    obj.DataboxDimensions = new Array();

	    obj.AggregationCallback = null;

	    obj.IsFillingField = false;

	    obj.Mode = 1;

	    obj.IsInLockMode = 0;

	    obj.TextBoxPosition = -1;

	    obj.SaveStyle = "";
	    obj.SaveStyleObjects = new Object();

	    obj.HighlightedActionList = new Array();

	    // object, class
	    //obj.CurrentActiveTab = new Array();
	    
        obj.ControlIDAlias = new Array();
    }
function GetObjectType(object)
{
	var oType = object.type;
	if (oType == null)
	{
		//if(object.tagName == "TABLE")
	   	oType = object.tagName;
	}
    return oType;
}
function ShowControl_Internal(ControlID, Style, CallingControl)
{
	var Style = Style || "dashed red 3px";
	var Object = null;
	var frame = window.document.getElementById('CwLogicEditor');
	if(frame)
	{
		Object = GetElementByCWId(ControlID, frame.contentWindow.document);
	}
	else
	{
		Object = GetElementByCWId(ControlID);
	}
	if (Object != null)
	{
		if(/(checkbox|radio)/i.test(Object.type)) {
			if(/logic-element/i.test(Object.parentNode.className)) {
				Object = Object.parentNode;
			}
			else {
				var span = document.createElement('span');
				Object.parentNode.insertBefore(span, Object);
				span.className = 'logic-element';
				span.appendChild(Object);
				Object = span;
			}	
		}
		
		SaveStyle = Object.style.border;	
		Object.orgborder = Object.style.border = Style;
	}
	else if(CallingControl != undefined && /(checkbox|radio)/i.test(CallingControl.type)) {
		Object = CallingControl;
		if(/logic-element/i.test(Object.parentNode.className)) {
			Object = Object.parentNode;
		}
		else {
			var span = document.createElement('span');
			Object.parentNode.insertBefore(span, Object);
			span.className = 'logic-element';
			span.appendChild(Object);
			Object = span;
		}
		SaveStyle = Object.style.border;
		Object.orgborder = Object.style.border = Style;
	}
	frame = null;
	Object = null;
}
function ShowControl(CallingControl, UseAsID, Style, NoAliasRequest)
{
		var Style = Style || "dashed red 3px";
		var ControlID = null;
		if (UseAsID != true)
		{
			ControlID = (CallingControl.value == null) ? CallingControl.innerHTML : CallingControl.value;
		}
		else
		{
			ControlID = CallingControl;
		}
	
		ControlID = ControlID.trim();
       if(!NoAliasRequest && ControlID && !CurrentInformation.ControlIDAlias[ControlID])
       {
	       SimpleWebAppRequest({'exec':'GetControlID','params':[ControlID,
								document.getElementById('cwAutoControl[GlobalCwAppID]').innerHTML,
								document.getElementById('cwAutoControl[GlobalCwAppVersion]').innerHTML]},
								function(Param){
			                        ShowControl_Internal(Param.ControlID, Style, CallingControl);
			                        CurrentInformation.ControlIDAlias[Param.Alias] = Param.ControlID;
			                        window.setTimeout(function(){CurrentInformation.ControlIDAlias[Param.Alias] = null;}, 5000);
						});
	   }
	   else
	   {
	   		var InternalControlID = (CurrentInformation.ControlIDAlias[ControlID] ? CurrentInformation.ControlIDAlias[ControlID] : ControlID);
	   		ShowControl_Internal(InternalControlID, Style, CallingControl);
	   		InternalControlID = null;	
	   }
	   ControlID = null;
}
function UnshowControl_Internal(ControlID, CallingControl)
{
	var Object = null;
	
	var frame = window.document.getElementById('CwLogicEditor');
	if(frame)
	{
		Object = GetElementByCWId(ControlID, frame.contentWindow.document);
	}
	else
	{
		Object = GetElementByCWId(ControlID);
	}	
	//}
	if (Object != null)
	{
		if(/(checkbox|radio)/i.test(Object.type)) {
			if(/logic-element/i.test(Object.parentNode.className)) {
				Object = Object.parentNode;
			}
		}
		Object.style.border = SaveStyle;
		// IE (5.5, 6, 7) restore border
		if('\v'=='v' && SaveStyle == '') {
			Object.style.borderColor = Object.style.borderWidth = Object.style.borderStyle = '';
		}

		SaveStyle = "";
	} 
	else if(CallingControl != undefined && /(checkbox|radio)/i.test(CallingControl.type)) {
		Object = CallingControl;
		if(/logic-element/i.test(Object.parentNode.className)) {
			Object = Object.parentNode;
		}

		Object.style.border = SaveStyle;
		// IE (5.5, 6, 7) restore border
		if('\v'=='v' && SaveStyle == '') {
			Object.style.borderColor = Object.style.borderWidth = Object.style.borderStyle = '';
		}

		SaveStyle = "";
	}
	frame = null;
	Object = null;
}
function UnshowControl(CallingControl, UseAsID, NoAliasRequest)
{
	var ControlID = null;
	if (UseAsID != true)
	{
		ControlID = (CallingControl.value == null) ? CallingControl.innerHTML : CallingControl.value;
	}
	else
	{
		ControlID = CallingControl;
	}
	if(ControlID && !CurrentInformation.ControlIDAlias[ControlID] && !NoAliasRequest)
	{
		 SimpleWebAppRequest({'exec':'GetControlID','params':[ControlID,
							document.getElementById('cwAutoControl[GlobalCwAppID]').innerHTML,
							document.getElementById('cwAutoControl[GlobalCwAppVersion]').innerHTML]},
							function(Param){ 
								UnshowControl_Internal(Param.ControlID, CallingControl);
								CurrentInformation.ControlIDAlias[Param.Alias] = Param.ControlID; 
								window.setTimeout(function(){CurrentInformation.ControlIDAlias[Param.Alias] = null;}, 5000);
							});
	}
	else
	{
		var InternalControlID = (CurrentInformation.ControlIDAlias[ControlID] ? CurrentInformation.ControlIDAlias[ControlID] : ControlID);
		UnshowControl_Internal(InternalControlID, CallingControl); 
		InternalControlID = null;	
	}
	ControlID = null;
}
function MakeActionsSortable()
{
    cwOffice.sortable(document.getElementById('cwAutoControl[PopupContent]').getElementsByTagName('table')[0], {
        "xAxis": true,
        "callback" : {
        "drop" : function(replaced, draged) {
            var rJson = {
                "php" : ["BerkeWebflowEditorLogicDatabox", "ChageActionSorting"],
                    "event" : null,
                    "getControls" : []
                };

                var trs = this.rootNode.getElementsByTagName('tr');
                for(var i=0;i<trs.length;i++) {
                    if(trs[i].getAttribute('sortable', 0) != null) {
                        var sortorpos = parseInt(trs[i].getAttribute('sortorpos', 0));
                        var sortindex = parseInt(trs[i].getAttribute('sortindex', 0));

                            rJson["getControls"].push({
                                "Name" : "ID",
                                "RepeaterName": "Actions",
                                "RepeaterRepID" : (sortorpos),
                                "getAttributes": {
                                    "value" : true
                                }
                            });
                            rJson["getControls"].push({
                                "Name" : "ActiveVersionID",
                                "RepeaterName": "Actions",
                                "RepeaterRepID" : (sortorpos),
                                "getAttributes": {
                                    "value" : true
                                }
                            });
                        }
                    }
                rJson["getControls"].push({"n":"GlobalCwAppID","a":{"v":true}});
                rJson["getControls"].push({"n":"GlobalCwAppVersion","a":{"v":true}});
                jS.queue.pA.set(rJson);
                rJson = null;
                trs = null;
            }
        }
    });
}
function MakeReturnControlsSortable()
{
    try{
        cwOffice.sortable(document.getElementById('DataboxActionReturnControls'), {
            "xAxis": true,
            "callback" : {
                "drop" : function(replaced, draged) {
                    var rJson = {
                        "php" : ["BerkeWebflowEditorLogicDatabox", "EditOutputSingleElement_Sorting"],
                        "event" : null,
                        "getControls" : []
                    };
                    
                    var trs = this.rootNode.getElementsByTagName('tr');
                    for(var i=0;i<trs.length;i++) {
                        if(trs[i].getAttribute('sortable', 0) != null) {
                            var sortorpos = parseInt(trs[i].getAttribute('sortorpos', 0));
                            var sortindex = parseInt(trs[i].getAttribute('sortindex', 0));
                            
                            rJson["getControls"].push({
                                "Name" : "ControlID",
                                "RepeaterName": "OutputControls",
                                "RepeaterRepID" : (sortorpos),
                                "getAttributes": {
                                    "value" : true
                                }
                            })
                        }    
                    }
                    rJson["getControls"].push({"n":"GlobalCwAppID","a":{"v":true}});
                    rJson["getControls"].push({"n":"GlobalCwAppVersion","a":{"v":true}});
                    rJson["getControls"].push({"n":"RemeberControl","a":{"v":true}});
                    jS.queue.pA.set(rJson);
                    
                    rJson = null;
                    trs = null;
                }
            }
        }); 
    }
    catch(e)
    {
        console.warn(e);
    }   
}
function AutoShowDataBox(ControlID)
{
	var Frame = document.getElementById('CwLogicEditor');
	var obj = Frame.contentDocument.getElementById(ControlID);
	
	UpdateMousePosition = false;
	
	document.getElementById('sys_winy').value = absTop(obj)+(obj.clientHeight/2);
	document.getElementById('sys_winx').value = absLeft(obj)+(obj.clientWidth/2);
		
	CurrentID = ControlID;
	Identify(null, obj);
	
	UpdateMousePosition = true;
	
	Frame = null;
	obj = null;
}
function Identify(event, object, CallDataBox)
{
	if(event && event.preventDefault)
	{
		event.preventDefault();
	}
	
	// make sure the correct element is being handled only works with the bubbeling effect
	if (!IsControlID(CurrentID))
	{
		CurrentID = GetCWId(object);
	}
	if (CurrentID == GetCWId(object))
	{
 		//console.info(object);
		var attr = object.attributes['translation'];
		var MyDiv = null;
		if(!event.ctrlKey && CurrentInformation.Mode == 1 && CallDataBox == undefined && attr && attr.value == 'true')
		{
			HideDataBox();
			if(CurrentInformation.IsInLockMode == 0)
			{
				MyDiv = document.getElementById('SelectLogicAction');
				if(MyDiv)
				{
					MyDiv.style.display = 'block';
					MyDiv.style.top = getCoord("y")+(window.pageYOffset?window.pageYOffset:0) + 'px';
					MyDiv.style.left = getCoord("x")+(window.pageXOffset?window.pageXOffset:0) + 'px';

					var ElemStyle = 'style="cursor:pointer;width:150px;"';
					//console.info("window.frames[0].document.getElementById('"+CurrentID+"')");
					MyDiv.innerHTML = "<div class=\"ContainerLink\" "+ElemStyle+" onclick=\"Identify(event, window.frames[0].document.getElementById('"+CurrentID+"'), true)\">"+ServerVars.Language.ShowDataBox+"</div>";
					MyDiv.innerHTML += "<div class=\"ContainerLink\" "+ElemStyle+" onclick=\"javascript:ShowWFTemplateInDataBox(event, '"+object.value+"', '"+ServerVars.TranslationTemplateID+"&Key="+object.value+"&JSFunc=parent.HideDataBox();')\">"+ServerVars.Language.EditTranslation+"</div>";
				}
				MyDiv = null;
			}
			return;
		}
		MyDiv = document.getElementById('SelectLogicAction');
		if(MyDiv)
		{
			MyDiv.style.display = 'none';
		}

		// only run if lock mode is not active
		if (CurrentInformation.IsInLockMode == 0)
		{
			if(!event.ctrlKey)
			{
				for(var c = 0; c < CurrentInformation.CtrlMultiElement.length; c++)
				{
					UnshowControl(CurrentInformation.CtrlMultiElement[c], true, true);
				}
				CurrentInformation.CtrlMultiElement = null;
				CurrentInformation.CtrlMultiElement = new Array();
				HideMultiElementOptionMenue();
				
				// if the regular selection mode is enabled
				if (CurrentInformation.Mode == 1)
				{
					//if(GetObjectType(object) == "IMG")
					//	return;

					var ObjectId = GetCWId(object);
				    //UnHighlightControl(object, true);

				    UnHighlightControl(CurrentInformation.SelectedObject, true);
				    UnHighlightControls(CurrentInformation.SelectionMultiElement, true);
                                                                                                
				    ShowControl(ObjectId, true, 'dashed red 1px');

					CurrentInformation.SelectedObject = object;

				    ShowDataBox();
						 jS.func = function() {
						var databox = document.getElementById('cwAutoControl[Databox]');
						var option = {"ignore":{'middle':true,'autocompletion_box':true}};
						window.cwOffice.drag(databox, option);
						window.cwOffice.resize(databox, {
							"trigger":document.getElementById('databox_resize_corner'), 
							"addSize": {"width":0, "height":100},
							"min-width":440});
						// make actions sortable
						MakeActionsSortable();
						databox = null;
					}
				    var ElementType = (object.type ? object.type : object.tagName);
				jS.queue.pA.set({"php":["BerkeWebflowEditorLogicDatabox","Load"],"event":"click","getControls":[
		    					{"Name":"TemplateEditor_config","getAttributes":{"value":true}},
		    					{"Name":"ObjectID","attributes" :{"value":GetCWId(object)}},
		    					{"Name":"InitialLoad","attributes" :{"value":"YES"}},
		    					{"Name":"HighlightedActions","attributes" :{"value":GetHighlightedActionListString()}},
		    					{"Name":"ObjectType","getAttributes":{"value":ElementType}},
		    					{"Name":"GlobalCwAppID","getAttributes":{"value":true}},
		    					{"Name":"GlobalCwAppVersion","getAttributes":{"value":true}}
		    					]});
		    	}
				else{}

				// if the aggration select mode is enabled
				if (CurrentInformation.Mode == 2 || CurrentInformation.Mode == 5)
				{

						if (CurrentInformation.SelectedAggregationObject != null)
					    {
					        // now unmark the other control
					        CurrentInformation.SelectedAggregationObject.style.border = "";

					        // IE (5.5, 6, 7) restore border
							if('\v'=='v') {
								var element = CurrentInformation.SelectedAggregationObject;
								element.style.borderColor = element.style.borderWidth = element.style.borderStyle = '';
							}
					    }
						ShowNextBox();


					if (IsAggrationControl(object) || CurrentInformation.Mode == 5)
					{
						object.style.border = "dashed blue 1px";
						CurrentInformation.SelectedAggregationObject = object;
						document.getElementById("NextBoxEntry").style.display = "block";
						document.getElementById("NextBoxErrorMsg").style.display = "none";
					}
					else
					{
						document.getElementById("NextBoxEntry").style.display = "none";
						document.getElementById("NextBoxErrorMsg").style.display = "block";
					}
				}
				// if the diagram select mode is enabled
				if (CurrentInformation.Mode == 6)
				{
					if (CurrentInformation.SelectedAggregationObject != null)
					{
						// now unmark the other control
						CurrentInformation.SelectedAggregationObject.style.border = "";

				        // IE (5.5, 6, 7) restore border
						if('\v'=='v') {
							var element = CurrentInformation.SelectedAggregationObject;
							element.style.borderColor = element.style.borderWidth = element.style.borderStyle = '';
						}
					}

					ShowNextBox();

					if(IsDiagramControl(object))
					{

						SaveStyle = object.border;
						object.style.border = "dashed blue 1px";

						CurrentInformation.SelectedAggregationObject = object;
						document.getElementById("NextBoxEntry").style.display = "block";
						document.getElementById("NextBoxErrorMsg").style.display = "none";
					}
					else
					{
						document.getElementById("NextBoxEntry").style.display = "none";
						document.getElementById("NextBoxErrorMsg").style.display = "block";
					}
				}
				// if the element select mode is enabled
				// mode '31' means that all types of controls can be selected
				if (CurrentInformation.Mode == 3  || CurrentInformation.Mode == 31 || CurrentInformation.Mode == 32)
				{
						if (CurrentInformation.SelectedElementObject != null)
					    {
					        // now unmark the other control
					        CurrentInformation.SelectedElementObject.style.border = "";

					        // IE (5.5, 6, 7) restore border
							if('\v'=='v') {
								var element = CurrentInformation.SelectedElementObject;
								element.style.borderColor = element.style.borderWidth = element.style.borderStyle = '';
							}
					    }

						ShowNextBox();

					if (IsElementControl(object) ||  CurrentInformation.Mode == 31 || CurrentInformation.Mode == 32)
					{
						object.style.border = "dashed green 1px";
						CurrentInformation.SelectedElementObject = object;
						document.getElementById("NextBoxElementEntry").style.display = "block";
						document.getElementById("NextBoxElementErrorMsg").style.display = "none";
					}
					else
					{
						document.getElementById("NextBoxElementEntry").style.display = "none";
						document.getElementById("NextBoxElementErrorMsg").style.display = "block";
					}
				}
				if(CurrentInformation.Mode == 7  || CurrentInformation.Mode == 71)
				{
					if (CurrentInformation.SelectedElementObject != null)
					{
						// now unmark the other control
					    CurrentInformation.SelectedElementObject.style.border = "";

					    // IE (5.5, 6, 7) restore border
						if('\v'=='v') {
							var element = CurrentInformation.SelectedElementObject;
							element.style.borderColor = element.style.borderWidth = element.style.borderStyle = '';
						}
					}

					ShowNextBox();

					if (IsElementControl(object) ||  CurrentInformation.Mode == 71)
					{
						object.style.border = "dashed green 1px";
						CurrentInformation.SelectedElementObject = object;
						document.getElementById("NextBoxElementEntry").style.display = "block";
						document.getElementById("NextBoxElementErrorMsg").style.display = "none";
					}
					else
					{
						document.getElementById("NextBoxElementEntry").style.display = "none";
						document.getElementById("NextBoxElementErrorMsg").style.display = "block";
					}

				}
				// if the multi element select mode is enabled
				if (CurrentInformation.Mode == 4)
				{

						if (CurrentInformation.SelectedElementObject != null)
					    {
					        // now unmark the other control
					        CurrentInformation.SelectedElementObject.style.border = "";

					        // IE (5.5, 6, 7) restore border
							if('\v'=='v') {
								var element = CurrentInformation.SelectedElementObject;
								element.style.borderColor = element.style.borderWidth = element.style.borderStyle = '';
							}
					    }

					    // remove from list if already selecte
					    var index = GetElementIndexById(CurrentInformation.SelectionMultiElement, GetCWId(object));

					    if (index == -1)
					    {
							ShowNextBox();
							if (IsElementControl(object))
							{
								object.style.border = "dashed green 1px";
								CurrentInformation.SelectionMultiElement.push(object);
								document.getElementById("NextBoxElementMultiEntry").style.display = "block";
								document.getElementById("NextBoxElementMultiErrorMsg").style.display = "none";
							}
							else
							{
								document.getElementById("NextBoxElementMultiEntry").style.display = "none";
								document.getElementById("NextBoxElementMultiErrorMsg").style.display = "block";

							}
					    }
					    else
					    {
				    		HideNextBox();
				    		// unselect
							object.style.border = "";

					        // IE (5.5, 6, 7) restore border
							if('\v'=='v') {
								object.style.borderColor = object.style.borderWidth = object.style.borderStyle = '';
							}
							CurrentInformation.SelectionMultiElement.splice(index, 1);
					    }


				}
			}
			else
			{ 
				HideDataBox();
				// CTRL PRESSED              
				ShowControl(object.id, true, 'dashed blue 2px', true);
				CurrentInformation.CtrlMultiElement.push(object.id);
				ShowMultiElementOptionMenue();
			}
		}
		else
		{
			var Proceed = confirm("Attention: This action has not been saved yet, are you sure to leave this window?");
			if (Proceed)
			{
				// unlock
				SetUnlockMode();
				// run this again
				Identify(event, object);
			}
		}
		MyDiv = null;

	}
	return false;
	/*else
	{
		alert(CurrentID + " "+ object.id);
	}*/
}
function ShowWFTemplateInDataBox(e, Key, AppID)
{
	var e = e || window.event;

	var MyDiv = document.getElementById('SelectLogicAction');
	if(MyDiv){MyDiv.style.display = 'none';}

	ShowDataBox();
	jS.func = function() {
			var databox = document.getElementById('cwAutoControl[Databox]');
			//var option = {};
			//if('\v'=='v') option = {"trigger":databox.getElementsByTagName('div')[0].getElementsByTagName('div')[0]};
			var option = {"ignore":{'middle':true,'autocompletion_box':true}};
			window.cwOffice.drag(databox, option);
			window.cwOffice.resize(databox, {
				"trigger":document.getElementById('databox_resize_corner'), 
				"addSize": {"width":0, "height":100},
				"min-width":440});
			// make actions sortable
			databox = null;
		}
	jS.queue.pA.set({"php":[
						"BerkeWebflowEditorLogicDatabox","ShowWFTemplateInDataBox"
						],
						"event":"click",
						"getControls":[
							{"n":"TextKey","a" :{"value":Key}},
							{"n":"AppID","a" :{"value":AppID}},
							{"n":"GlobalCwAppID","a":{"v":true}},
							{"n":"GlobalCwAppVersion","a":{"v":true}}
						]});

	if('\v' == 'v') {
		e.cancelBubble=true;
	}
	else {
		e.stopPropagation();
	}
}

function GetElementIndexById(Array, Name)
{
	var vRet = -1;
	for (i = 0; i < Array.length; i++)
	{
		if (GetCWId(Array[i]) == Name)
		{
			vRet = i;
		}
	}
	return vRet;
}
function IsAggrationControl(object)
{
	return (object.tagName == "TABLE" && object.type == null || object.type == "select-one");
}
function IsDiagramControl(object)
{
	return (object.tagName == "IMG" && object.type == null);
}
function IsElementControl(object)
{
	return (object && (object.type != null || IsDiagramControl(object)));
}
function SelectAggregationControl(Callback, IsFillingField)
{
	CurrentInformation.AggregationCallback = Callback;
	CurrentInformation.IsFillingField = IsFillingField;
	// first: hide the databox
	var box = document.getElementById('cwAutoControl[Databox]');
	box.style.display = "none";

	// then show message
	/*message = document.getElementById('blackBox');
	message.style.display = "block";
	message = document.getElementById('whiteBox');
	message.style.display = "block";*/

	if(cwOffice.keybind)
		document.getElementById('CwLogicEditor').contentWindow.ArrowKeysInputMovement.setKeybinds();
	
	CurrentInformation.Mode = 2;

	// unlock
	SetUnlockMode();
	
	box = null;
}
function SelectDiagramControl(Callback, IsFillingField)
{
	CurrentInformation.AggregationCallback = Callback;
	CurrentInformation.IsFillingField = IsFillingField;
	// first: hide the databox
	var box = document.getElementById('cwAutoControl[Databox]');
	box.style.display = "none";

	CurrentInformation.Mode = 6;

	if(cwOffice.keybind)
		document.getElementById('CwLogicEditor').contentWindow.ArrowKeysInputMovement.setKeybinds();
	
	// unlock
	SetUnlockMode();
	
	box = null;
}
function OutputToMessageBox(Callback, IsFillingField)
{
	jS.queue.pA.set({"name": "BerkeWebflowEditorLogic",
					"php":[
						"BerkeWebflowEditorLogicDatabox","AddActionStep4_ExecCommand_SelectReturnFields_Save"
					],
					"getControls":[
						{"Name":"RemeberControl","getAttributes" :{"value":true}},
						{"Name":"TemplateEditor_config","getAttributes" :{"value":true}},
						{"Name":"ID","getAttributes" :{"value":true}},
						{"Name":"Method","attributes" :{"value":"MessageBox"}},
						{"Name":"FillingControl","attributes" :{"value":"CwMessageBoxControl"}},
						{"n":"ObjectType","a":{"v":true}},
						{"n":"GlobalCwAppID","a":{"v":true}},
						{"n":"GlobalCwAppVersion","a":{"v":true}}
					] });

	// unlock
	SetUnlockMode();
}
function OutputToJavaScript(Callback, IsFillingField)
{
	jS.queue.pA.set({"name": "BerkeWebflowEditorLogic",
					"php":[
						"BerkeWebflowEditorLogicDatabox","AddActionStep4_ExecCommand_SelectReturnFields_Save"
					],
					"getControls":[
						{"Name":"RemeberControl","getAttributes" :{"value":true}},
						{"Name":"TemplateEditor_config","getAttributes" :{"value":true}},
						{"Name":"ID","getAttributes" :{"value":true}},
						{"Name":"Method","attributes" :{"value":"JavaScript"}},
						{"Name":"FillingControl","attributes" :{"value":"CwJavaScriptControl"}},
						{"n":"ObjectType","a":{"v":true}},
						{"n":"GlobalCwAppID","a":{"v":true}},
						{"n":"GlobalCwAppVersion","a":{"v":true}}
					] });

	// unlock
	SetUnlockMode();
}
function OutputToAutoCompletion(Callback, IsFillingField)
{
	jS.queue.pA.set({"name": "BerkeWebflowEditorLogic",
					"php":[
						"BerkeWebflowEditorLogicDatabox","AddActionStep4_ExecCommand_SelectReturnFields_Save"
					],
					"getControls":[
						{"Name":"RemeberControl","getAttributes" :{"value":true}},
						{"Name":"TemplateEditor_config","getAttributes" :{"value":true}},
						{"Name":"ID","getAttributes" :{"value":true}},
						{"Name":"Method","attributes" :{"value":"JavaScript"}},
						{"Name":"FillingControl","attributes" :{"value":"CwAutoCompletionControl"}},
						{"n":"ObjectType","a":{"v":true}},
						{"n":"GlobalCwAppID","a":{"v":true}},
						{"n":"GlobalCwAppVersion","a":{"v":true}}
					] });

	// unlock
	SetUnlockMode();
}
function OutputToVariable(Callback, IsFillingField)
{
	jS.queue.pA.set({"name": "BerkeWebflowEditorLogic",
					"php":[
						"BerkeWebflowEditorLogicDatabox","AddActionStep4_ExecCommand_SelectReturnFields_Save"
					],
					"getControls":[
						{"Name":"VariableName","getAttributes" :{"value":true}},
						{"Name":"RemeberControl","getAttributes" :{"value":true}},
						{"Name":"TemplateEditor_config","getAttributes" :{"value":true}},
						{"Name":"ID","getAttributes" :{"value":true}},
						{"Name":"Method","attributes" :{"value":"Variable"}},
						{"Name":"FillingControl","attributes" :{"value":"CwVariableControl"}},
						{"n":"ObjectType","a":{"v":true}},
						{"n":"GlobalCwAppID","a":{"v":true}},
						{"n":"GlobalCwAppVersion","a":{"v":true}}
					] });

	// unlock
	SetUnlockMode();
}
function SelectControl(Callback, IsFillingField, ActionID, AjaxHandlerControls)
{
	CurrentInformation.AggregationCallback = Callback;
	CurrentInformation.IsFillingField = IsFillingField;
	CurrentInformation.ActionID = ActionID;
	CurrentInformation.AjaxHandlerControls = AjaxHandlerControls;
    
    // first: hide the databox
	var box = document.getElementById('cwAutoControl[Databox]');
	box.style.display = "none";

	// then show message
	/*message = document.getElementById('blackBox');
	message.style.display = "block";
	message = document.getElementById('whiteBox');
	message.style.display = "block";*/

	if(cwOffice.keybind)
		document.getElementById('CwLogicEditor').contentWindow.ArrowKeysInputMovement.setKeybinds();
	
	CurrentInformation.Mode = 5;

	// unlock
	SetUnlockMode();

	box = null;
}
function SelectMultiElementsControl(Callback, IsFillingField, ActionID)
{
	CurrentInformation.AggregationCallback = Callback;
	CurrentInformation.IsFillingField = IsFillingField;
	CurrentInformation.ActionID = ActionID;
	// first: hide the databox
	var box = document.getElementById('cwAutoControl[Databox]');
	box.style.display = "none";

	/*
	// then show message
	message = document.getElementById('blackBox');
	message.style.display = "block";
	message = document.getElementById('whiteBox');
	message.style.display = "block";*/

	if(cwOffice.keybind)
		document.getElementById('CwLogicEditor').contentWindow.ArrowKeysInputMovement.setKeybinds();
	
	CurrentInformation.Mode = 4;

	// unlock
	SetUnlockMode();

	box = null;
}
function SelectSingleElementControl(Callback, FillingMethod)
{
	CurrentInformation.AggregationCallback = Callback;
	CurrentInformation.FillingMethod = FillingMethod;

	var box = document.getElementById('cwAutoControl[Databox]');
	box.style.display = "none";

	CurrentInformation.Mode = 32;

	SetUnlockMode();
	
	box = null;
}
/*If IsFillingField is true, the callback wont be executed, instead
the value of Callback will be used as a control ID*/
function SelectElementControl(Callback, IsFillingField, PromiscuousMode)
{
	// first: hide the databox
	var box = document.getElementById('cwAutoControl[Databox]');
	box.style.display = "none";

	// then show message
	CurrentInformation.IsFillingField = IsFillingField;
	CurrentInformation.AggregationCallback = Callback;

	if (!PromiscuousMode)
	{
		CurrentInformation.Mode = 3;
	}
	else
	{
		CurrentInformation.Mode = 31;
	}
	// save textbox position


	// unlock
	SetUnlockMode();
	
	box = null;
}
function SelectActionControl(Callback, IsFillingField, PromiscuousMode)
{
	// first: hide the databox
	var box = document.getElementById('cwAutoControl[Databox]');
	box.style.display = "none";

	// then show message
	CurrentInformation.IsFillingField = IsFillingField;
	CurrentInformation.AggregationCallback = Callback;

	if (!PromiscuousMode)
	{
		CurrentInformation.Mode = 7;
	}
	else
	{
		CurrentInformation.Mode = 71;
	}
	// save textbox position


	// unlock
	SetUnlockMode();
	
	box = null;
}
function HighlightControl(controlId, color, persistant)
{
	var control = null;
	var frame = window.document.getElementById('CwLogicEditor');
	if(frame)
	{
		control = GetElementByCWId(controlId, frame.contentWindow.document);
	}
	else
	{
		control = GetElementByCWId(controlId);
	}
	if (control != null)
	{
		control.style.border = "dashed "+color+" 1px";
		if (persistant)
		{
			CurrentInformation.PersistantHighlightControls[ controlId ] = control;
		}
		else
		{
			CurrentInformation.SelectedObject = control;
		}
	}
	
	control = null;
	frame = null;
}
function UnHighlightControl(object, ignorePersistantControls)
{
	if (object != null)
	{
		if (CurrentInformation.PersistantHighlightControls[GetCWId(object)] != null && !ignorePersistantControls)
		{
			object.style.border = "";

			// IE (5.5, 6, 7) restore border
			if('\v'=='v') {
				object.style.borderColor = object.style.borderWidth = object.style.borderStyle = '';
			}

			//remove from persistant list
			CurrentInformation.PersistantHighlightControls[GetCWId(object)] = null;
		}

		if (CurrentInformation.PersistantHighlightControls[GetCWId(object)] == null)
		{
			UnshowControl(object);
//			object.style.border = "";
//
//			// IE (5.5, 6, 7) restore border
//			if('\v'=='v') {
//				object.style.borderColor = object.style.borderWidth = object.style.borderStyle = '';
//			}
		}
	}
}

function UnHighlightControls(list, ignorePersistantControls)
{
	for (i = 0; i < list.length; i++)
	{
		UnHighlightControl(list[i], ignorePersistantControls);
	}
	// clear array
	list.splice(0, list.length);
}
function RequiredFieldsData()
{
	this.Highlighted = new Array();
	this.oldBackground = new Object();
	this.oldClassName = new Object();
}
var RFData = new RequiredFieldsData();

function UnHighlightRequiredFields(ActionID)
{
	if(RFData.Highlighted[ActionID] !== undefined)
	{
		var obj = RFData.Highlighted[ActionID];
		if(obj)
		{
			for(i = 0; i < obj.length; i++)
			{
				//var object = GetElementByCWId(obj[i]);
				var object = document.getElementById(obj[i]);
				if(object == null)
				{
					object = document.getElementsByName(obj[i])[0];
				}
				if(object)
				{
					//object.style.backgroundColor = RFData.oldBackground[obj[i]];
					object.className = RFData.oldClassName[obj[i]];
					var ErrObj = document.getElementById(obj[i]+'_ERR');
					if(ErrObj)
					{
						ErrObj.innerHTML = "";
					}
					ErrObj = null;
				}
				object = null;
			}
			RFData.Highlighted[ActionID].splice(0, RFData.Highlighted[ActionID].length);
			RFData.Highlighted[ActionID] = new Array();
		}
		
		obj = null;
	}
}
// Alias for UnHighlightRequiredFields
function UHRF(ActionID)
{
	UnHighlightRequiredFields(ActionID);
}
function HighlightRequiredFields(ActionID, list)
{
	RFData.Highlighted[ActionID] = new Array();
	for(i = 0; i < list.length; i++)
	{
		var object = document.getElementById(list[i][0]);
		if(object == null)
		{
			object = document.getElementsByName(list[i][0])[0];
		}

		if(object)
		{
			RFData.Highlighted[ActionID].push(list[i][0]);

			//RFData.oldBackground[list[i][0]] = object.style.backgroundColor;
			//object.style.backgroundColor = 'red';
			RFData.oldClassName[list[i][0]] = object.className;
			object.className = 'CwRequiredField';

			var errObj = document.getElementById(list[i][0]+'_ERR');
			if(!errObj)
			{
				errObj = document.createElement('span');
				errObj.id = object.id + '_ERR';
				errObj.className = 'CwRequiredFieldMessage';
				object.parentNode.insertBefore(errObj, object.nextSibling)
			}
			errObj.innerHTML = " "+list[i][1];
			
			errObj = null;
		}
		object = null;
	}
}
function HRF(ActionID, list)
{
	HighlightRequiredFields(ActionID, list);
}
function SetLockMode()
{
	// function to lock window
	CurrentInformation.IsInLockMode = 1;
}
function SetUnlockMode()
{
	// function to lock window
	CurrentInformation.IsInLockMode = 0;
}

function HideMessageBox()
{
	var message = document.getElementById('blackBox');
	message.style.display = "none";
	message = null;
}

var MaximizeDataBoxOrgDim = {'x':0,'y':0,'top':0,'left':0};
function MaximizeDataBox() 
{
	var box = document.getElementById('cwAutoControl[Databox]');
	if(MaximizeDataBoxOrgDim.x < window.screenX || MaximizeDataBoxOrgDim.y < window.screenY)
	{
		MaximizeDataBoxOrgDim.x = parseInt(box.style.width);
		MaximizeDataBoxOrgDim.y = parseInt(box.style.height);
		MaximizeDataBoxOrgDim.top = parseInt(box.style.top);
		MaximizeDataBoxOrgDim.left = parseInt(box.style.left);
		
		box.style.width = top.window.document.body.clientWidth + 'px';
		box.style.height = top.window.document.body.clientHeight + 'px';
		box.style.top = '0px';
		box.style.left = '0px';
	}
	else
	{
		box.style.width = MaximizeDataBoxOrgDim.x + 'px';
		box.style.height = MaximizeDataBoxOrgDim.y + 'px';
		box.style.top =  MaximizeDataBoxOrgDim.top + 'px';
		box.style.left =  MaximizeDataBoxOrgDim.left + 'px';
		MaximizeDataBoxOrgDim = {'x':0,'y':0,'top':0,'left':0};
	}
	box = null;
}
function HideDataBox()
{
	if (CurrentInformation.IsInLockMode == 0)
	{
		UnHighlightControl(CurrentInformation.SelectedObject, true);
		var box = document.getElementById('cwAutoControl[Databox]');
		box.style.display = "none";
		box.innerHTML = "";
		SetUnlockMode();

		if(cwOffice.keybind) {
			cwOffice.keybind.remove(false,true,'ctrl+backspace');
			document.getElementById('CwLogicEditor').contentWindow.ArrowKeysInputMovement.setKeybinds();
		}
		
		box = null;
	}
	else
	{
		var Proceed = confirm(ServerVars.Language.AttentionActionNotSaved);
		if (Proceed)
		{
			// unlock
			SetUnlockMode();
			// run this again
			HideDataBox();
		}
	}
}
function ShowDataBox()
{
var xpos = getCoord("x"); // logo width .. -65
// move xpos if the box is too far on the right

var boxwidth = 689;

xpos = (xpos+boxwidth > window.outerWidth) ? xpos-boxwidth : xpos;
xpos = (xpos < 0) ? 0 : xpos;

// get the document handle
var box = document.getElementById('cwAutoControl[Databox]');
box.style.position = "absolute";
box.style.display = "block";
box.style.left = xpos + 'px';
box.style.zIndex = 100001;
box.style.width = "600px";
box.style.height = "350px";
//box.makeDrag("dragable", "");


CurrentInformation.DataboxDimensions[0] = xpos;

var boxheight = 550;
// get the actual height of the dispalying screen by measuring the html coordinates
//actualheight = screen.height - document.getElementsByTagName("html")[0].offsetHeight;
var actualheight = window.outerHeight;

    // only move the box to the top if there is enough space (also calculate a padding of 5%)
	//TODO: merge - jan 24022009
	if ((actualheight - getCoord("y")) > boxheight || getCoord("y") < (boxheight*1.05))
	{
		box.style.top = getCoord("y")+ (window.pageYOffset?window.pageYOffset:0) + 'px'; //120px image (logo);  -120
		CurrentInformation.DataboxDimensions[1] = getCoord("y")+ (window.pageYOffset?window.pageYOffset:0); //120px image (logo); -120
	}
	else
	{
		box.style.top = getCoord("y")-boxheight+ (window.pageYOffset?window.pageYOffset:0) + 'px'; //120px image (logo);-120 
		CurrentInformation.DataboxDimensions[1] = getCoord("y")-boxheight+ (window.pageYOffset?window.pageYOffset:0); //120px image (logo); -120
	}
	top.window.focus();
	box = null;
	
	if(cwOffice.keybind) {
		cwOffice.keybind.event(HideDataBox,"ctrl+backspace",false);
		//Server Side ... JavaScriptExecute
		//ArrowKeysTableMovement.init("DataboxActions", {"steps":{"down":1,"up":1},"column":1});
	}
}

function RecallDataBox()
{
	// hide current notifcation box
	HideNextBox();

	// show box again
	var box = document.getElementById('cwAutoControl[Databox]');
	box.style.display = "block";

	//change mode again
	CurrentInformation.Mode = 1;

	if(cwOffice.keybind)
		ArrowKeysTableMovement.init("DataboxOutput", {"steps":{"down":1,"up":1},"column":0});
	
	// lock
	SetLockMode();
	
	box = null;
}
function UseInputField()
{
	if (CurrentInformation.Mode == 2 || CurrentInformation.Mode == 5)
	{
		// get the document handle
		HideNextBox();
		RecallDataBox()
		CurrentInformation.SelectedAggregationObject.border = "";

		// now call the save method
		if (CurrentInformation.AggregationCallback == null)
		{
			jS.queue.pA.set({"name": "BerkeWebflowEditorLogic",
							"php":[
								"BerkeWebflowEditorLogicDatabox","AddActionStep4_ExecCommand_SelectReturnFields_Save"
							],
							"getControls":[
								{"Name":"RemeberControl","getAttributes" :{"value":true}},
								{"Name":"TemplateEditor_config","getAttributes" :{"value":true}},
								{"Name":"ID","getAttributes" :{"value":true}},
								{"Name":"Method","attributes" :{"value":"Aggregation"}},
								{"Name":"FillingControl","attributes" :{"value":GetCWId(CurrentInformation.SelectedAggregationObject)}},
								{"Name":"ObjectType","a":{"v":true}},
								{"n":"GlobalCwAppID","a":{"v":true}},
								{"n":"GlobalCwAppVersion","a":{"v":true}}
							] });
		}
		else
		{
			var SelectedControlID = GetCWId(CurrentInformation.SelectedAggregationObject);
            SimpleWebAppRequest({'exec':'GetControlAlias','params':[SelectedControlID,
						document.getElementById('cwAutoControl[GlobalCwAppID]').innerHTML,
						document.getElementById('cwAutoControl[GlobalCwAppVersion]').innerHTML]},
					function(Param){
						var SelectedControlID = (!Param.Alias ? Param.ControlID : Param.Alias);
                        var getControls = [
                                {"Name":"RemeberControl","getAttributes" :{"value":true}},
                                {"Name":"TemplateEditor_config","getAttributes" :{"value":true}},
                                {"Name":"ID","getAttributes" :{"value":true}},
                                {"Name":"Method","attributes" :{"value":"Aggregation"}},
                                {"Name":"FillingControl","attributes" :{"value":Param.ControlID}},
                                {"Name":"FillingMethod","getAttributes" :{"value":true}},
                                {"Name":"FillingControlType","attributes" :{"value":CurrentInformation.SelectedAggregationObject.type}},
                                {"Name":"TargetFieldID","attributes":{"value":Param.ControlID}},
                                {"Name":"SourceActionID","attributes":{"value":CurrentInformation.ActionID}},
								{"Name":"ObjectType","a":{"v":true}},
                                {"n":"GlobalCwAppID","a":{"v":true}},
                                {"n":"GlobalCwAppVersion","a":{"v":true}}
                            ];
                            if(CurrentInformation.AjaxHandlerControls)
                            {
                                for(var celem = 0; celem < CurrentInformation.AjaxHandlerControls.length; celem++)
                                {
                                    getControls.push({"Name":CurrentInformation.AjaxHandlerControls[celem], "getAttributes" : {"value" : true}});
                                }
                            }
						jS.queue.pA.set({"name": "BerkeWebflowEditorLogic",
							"php":[
								"BerkeWebflowEditorLogicDatabox",CurrentInformation.AggregationCallback
							],
							"getControls": getControls});
                            getControls = null;
                            
							CurrentInformation.ActionID = null;
						SelectedControlID = null;
					});
			SelectedControlID = null;
		}
		//set mode back to selection mode
		CurrentInformation.Mode = 1;
	}
	if(CurrentInformation.Mode == 6)
	{
		// get the document handle
		var tmpStyle = SaveStyle;

		HideNextBox();
		RecallDataBox();

		CurrentInformation.SelectedAggregationObject.border = tmpStyle;
		// now call the save method
		if (CurrentInformation.AggregationCallback == null)
		{
			jS.queue.pA.set({"name": "BerkeWebflowEditorLogic",
							"php":[
								"BerkeWebflowEditorLogicDatabox","AddActionStep4_ExecCommand_SelectReturnFields_Save"
							], 
							"getControls":[
								{"Name":"RemeberControl","getAttributes" :{"value":true}},
								{"Name":"TemplateEditor_config","getAttributes" :{"value":true}},
								{"Name":"ID","getAttributes" :{"value":true}},
								{"Name":"Method","attributes" :{"value":"Diagram"}},
								{"Name":"FillingControl","attributes" :{"value":GetCWId(CurrentInformation.SelectedAggregationObject)}},
								{"Name":"ObjectType","a":{"v":true}},
								{"n":"GlobalCwAppID","a":{"v":true}},
								{"n":"GlobalCwAppVersion","a":{"v":true}}
							] });
		}
		else
		{
			jS.queue.pA.set({"name": "BerkeWebflowEditorLogic",
							"php":[
								"BerkeWebflowEditorLogicDatabox",CurrentInformation.AggregationCallback],
								"getControls":[
									{"Name":"RemeberControl","getAttributes" :{"value":true}},
									{"Name":"TemplateEditor_config","getAttributes" :{"value":true}},
									{"Name":"ID","getAttributes" :{"value":true}},
									{"Name":"Method","attributes" :{"value":"Diagram"}},
									{"Name":"FillingControl","attributes" :{"value":GetCWId(CurrentInformation.SelectedAggregationObject)}},
									{"Name":"FillingMethod","getAttributes" :{"value":true}},
									{"Name":"DiagramType","getAttributes" :{"value":true}},
									{"Name":"FillingControlType","attributes" :{"value":CurrentInformation.SelectedAggregationObject.type}},
									{"Name":"ObjectType","a":{"v":true}},
									{"n":"GlobalCwAppID","a":{"v":true}},
									{"n":"GlobalCwAppVersion","a":{"v":true}}
								] });
		}
		//set mode back to selection mode
		CurrentInformation.Mode = 1;
	}
	if (CurrentInformation.Mode == 3 || CurrentInformation.Mode == 31 || CurrentInformation.Mode == 32)
	{
		// get the document handle
		HideNextBox();
		if(CurrentInformation.Mode != 32)
		{
			RecallDataBox()
			CurrentInformation.SelectedElementObject.border = "";

			// now call the save method
			//jS.queue.pA.set({"name": "BerkeWebflowEditorLogic","php":["BerkeWebflowEditorLogicDatabox","AddActionStep4_ExecCommand_SelectReturnFields_Save"], "getControls":[{"Name":"RemeberControl","getAttributes" :{"value":true}},{"Name":"TemplateEditor_config","getAttributes" :{"value":true}},{"Name":"Method","getAttributes" :{"value":"Aggregation"}},{"Name":"FillingControl","getAttributes" :{"value":CurrentInformation.SelectedAggregationObject.id}}] });

			if (CurrentInformation.AggregationCallback == null)
			{
				var SelectedControlID = GetCWId(CurrentInformation.SelectedElementObject);
				SimpleWebAppRequest({'exec':'GetControlAlias','params':[SelectedControlID,
										document.getElementById('cwAutoControl[GlobalCwAppID]').innerHTML,
										document.getElementById('cwAutoControl[GlobalCwAppVersion]').innerHTML]},
									function(Param){  
										var SelectedControlID = (!Param.Alias ? Param.ControlID : Param.Alias);
										if (ClearFunctionName(GetCurrentSection()) == "field" || ClearFunctionName(GetCurrentSection()) == "repeater" || ClearFunctionName(GetCurrentSection()) == "id")
										{
											// if the field: parameter has been set use the set argument completer
											SetArgument(SelectedControlID);
										}
										else
										{
											InsertMessage(SelectedControlID,1);
										}
										SelectedControlID = null;
									});
				SelectedControlID = null;
			}
			else
			{
				if (!CurrentInformation.IsFillingField)
				{
					jS.queue.pA.set({"name": "BerkeWebflowEditorLogic",
									"php":[
										"BerkeWebflowEditorLogicDatabox",CurrentInformation.AggregationCallback
									],
									"getControls":[
										{"Name":"RemeberControl","getAttributes" :{"value":true}},
										{"Name":"TemplateEditor_config","getAttributes" :{"value":true}},
										{"Name":"ID","getAttributes" :{"value":true}},
										{"Name":"Method","attributes" :{"value":"Aggregation"}},
										{"Name":"FillingControl","attributes" :{"value":GetCWId(CurrentInformation.SelectedElementObject)}},
										{"Name":"FillingMethod","getAttributes" :{"value":true}},
										{"Name":"FillingControlType","attributes" :{"value":CurrentInformation.SelectedAggregationObject.type}},
										{"Name":"ObjectType","a":{"v":true}},
										{"n":"GlobalCwAppID","a":{"v":true}},
										{"n":"GlobalCwAppVersion","a":{"v":true}}
									] });
				}
				else
				{
					var SelectedControlID = GetCWId(CurrentInformation.SelectedElementObject);
					SimpleWebAppRequest({'exec':'GetControlAlias','params':[SelectedControlID,
											document.getElementById('cwAutoControl[GlobalCwAppID]').innerHTML,
											document.getElementById('cwAutoControl[GlobalCwAppVersion]').innerHTML]},
										function(Param){
											var SelectedControlID = (!Param.Alias ? Param.ControlID : Param.Alias);
											  if (document.getElementById(CurrentInformation.AggregationCallback).value == null)
											  {
												document.getElementById(CurrentInformation.AggregationCallback).innerHTML = SelectedControlID;
											  }
											  else
											  {
												document.getElementById(CurrentInformation.AggregationCallback).value = SelectedControlID;
											  }
											  SelectedControlID = null;
										});
					SelectedControlID = null;
					/*
					// make sure that values can be filled as well as innerHTML's
					if (document.getElementById(CurrentInformation.AggregationCallback).value == null)
					{
						document.getElementById(CurrentInformation.AggregationCallback).innerHTML = GetCWId(CurrentInformation.SelectedElementObject);
					}
					else
					{
						document.getElementById(CurrentInformation.AggregationCallback).value = GetCWId(CurrentInformation.SelectedElementObject);
					}
					*/
				}
			}
		}
		else
		{
			jS.queue.pA.set({"name": "BerkeWebflowEditorLogic",
							"php":[
								"BerkeWebflowEditorLogicDatabox",CurrentInformation.AggregationCallback
							], 
							"getControls":[
								{"Name":"RemeberControl","getAttributes" :{"value":true}},
								{"Name":"TemplateEditor_config","getAttributes" :{"value":true}},
								{"Name":"ID","getAttributes" :{"value":true}},
								{"Name":"Method","attributes" :{"value":CurrentInformation.FillingMethod != null ? CurrentInformation.FillingMethod : "SingleElement"}},
								{"Name":"FillingControl","attributes" :{"value":GetCWId(CurrentInformation.SelectedElementObject)}},
								{"Name":"FillingMethod","getAttributes" :{"value":true}},
								{"Name":"FillingControlType","attributes" :{"value":CurrentInformation.SelectedElementObject.type}},
								{"Name":"ObjectType","a":{"v":true}},
								{"n":"GlobalCwAppID","a":{"v":true}},
								{"n":"GlobalCwAppVersion","a":{"v":true}}
							] });

			RecallDataBox();
		}
		//set mode back to selection mode
		CurrentInformation.Mode = 1;
	}

	if(CurrentInformation.Mode == 7 || CurrentInformation.Mode == 71)
	{
		//set mode back to selection mode
		HideNextBox();

		if(CurrentInformation.Mode != 71)
		{
			RecallDataBox();
			CurrentInformation.SelectedElementObject.border = "";

			if (CurrentInformation.AggregationCallback == null)
			{
				AutoCompletionInfo.LastActionControl = GetCWId(CurrentInformation.SelectedElementObject);

				if (ClearFunctionName(GetCurrentSection()) == "action")
				{
					//SetArgument("");
				}
				else
				{
					InsertMessage("",3);
				}
				HideAutoCompletionBox();
				CurrentInformation.TextBoxPosition = CurrentInformation.TextBoxPosition+7;

				jS.func = function()
				{
					ShowAutoCompletionBox(AutoCompletionInfo.LastXPos, AutoCompletionInfo.LastYPos, "action");
				}
				jS.queue.pA.set({"php":["BerkeWebflowEditorLogicDatabox","GetControlActions"], "getControls":[{"Name":"TemplateEditor_config","getAttributes" :{"value":true}},{"Name":"ActiveVersionID","getAttributes" :{"value":true}},{"Name":"ControlID","attributes" :{"value":AutoCompletionInfo.LastActionControl}},{"n":"GlobalCwAppID","a":{"v":true}},{"n":"GlobalCwAppVersion","a":{"v":true}}] });
			}
		}
		CurrentInformation.Mode = 1;
	}

	// for the multi mode
	if (CurrentInformation.Mode == 4)
	{
		// get the document handle
		HideNextBox();
		RecallDataBox()


		// now call the save method
		if (CurrentInformation.AggregationCallback != null)
		{
			var ids = "";
			// create a string with the selected id's
			for (i=0; i < CurrentInformation.SelectionMultiElement.length; i++)
			{
				ids += "|"+GetCWId(CurrentInformation.SelectionMultiElement[i]);
			}
			jS.queue.pA.set({"name": "BerkeWebflowEditorLogic",
							 "php":["BerkeWebflowEditorLogicDatabox",CurrentInformation.AggregationCallback],
							 "getControls":[
							 	{"Name":"RemeberControl","getAttributes" :{"value":true}},
							 	{"Name":"TemplateEditor_config","getAttributes" :{"value":true}},
							 	{"Name":"ID","getAttributes" :{"value":true}},
							 	{"Name":"Method","attributes" :{"value":"MultipleElements"}},
							 	{"Name":"FillingControl","attributes" :{"value":ids}},
							 	{"Name":"FillingMethod","getAttributes" :{"value":true}},
							 	{"Name":"SourceActionID","attributes":{"value":CurrentInformation.ActionID}},
							 	{"Name":"ObjectType","a":{"v":true}},
							 	{"n":"GlobalCwAppID","a":{"v":true}},
							 	{"n":"GlobalCwAppVersion","a":{"v":true}}
							 ] });
			CurrentInformation.ActionID = null;
		}
		//set mode back to selection mode
		UnHighlightControls(CurrentInformation.SelectionMultiElement, true);
		CurrentInformation.Mode = 1;
	}
}
/*
function AutoShowNextBox(ControlID)
{
	var Frame = document.getElementById('CwLogicEditor');
	var obj = Frame.contentDocument.getElementById(ControlID);
	
	UpdateMousePosition = false;
	
	document.getElementById('sys_winy').value = absTop(obj)+(obj.clientHeight/2);
	document.getElementById('sys_winx').value = absLeft(obj)+(obj.clientWidth/2);
		
	CurrentID = ControlID;
	Identify(null, obj);
	
	UpdateMousePosition = true;
	
	Frame = null;
	obj = null;
}*/
function ShowNextBox()
{
	var box = null;
	//alert(getCoord("x")+" "+getCoord("y")+window.pageYOffset-120);
	if (CurrentInformation.Mode == 2 || CurrentInformation.Mode == 5 || CurrentInformation.Mode == 6)
	{
		// get the document handle
		box = document.getElementById('NextBoxAggregation');
		box.style.position = "absolute";
		box.style.display = "block";
		box.style.left = getCoord("x") + 'px'; //-65
		box.style.top = getCoord("y")+(window.pageYOffset?window.pageYOffset:0) + 'px'; //-120
		box = null;
		
		if (cwOffice.keybind)
			ArrowKeysTableMovement.init("NextBoxAggregationTable", {"steps":{"down":1,"up":1},"column":0});
	}
	if (CurrentInformation.Mode == 3 || CurrentInformation.Mode == 31 ||  CurrentInformation.Mode == 32)
	{
		// get the document handle
		box = document.getElementById('NextBoxElement');
		box.style.position = "absolute";
		box.style.display = "block";
		box.style.left = getCoord("x") + 'px'; //-65
		box.style.top = getCoord("y")+(window.pageYOffset?window.pageYOffset:0) + 'px'; //-120
		box = null;

		if (cwOffice.keybind)
			ArrowKeysTableMovement.init("NextBoxElementTable", {"steps":{"down":1,"up":1},"column":0});
	}
	if (CurrentInformation.Mode == 7 || CurrentInformation.Mode == 71 )
	{
		// get the document handle
		box = document.getElementById('NextBoxElement');
		box.style.position = "absolute";
		box.style.display = "block";
		box.style.left = getCoord("x") + 'px'; //-65
		box.style.top = getCoord("y")+(window.pageYOffset?window.pageYOffset:0) + 'px'; //-120
		box = null;

		if (cwOffice.keybind)
			ArrowKeysTableMovement.init("NextBoxElementTable", {"steps":{"down":1,"up":1},"column":0});
	}
	if (CurrentInformation.Mode == 4)
	{
		// get the document handle
		box = document.getElementById('NextBoxElementMulti');
		box.style.position = "absolute";
		box.style.display = "block";
		box.style.left = getCoord("x") + 'px'; //-65
		box.style.top = getCoord("y")+(window.pageYOffset?window.pageYOffset:0) + 'px'; //-120

		if (cwOffice.keybind)
			ArrowKeysTableMovement.init("NextBoxElementMultiTable", {"steps":{"down":1,"up":1},"column":0});
	}
	if(box)
	{
		box.style.zIndex = 5;
	}
	box = null;
}

function HideNextBox()
{
	var box = null;
	if (CurrentInformation.Mode == 2 || CurrentInformation.Mode == 5 || CurrentInformation.Mode == 6)
	{
		// get the document handle
		box = document.getElementById('NextBoxAggregation');
		box.style.position = "absolute";
		box.style.display = "none";
		box.style.left = getCoord("x") + 'px';
		box.style.top = getCoord("y") + 'px';

		if (CurrentInformation.SelectedAggregationObject != null)
		{
		   // now unmark the other control
		   if(CurrentInformation.Mode == 6)
		   {

		   		CurrentInformation.SelectedAggregationObject.style.border = "";
		   		CurrentInformation.SelectedAggregationObject.border = SaveStyle;
		   		SaveStyle = "";
		   }
		   else
		   {
		   		CurrentInformation.SelectedAggregationObject.style.border = "";
		   		// IE (5.5, 6, 7) restore border
			   if('\v'=='v') {
			   	var element = CurrentInformation.SelectedAggregationObject;
			   	element.style.borderColor = element.style.borderWidth = element.style.borderStyle = '';
			   }
		   }
		}
		box = null;
	}
	if (CurrentInformation.Mode == 3 || CurrentInformation.Mode == 31 || CurrentInformation.Mode == 32	||
		 CurrentInformation.Mode == 7 ||  CurrentInformation.Mode == 71)
	{
		// get the document handle
		box = document.getElementById('NextBoxElement');
		box.style.position = "absolute";
		box.style.display = "none";
		box.style.left = getCoord("x") + 'px';
		box.style.top = getCoord("y") + 'px';

		if (CurrentInformation.SelectedElementObject != null)
		{
		   // now unmark the other control
		   CurrentInformation.SelectedElementObject.style.border = "";

		   // IE (5.5, 6, 7) restore border
		   if('\v'=='v') {
		   	var element = CurrentInformation.SelectedElementObject;
		   	element.style.borderColor = element.style.borderWidth = element.style.borderStyle = '';
		   }
		}
		box = null;
	}
	if (CurrentInformation.Mode == 4)
	{
		// get the document handle
		box = document.getElementById('NextBoxElementMulti');
		box.style.position = "absolute";
		box.style.display = "none";
		box.style.left = getCoord("x") + 'px';
		box.style.top = getCoord("y") + 'px';
		box = null;
	}
	if(cwOffice.keybind)
		document.getElementById('CwLogicEditor').contentWindow.ArrowKeysInputMovement.setKeybinds();
}
var UpdateMousePosition = true;
function CaptureEvent (Event)
{
	if(!UpdateMousePosition)
		return;
	
	  if (!Event)
	  {
		//TODO: merge - jan 02242009
	    Event = window.event || window.frames['CwLogicEditor'].event;
	  }
	
	  CurrentEvent = Event;
	
	  if (CurrentEvent != null)
	  {
	  	CurrentID = (CurrentEvent.target) ? GetCWId(CurrentEvent.target) : GetCWId(CurrentEvent.srcElement);
	   }
	//    alert(Event.clientX);
	
	 if (document.getElementById('sys_winy') != null)
	    {
		  document.getElementById('sys_winx').value = Event.clientX;
		  document.getElementById('sys_winy').value = Event.clientY;
	    }


}
function $LogicElement(ElementID)
{
	var el = document.getElementById('CwLogicEditor');
	if (el)
	{
		if (ElementID != "")
		{
			return el.contentWindow.document.getElementById(ElementID);
		}
		else
		{
			return el.contentWindow.document;
		}
	}
	el = null;
}
function getCoord(Side)
{
	var frame = window.document.getElementById('CwLogicEditor');
	var addX = 0;
	var addY = 0;

	if(frame)
	{
		addX += frame.offsetLeft;
		addY += frame.offsetTop;

		var Element = frame.offsetParent;
		while(Element)
		{
			addX += Element.offsetLeft;
			addY += Element.offsetTop;
			Element = Element.offsetParent;
		}
//TODO: merge - jan 24022009
		addX -= (window.pageXOffset?window.pageXOffset:0);
		addY -= (window.pageYOffset?window.pageYOffset:0);
		
		Element = null;
	}

    var vRet = null;
    if (document.getElementById('sys_winy') != null)
    {
	    if (Side == "y")
	    {
	        vRet = document.getElementById('sys_winy').value + addY;
	    }
	    else
	    {
	        vRet = document.getElementById('sys_winx').value + addX;
	    }
    }
    
    frame = null;
    return vRet;
}

var LastScrollPosition = 0;
function UpdateDataboxPosition(Event)
{
	var box = document.getElementById('cwAutoControl[Databox]');

	var newYPos = box.style.top;
	newYPos = parseInt(newYPos.substring(0, newYPos.length -2));

	var scrollOffset = window.document.getElementById('CwLogicEditor').contentWindow.pageYOffset - LastScrollPosition;

	newYPos = newYPos - scrollOffset;
	if(newYPos)
		box.style.top = parseInt(newYPos) + 'px';

	LastScrollPosition = window.document.getElementById('CwLogicEditor').contentWindow.pageYOffset;
	
	box = null;
}
window.document.onmousemove = CaptureEvent;
function SetupEventHandler(calltimes)
{
	//document.onmouseup = CaptureEvent;
	//while(window.document.getElementById('CwLogicEditor') === undefined){}
	if(window.document.getElementById('CwLogicEditor') && window.document.getElementById('CwLogicEditor').contentWindow.document.location.href !== 'about:blank')
	{
		window.document.getElementById('CwLogicEditor').contentWindow.document.onmouseup = CaptureEvent;
		window.document.getElementById('CwLogicEditor').contentWindow.document.onscroll = UpdateDataboxPosition;
	}
	else if(!calltimes || calltimes < 10) {
		calltimes = calltimes || 1;
		setTimeout(function() {
			SetupEventHandler(calltimes + 1);
		}, 200);
	}
	else {
		// ERROR DATABOX POSITIONING...
	}
}

function ToggleClass(object, className)
{
	if (object != null)
	{
		// reset the last tab
		if (CurrentInformation.CurrentActiveTab[0] != null)
		{
			CurrentInformation.CurrentActiveTab[0].className = GetClearClassName(CurrentInformation.CurrentActiveTab[1]);
		}
		CurrentInformation.CurrentActiveTab[0] = object;
		object.className = className+'Active';
		CurrentInformation.CurrentActiveTab[1] = className;
	}
}

function GetClearClassName(ClassName)
{
	if (ClassName != null)
	{
		return ClassName.replace('Active', '');
	}
}

function ToggleMouseover(object, IsMouseOver)
{
	//alert(object.className);
	if (object.className != null)
	{
		// hover only if not active
		if (object.className.search('Active') == -1)
		{
			//alert("Org: "+object.className);
			if (IsMouseOver)
			{
				// highlight
				object.className = object.className.replace('Hover', '')+'Hover';
			}
			else
			{
				//unhighlight
				object.className = object.className.replace('Hover', '');
			}
			//alert("Changed: "+object.className);
		}
	}
}

function DeleteTableRow(element)
{
	var ParentElement = element.parentNode;
	while(ParentElement)
	{
		if(ParentElement.tagName == "TR")
		{
			var Parent = ParentElement.parentNode;
			ParentElement.parentNode.removeChild(ParentElement);
			ResetRepeaterIDs(Parent);
			Parent = null;
			break;
		}
		ParentElement = ParentElement.parentNode;
	}
	ParentElement = null;
}
function ResetRepeaterIDs(element)
{
	var Exp = new RegExp('cwAutoRepControl\\[\\_([a-zA-Z0-9=]+)\\_([0-9]+)\\_([a-zA-Z0-9=]+)\\]', 'gim');
	var erg = null;
	var RepID = -1;
	var CurrentRepID = null;
	var ElemInnerHTML = element.innerHTML
	var LastElement = '';
	while(erg = Exp.exec(ElemInnerHTML))
	{
		if(LastElement == erg[0])
			continue;
		LastElement = erg[0];
		
		if(CurrentRepID != erg[2])
		{
			RepID++;
			CurrentRepID = erg[2];
		}
		
		var CurrentElement = document.getElementById(erg[0]);
		if(CurrentElement)
		{
			CurrentElement.id = 'cwAutoRepControl[_'+erg[1]+'_'+RepID+'_'+erg[3]+']';
			CurrentElement.name = 'cwAutoRepControl[_'+erg[1]+'_'+RepID+'_'+erg[3]+']';
		}
		CurrentElement = null;
        ElemInnerHTML = null;
		erg = null;
	}
}
function CreateInfoBox(ElementID, Text, ActionID, ElementBorder, InfoBoxBorder, CallingControl)
	{
		var $Element = document.getElementById(ElementID);
		if ($Element == null)
		{
			$Element = $LogicElement(ElementID);
			// change document space to iframe
			//TODO: merge - jan 24022009
			if ('\v' != 'v') {
				document = $LogicElement("");
			}
		}
		if ($Element != null)
		{
			// first save element style and highlight

			// save only when style info for this control is empty
			if (CurrentInformation.SaveStyleObjects[ElementID] == null)
			{
				CurrentInformation.SaveStyleObjects[ElementID] = $Element.style.border;
			}

			$Element.style.border = ElementBorder;


			// now create info box if text is not null
			if (Text != "")
			{
				// get control location
				//var position = findPos($Element);
				var div = document.getElementById(ElementID+"INFOBOX");
				if (div == null)
				{
					// use parent node as element, so that the block statement worx
					//var body = $Element.previousObject();
					//var body = document.getElementsByTagName("body")[0];
					//TODO: merge - jan 24022009
					div = ('\v'=='v'?window.frames['CwLogicEditor'].document.createElement("div"):window.document.createElement("div"));
					$Element.parentNode.insertBefore(div, $Element);
					CurrentInformation.SaveStyleObjects[ElementID+"_PARENTNODE"] = $Element.parentNode;
				}
				//var divtop = position[1] - $Element.clientHeight - 2 ;
				div.id = ActionID+"_"+ElementID+"INFOBOX";
				//div.style.top = divtop;
				//div.style.left = position[0];
				div.style.border = InfoBoxBorder;
				div.style.background = "white";
				div.style.width = "150px";
				div.onmouseover =  function () { ShowControl(CallingControl, true); };
				div.onmouseout =  function () { UnshowControl(CallingControl, true); };
				div.overflow = scroll;

				//div.onmouseout="UnshowControl(CallingControl,true)";
				//div.style.position = "absolute";
				// top:"+divtop+"px;left:"+position[0]+"px;
				div.innerHTML = Text;

				div = null;
			}
		}
		$Element = null;

	}
	function CreateInfoBoxCheckboxWrapper(ElementID, Text, ActionID,ElementBorder, InfoBoxBorder, Checkbox, CallingControl)
	{
		if (Checkbox.checked == false)
		{
			CreateInfoBox(ElementID, Text,ActionID, ElementBorder, InfoBoxBorder, CallingControl)
		}
	}
	function RemoveInfoBox(ElementID,ActionID)
	{

		var $Element = document.getElementById(ElementID);
		var docspace = document;
		if ($Element == null)
		{
			$Element = $LogicElement(ElementID);
			// change document space to iframe
			docspace = $LogicElement("");
		}
		if ($Element != null)
		{
			// first save element style and highlight

			// set only when style info for this control is not empty
			if (CurrentInformation.SaveStyleObjects[ElementID] != null)
			{
				$Element.style.border = CurrentInformation.SaveStyleObjects[ElementID];

				// IE (5.5, 6, 7) restore border
				if('\v'=='v' && CurrentInformation.SaveStyleObjects[ElementID] == '') {
					$Element.style.borderColor = $Element.style.borderWidth = $Element.style.borderStyle = '';
				}

				CurrentInformation.SaveStyleObjects[ElementID] = null;
			}
			var infodiv = docspace.getElementById(ActionID+"_"+ElementID+"INFOBOX");

			if (infodiv != null)
			{
				CurrentInformation.SaveStyleObjects[ElementID+"_PARENTNODE"].removeChild(infodiv);
			}
			infodiv = null;
		}
		$Element = null;

	}
	function RemoveInfoBoxCheckboxWrapper(ElementID,ActionID, Checkbox)
	{
		if (Checkbox.checked == false)
		{
			RemoveInfoBox(ElementID,ActionID)
		}
	}
	function AddRemoveCheckboxToHighlightedActionList(Checkbox, ActionID, ElementIDs)
	{
		if (Checkbox.checked)
		{
			CurrentInformation.HighlightedActionList.push(ActionID);
			document.getElementById('infoc'+ActionID).onmouseover();
		}
		else
		{
			for (var i = 0; i < CurrentInformation.HighlightedActionList.length; i++)
			{
				if (CurrentInformation.HighlightedActionList[i] == ActionID)
				{
					CurrentInformation.HighlightedActionList[i] = null;
				}
			}
			document.getElementById('infoc'+ActionID).onmouseout();
			/*for each (var ElementID in ElementIDs.split("|"))
			{
				if (ElementID != "")
				{
					RemoveInfoBox(ElementID,ActionID);
				}
			}*/

		}
	}
	function GetHighlightedActionListString()
	{
		var vRet = "";
		//alert(CurrentInformation.HighlightedActionList);

		// TEMP!!!!!

		for (var i = 0; i < CurrentInformation.HighlightedActionList.length; i++)

			//for each (var ActionID in CurrentInformation.HighlightedActionList)
			{


				if (CurrentInformation.HighlightedActionList[i] != null)
				{

					if (/^[0-9]+$/i.test(CurrentInformation.HighlightedActionList[i]))
					{
					vRet += CurrentInformation.HighlightedActionList[i]+"|";
					}

				}
			}

		return vRet;
	}
	function ToggleCheckboxImage(ImageCntrl, Checkbox, ImageChecked, ImageUnchecked)
	{
		var CompletePath = ImageCntrl.src.split("/");
		var file = CompletePath [ CompletePath.length - 1 ];
		var path = ImageCntrl.src.replace(file, "");

		Checkbox = document.getElementById(Checkbox);
		if (Checkbox != null)
		{
			if (Checkbox.checked)
			{
				ImageCntrl.src = path+ImageUnchecked;
				Checkbox.checked = false;
			}
			else
			{
				ImageCntrl.src = path+ImageChecked;
				Checkbox.checked = true;
			}
		}
		Checkbox = null;
	}
// AutoCompletion
	cwOffice['CwAutoCompletion'] = {
		"instances": {},
		"refreshInstances": function() {
			//console.warn('refresh');
			var Exp = new RegExp('cwAutoRepControl\\[\\_([a-zA-Z0-9=]+)\\_([0-9]+)\\_([a-zA-Z0-9=]+)\\]', 'gi');
			var rep = {};
			//console.warn('start');
			for(inst in cwOffice['CwAutoCompletion']['instances']) {
				//console.warn(inst);
				var e = document.getElementById(inst);
				if(e && typeof(e.AutoComplete) == 'undefined') {
					CwAutoCompletionBoxSetWordList(inst, cwOffice['CwAutoCompletion']['instances'][inst]['list'], cwOffice['CwAutoCompletion']['instances'][inst]['searchMode']);
				}
				var erg = Exp.exec(inst);
				if (erg && erg[1] != "") {
					rep[erg[1]] = {"t":erg[2],"n":erg[3],"i":inst};
				}
			}
			for(repName in rep) {
				var t = rep[repName]['t'];
				var control;
				while (control = document.getElementById("cwAutoRepControl[_" + repName + "_" + t + "_" + rep[repName]['n'] + "]")) {
					var name = "cwAutoRepControl[_" + repName + "_" + t + "_" + rep[repName]['n'] + "]";
					t++;
					if(typeof(control.AutoComplete) == 'undefined') {
						var inst = rep[repName]['i'];
						CwAutoCompletionBoxSetWordList(name, cwOffice['CwAutoCompletion']['instances'][inst]['list'], cwOffice['CwAutoCompletion']['instances'][inst]['searchMode'], cwOffice['CwAutoCompletion']['instances'][inst]['freeEditable']);
					}
					control = null;
				}
			}
			rep = null;
		}
	};
	
	// AutoCompletion
	function CwAutoCompletionBox(elementid, list, SearchMode, freeEditable)
	{
		var element = document.getElementById(elementid);
		if(element != null)
		{
			cwOffice['CwAutoCompletion']['instances'][elementid] = {'list': list, 'searchMode': SearchMode, 'freeEditable':freeEditable};
			
			this.WordList = list;
			this.TextElement = element;
			this.SearchMode = SearchMode == null ? 0 : SearchMode;
			
			this.freeEditable = freeEditable; //typeof(freeEditable) != 'undefined' ? freeEditable : false;
			
			element.AutoComplete = this;

			element.onkeyup = CwAutoCompletionBox.prototype.OnTextChange;
			element.onfocus = CwAutoCompletionBox.prototype.OnFocus;
			element.onblur = CwAutoCompletionBox.prototype.OnBlur;
			element.onkeydown = function(e)
			{
				var Key = document.all ? window.event.keyCode : e.which;
				switch(Key)
				{
					case 13:
						// Wird disabled, weil sonst zwei Events gesendet werden (bevor der Wert inst Feld geschrieben wird und dannach)
						this.cwoDisable = {"change":true};
					case 37:
					case 38:
					case 39:
					case 40:
						this.cwoDisable = {"keyup":true,"change":true};
						break;
				}
			};
			
			
			var id = element.id;
			cwOffice.util.event.add(window, 'resize', function() { var x = document.getElementById(id); if(x && x.AutoComplete) x.AutoComplete.CheckLeftPosition(); x = null; }, true);
		}
		element = null;
	}
	CwAutoCompletionBox.prototype.Updated = false;
	CwAutoCompletionBox.prototype.WaitKeys = null;
	CwAutoCompletionBox.prototype.HasFocus = false;
	// IE Bugfix
	// Ueberprueft ob die Maus ueber der Autocomplition List ist
	CwAutoCompletionBox.prototype.IsOverList = false;

	var bodyInnerHTML = '';
	function CwAutoCompletionBoxSetWordList(elementid, list, SearchMode, freeEditable)
	{
		var element = document.getElementById(elementid);
		if(element != null)
		{
			if(element.AutoComplete != null)
			{
				if(list !== -1) element.AutoComplete.WordList = list;
				element.AutoComplete.freeEditable = freeEditable;
			}
			else
			{
				element.AutoComplete = new CwAutoCompletionBox(elementid, list, SearchMode, freeEditable);
			}
			//alert(document.activeElement.id);
			if(document.activeElement && document.activeElement.id == elementid || element.AutoComplete.HasFocus) {
				element.AutoComplete.OnFocus.apply(element, []);
			}
		}
		else {
	    	if(bodyInnerHTML == "") {
				bodyInnerHTML = document.body.innerHTML;
			}
	    	var id = /^\w+\[(.*?)\]$/.exec(elementid)[1];
			var Exp = new RegExp('cwAutoRepControl\\[\\_([a-zA-Z0-9=]+)\\_([0-9]+)\\_(' + id + ')\\]', 'i');
			var erg = Exp.exec(bodyInnerHTML);  
			if (erg) {
				var RepeaterName = erg[1];
				if (RepeaterName != "") {
					var t = 0;
					var control = null;
					while (control = document.getElementById("cwAutoRepControl[_" + RepeaterName + "_" + t + "_" + id + "]")) {
						CwAutoCompletionBoxSetWordList("cwAutoRepControl[_" + RepeaterName + "_" + t + "_" + id + "]", list, SearchMode, freeEditable);
						t++;
						control = null;
					}
				}
			}
			else {                      
				cwOffice['CwAutoCompletion']['instances'][elementid] = {'list': list, 'searchMode': SearchMode, 'freeEditable':freeEditable};
			}
			
		}
		element = null;
	}
	var CwAutoCompletionBoxAggregation = {};
	CwAutoCompletionBox.prototype.OnTextChange = function(e)
	{	
		if(!this.AutoComplete) return;
		var Key = document.all ? window.event.keyCode : e.which;
		this.AutoComplete.CreateList();
		
		var ListDiv = document.getElementById(this.id+'_cw2autocomlition');
		switch(Key)
		{
			case 9:
			case 13: // Enter  
				var Children = ListDiv.childNodes.length;
				for(i = 0; i < Children; i++)
				{
					if(ListDiv.childNodes[i].IsSelected)
					{
						var Value = ListDiv.childNodes[i].firstChild.innerHTML;
						this.AutoComplete.SetValue(Value);
						this.AutoComplete.HideBox();
						Value = null;
						break;
					}
				}
				Children = null;
				break;
			case 37: // Left
				break;
			case 38: // Up
				var Children = ListDiv.childNodes.length;
				var SelectedItem = Children-1;
				for(i = 0; i < Children; i++)
				{
					if(ListDiv.childNodes[i].style.display != 'none' && ListDiv.childNodes[i].IsSelected)
					{
						SelectedItem = i;
						break;
					}
				}
				if(SelectedItem == 0) { ListDiv.scrollTopCw2AC = 0; }
				var i = 0;
				for(i = SelectedItem; i >= 0; i--)
				{
					var Child = ListDiv.childNodes[i];
					if(Child.style.display == 'none') {
						Child = null;
						continue;
					}
					
					if(Child.IsSelected)
					{
						Child.IsSelected = false;
						Child.className = 'CwAutoComp_UnSelectedItem';
					}
					else
					{
						Child.IsSelected = true;
						Child.className = 'CwAutoComp_SelectedItem';
						break;
					}
					Child = null;
				}

				if(i < 0 || !ListDiv.childNodes[i]) return;
				var ItemHeight = ('v'=='\v'?ListDiv.childNodes[i].offsetHeight:ListDiv.childNodes[i].clientHeight);
				//if(ListDiv.scrollTop >= (SelectedItem)*ItemHeight || ((SelectedItem)*ItemHeight - ListDiv.scrollTop < ItemHeight))
				{
					if(!ListDiv.scrollTopCw2AC) ListDiv.scrollTopCw2AC = 0;
					
					var sc = 0;
					ListDiv.scrollTopCw2AC -= ItemHeight;
					if(ListDiv.scrollTopCw2AC > (100-ItemHeight)) {
						sc = ListDiv.scrollTopCw2AC - (100-ItemHeight);
					}
					ListDiv.scrollTop = sc;
					
					//ListDiv.scrollTop = ((SelectedItem)*ItemHeight)-ItemHeight;
				}
				
				Children = null;
				SelectedItem = null;
				break;
			case 39: // Right
				break;
			case 40: // Down
				var Children = ListDiv.childNodes.length;
				var SelectedItem = 0;
				for(i = 0; i < Children; i++)
				{
					if(ListDiv.childNodes[i].style.display != 'none' && ListDiv.childNodes[i].IsSelected)
					{
						SelectedItem = i;
						break;
					}
				}
				if(SelectedItem == 0 || ListDiv.scrollTopCw2AC < 0) ListDiv.scrollTopCw2AC = 0;
				var i = 0;
				for(i = SelectedItem; i < Children; i++)
				{
					var Child = ListDiv.childNodes[i];
					if(!Child) break;
					
					if(Child.style.display == 'none') {
						Child = null;
						continue;
					}

					if(Child.IsSelected)
					{
						Child.IsSelected = false;
						Child.className = 'CwAutoComp_UnSelectedItem';
					}
					else
					{
						Child.IsSelected = true;
						Child.className = 'CwAutoComp_SelectedItem';
						break;
					}
					Child = null;
				}
				
				var ItemHeight = 0;
				if(ListDiv.childNodes.length > 0) ItemHeight = (ListDiv.childNodes[i]?'v'=='\v'?ListDiv.childNodes[i].offsetHeight:ListDiv.childNodes[i].clientHeight:0);
				//if((SelectedItem+1)*ItemHeight > 100-ItemHeight && ListDiv.scrollTop+100-ItemHeight < (SelectedItem+1)*ItemHeight)
				{
					if(!ListDiv.scrollTopCw2AC) ListDiv.scrollTopCw2AC = 0;
					
					var sc = 0;
					ListDiv.scrollTopCw2AC += ItemHeight + ('v'=='\v'?0: 0.25);
					if(ListDiv.scrollTopCw2AC > (100-ItemHeight)) {
						sc = ListDiv.scrollTopCw2AC - (100-ItemHeight);
					}
					ListDiv.scrollTop = sc; //(SelectedItem+1)* ListDiv.scrollTop  -(100-ItemHeight)
				} 
				
				Children = null;
				SelectedItem = null;
				break;
			default:
			/*
			var s = '';
			for(foo in this)s = foo + ' = "' + this[foo] + '"\n';
			alert(s);
			*/ 
				if(this.AutoComplete.WaitKeys === true) {
					this.AutoComplete.WaitKeys = null;
					
					if(typeof(this.AutoComplete.WordList) == 'string') {
						// New method
						this.AutoComplete.ShowItems = 0;
					}
					else {
						this.AutoComplete.ShowItems = 20;
					}
					
					this.AutoComplete.onchange();
				}
				else {
					this.cwoDisable = {"keyup":true};
					var _this = this;
					if(this.AutoComplete.WaitKeys !== null) clearTimeout(this.AutoComplete.WaitKeys);
					this.AutoComplete.WaitKeys = setTimeout(function() {
						_this.AutoComplete.WaitKeys = true;
						cwOffice.util.fireEvent(_this, 'keyup');     
					}, (typeof(this.AutoComplete.WordList) == 'string'?150:150));
				}
		}
		ListDiv = null;
	}
	CwAutoCompletionBox.prototype.OnMouseOver = function()
	{
		this.className = 'CwAutoComp_SelectedItem';
	}
	CwAutoCompletionBox.prototype.OnMouseOut = function()
	{
		this.className = 'CwAutoComp_UnSelectedItem';
	}

	var ie_hide_comlitionbox = null;
	var ie_ctrl_comlitionbox = null;
	CwAutoCompletionBox.prototype.OnMouseDown = function()
	{
		if(cwautocompletiontest !== null) {
			clearTimeout(cwautocompletiontest);
			cwautocompletiontest = null;
		}
		var elem = this.AutoComplete.TextElement;
		//elem.setAttribute('cwoDisable', 'blur');
		elem.cwoDisable = cwOffice.util.extend({}, {'blur': true}, elem.cwoDisable);
		//console.warn(elem);
		
		this.AutoComplete.SetValue(this.firstChild.innerHTML);
		this.AutoComplete.ValueSelected = true;
		setTimeout(function(){
			if(document.activeElement && document.activeElement.tagName.toLowerCase() == 'input' && document.activeElement.id != elem.id) {
				cwOffice.util.fireEvent(elem, 'blur');
				return;
			}
			//elem.setAttribute('cwoDisable', 'focus');
			elem.cwoDisable = cwOffice.util.extend({}, {'focus': true}, elem.cwoDisable);
			
			elem.focus();
			//elem.removeAttribute('cwoDisable');
			if('v'=='\v') {
				var r = elem.createTextRange();
				r.moveStart ("character", elem.value.length);
		        r.collapse ();
		        r.moveEnd ("character", 0);
		        r.select ();
		        r = null;
			}
			elem = null;
		}, 100);
	}
	CwAutoCompletionBox.prototype.SetValue = function(Value)
	{
		var doEvent = function(func) {
		};	
		Value = Value.replace('&amp;', '&'); // Das &-Zeichen wird von Browsern umgewandelt!
		Value = Value.replace('&lt;', '<'); // Das <-Zeichen wird von Browsern umgewandelt!
		Value = Value.replace('&gt;', '>'); // Das >-Zeichen wird von Browsern umgewandelt!
		this.TextElement.value = Value;	   
		// Sollte es wieder Probleme mit dem Onchange-Event geben ggf. diese Zeile loeschen 
		this.TextElement.cwoDisable = {};
		    
		jS.queue.pA.clear();
		if('v' == '\v')
		{
			var obje = this;
			setTimeout(function() {
				try {
					jS.xhr.obj.aborted = true; // Wg. Fehler im IE9 (http://www.enkeladress.com/article.php/internetexplorer9jscripterror) 
					jS.xhr.obj.abort();
				}
				catch (e) {
				}
				var newEvt = document.createEventObject(); 
				obje.TextElement.fireEvent("onchange");
				obje.cwoDisable = false;
				newEvt = null;
				obje = null;
			}, 50);
		}
		else
		{
			var ChangeEvt = document.createEvent("MouseEvents");
			ChangeEvt.initEvent("change", true, true);
			this.TextElement.dispatchEvent(ChangeEvt);	
			ChangeEvt = null;
		}
	}
	CwAutoCompletionBox.prototype.HideBox = function()
	{
		var ListDiv = document.getElementById(this.TextElement.id+'_cw2autocomlition');
		ListDiv.innerHTML = "";
		ListDiv.style.visibility = "hidden";
		ListDiv = null;
		if(document.getElementById("CwAutoCompletionBoxList_iframe")) {
			var iframe = document.getElementById("CwAutoCompletionBoxList_iframe");
			iframe.style.display = 'none';
			iframe = null;
		}
		if(ie_hide_comlitionbox !== null) {
			clearTimeout(ie_hide_comlitionbox);
			ie_hide_comlitionbox = null;
			ie_ctrl_comlitionbox = null;
		}
		if(cwautocompletiontest !== null) {
			clearTimeout(cwautocompletiontest);
			cwautocompletiontest = null;
		}
	}
	var Cw2AutoCompletionLastSelectedID = null;
	CwAutoCompletionBox.prototype.CreateList = function() 
	{
		if(!document.getElementById(this.TextElement.id+'_cw2autocomlition')) {
			var div = document.createElement('div');
			document.getElementsByTagName('body')[0].appendChild(div);
			div.id = this.TextElement.id+'_cw2autocomlition';
			div.style.display = 'none';
			div.style.position = 'absolute';
			div.style.overflowY = 'auto';
			div.style.overflowX = 'hidden';
			div.style.top = '0px';
			div.style.left = '0px';
			div.className = 'CwAutoComp_Box';
			var _this = this;
			// IE Bugfix
			// Speichert ob die Maus ueber der Autocomplition List ist
			div.onmouseover = function() { 
				_this.IsOverList = true;
				// Onblur blockieren
				_this.TextElement.setAttribute('cwoDisable', 'blur');
			};
			div.onmouseout = function() {  
				_this.IsOverList = false;
				// Onblur blockierung aufheben
				_this.TextElement.removeAttribute('cwoDisable');
			};
			div.onscroll = function(e) {
				var e = e || window.event;
				var target = e.target?e.target:e.srcElement;
				var heightLeft = target.scrollHeight - parseInt(target.style.height) - target.scrollTop;
				if(heightLeft < 200) { //_this.ShowItemsLoaded
					if(typeof(_this.WordList) == 'string') {
						// New method
						_this.onchange();
					}
					else {
						_this.ShowItems += 60;
						_this.onchange();
						//_this = null;
					}
				}
			}
			div = null;
		}
	}
	CwAutoCompletionBox.prototype.OnFocus = function()
	{   
		if(Cw2AutoCompletionLastSelectedID !== null) 
			var x = document.getElementById(Cw2AutoCompletionLastSelectedID);
		if(x) 
			x.style.display = 'none';
		Cw2AutoCompletionLastSelectedID = this.id+'_cw2autocomlition';
		
		this.AutoComplete.CreateList();
		if(typeof(this.AutoComplete.WordList) == 'string') {
			// New method
			this.AutoComplete.ShowItems = 0;
		}
		else {
			this.AutoComplete.ShowItems = 20;
		}
		
		if(ie_hide_comlitionbox !== null) {
			clearTimeout(ie_hide_comlitionbox);
			ie_hide_comlitionbox = null;
			ie_ctrl_comlitionbox = null;
		}
		
		this.AutoComplete.HasFocus = true;
		if(!this.AutoComplete.ValueSelected)
		{    
			this.AutoComplete.onchange();
		}
		this.AutoComplete.ValueSelected = false;
	}
	CwAutoCompletionBox.prototype.OnBlur = function(e)
	{
		var e = e || window.event;
		this.AutoComplete.CreateList();
		
		if(this.AutoComplete.freeEditable === false) {
			re = new RegExp('(?:^|\\|)('+this.AutoComplete.TextElement.value.replace(/([\\\.\+\*\?\[\^\]\$\(\)\{\}\=\!<>\|-])/g, "\\$1")+')(;|$|\\|)', 'ig');
			if(!re.test(this.AutoComplete.replaceUserInput(this.AutoComplete.WordList))) {
				this.AutoComplete.TextElement.value = '';
			}
		}
		//return;
		// IE Bugfix
		// Falls die Maus ueber der List ist soll sie nicht geschlossen werden
		if ( ! this.AutoComplete.IsOverList) {
			if('v'=='\v') {  	
				ie_ctrl_comlitionbox = e.srcElement?e.srcElement:e.target;
				ie_hide_comlitionbox = setTimeout(function() {
					if(ie_ctrl_comlitionbox && ie_ctrl_comlitionbox.AutoComplete) {
						ie_ctrl_comlitionbox.AutoComplete.HasFocus = false;
						ie_ctrl_comlitionbox.AutoComplete.HideBox();
						ie_hide_comlitionbox = null;
						ie_ctrl_comlitionbox = null;
					}
					else {
						ie_hide_comlitionbox = null;
						ie_ctrl_comlitionbox = null;
					}
				}, 200);
			}
			else {
				this.AutoComplete.HasFocus = false;
				this.AutoComplete.HideBox();
			}
		}
	}
	function absLeft(el)
	{
		return (el.offsetParent) ? el.offsetLeft+absLeft(el.offsetParent) : el.offsetLeft;
	}

	function absTop(el)
	{
		return (el.offsetParent) ? el.offsetTop+absTop(el.offsetParent) : el.offsetTop;
	}
	var cwautocompletiontest = null;
	CwAutoCompletionBox.prototype.CheckLeftPosition = function() {  
		if(!this.TextElement) return;
		var ListDiv = document.getElementById(this.TextElement.id+'_cw2autocomlition');
		if(ListDiv) {
		ListDiv.style.top = absTop(this.TextElement) + (this.TextElement.offsetHeight?this.TextElement.offsetHeight:0)+'px';
		ListDiv.style.left = absLeft(this.TextElement)+'px';
		var ListX = parseInt(ListDiv.style.left) + parseInt(ListDiv.style.width);
		var WindowWidth = ('v' == '\v' ? document.body.clientWidth : window.innerWidth);
		if(ListX && ListX > WindowWidth)
		{
			ListDiv.style.left = (parseInt(ListDiv.style.left) - (ListX - WindowWidth) - 13)+'px';
		}
		
		ListDiv.style.visibility = "visible";
		
		if(document.getElementById("CwAutoCompletionBoxList_iframe")) {
			var iframe = document.getElementById("CwAutoCompletionBoxList_iframe");
			iframe.style.top = ListDiv.style.top;
			iframe.style.left = ListDiv.style.left;
			
		}
		}
		ListDiv = null;
	}
	CwAutoCompletionBox.prototype.ShowItems = 0;
	CwAutoCompletionBox.prototype.ShowItemsLoaded = true;
	CwAutoCompletionBox.prototype.replaceUserInput = function(string) {
		return string.replace(/@\[\.\-!\(@/, '|').replace(/@\[\.!\-\(@/, ';')
	}
	CwAutoCompletionBox.prototype.onchange = function()
	{
		if(this.WaitKeys !== null) return;

		this.CreateList();
		this.ShowItemsLoaded = false;
		var value = this.TextElement.value;
		value = value.replace('+', '\\\+').replace('?', '\\\?').replace('.', '\\\.');
		var ListDiv = document.getElementById(this.TextElement.id+'_cw2autocomlition');
		//ListDiv.innerHTML = "";
		
		ListDiv.style.top = absTop(this.TextElement) + (this.TextElement.offsetHeight?this.TextElement.offsetHeight:0)+'px';
		ListDiv.style.left = absLeft(this.TextElement)+'px';
		
		//ListDiv.style.width = null;
		var MaxWidth = parseInt(this.TextElement.offsetWidth);

		var MaxHeight = 0;
		var ItemHeight = 0;
		if(this.WordList != null)
		{
			if(typeof(this.WordList) == 'string') {
				var DisplayLength = 0;
				if(this.ShowItems == 0) {
					ListDiv.innerHTML = '';
					ListDiv.style.height = null;
				}	
				MaxWidth = parseInt(this.TextElement.offsetWidth?this.TextElement.offsetWidth:this.TextElement.offsetWidth)-25;

				var search = value.replace(/([\\\.\+\*\?\[\^\]\$\(\)\{\}\=\!<>\|\:-])/g, "\\$1");
				var re = null;
				
				//console.info(this.WordList);
				if(this.SearchMode == 0)
					re = new RegExp('(?:^|\\|)('+search+'[^\\|]*)', 'ig');                    
				else
					re = new RegExp('(?:^|\\|)([^\\|]*?'+search+'[^\\|]*)', 'ig');

				var match;
				var i = -1; 
				while (match = re.exec(this.WordList)) {
					//console.warn(match);
					if(++i != this.ShowItems) continue;
					
					var vM = /^(.*?)(?:$|;)(.*)$/.exec(match[1]);
					var Value1 = cwOffice.util.stripslashes(this.replaceUserInput(vM[1]));
					var Value2 = vM[2]!=''?cwOffice.util.stripslashes(this.replaceUserInput(vM[2])):null;
			
					//console.warn(Value1);
					var nDiv = document.createElement('div');
					ListDiv.appendChild(nDiv);

					nDiv.style.cursor = "pointer";
					nDiv.onmouseover = CwAutoCompletionBox.prototype.OnMouseOver;
					nDiv.onmouseout = CwAutoCompletionBox.prototype.OnMouseOut;
					nDiv.onmousedown = CwAutoCompletionBox.prototype.OnMouseDown;
					nDiv.AutoComplete = this;
					
					var HiddenValue = document.createElement('div');
					nDiv.appendChild(HiddenValue);
					HiddenValue.style.display = "none";
					HiddenValue.innerHTML = Value1;
	
					var VisibleValue = document.createElement('div');
					nDiv.appendChild(VisibleValue);
					VisibleValue.innerHTML = Value1.replace(new RegExp(search, 'i'), '<b>'+value+'</b>') + (Value2 != null ? ' '+Value2.replace(new RegExp(search, 'i'), '<b>'+value+'</b>')+'': '');
					VisibleValue.style.whiteSpace = 'nowrap';

	               if(Value1 == value)
	               {
               		  nDiv.IsSelected = true;
			   		  nDiv.className = 'CwAutoComp_SelectedItem'; 
				   }
				   else
				   {
               		  nDiv.IsSelected = false;
					  nDiv.className = 'CwAutoComp_UnSelectedItem';				   
				   }
			   		var CurrentWidth = 0;
				//	if (navigator.appVersion.indexOf("Win")!=-1) {
						CurrentWidth = parseInt(ListDiv.scrollWidth)-('v'=='\v'?25:25);
				//	}
				//	else {
				//		CurrentWidth = parseInt(VisibleValue.offsetWidth)-('v'=='\v'?20:10);
				//	}
					if(CurrentWidth > MaxWidth) MaxWidth = CurrentWidth+('v'=='\v'?15:15);
					
					nDiv = null;
					HiddenValue = null;
					VisibleValue = null;
					
					this.ShowItems++;
					this.CheckLeftPosition();
					ItemHeight = ListDiv.lastChild.offsetHeight;
					ListDiv.style.width = ('v' == '\v'? MaxWidth +25 : MaxWidth + 25)+'px'; // (this.ShowItems > 5 ? MaxWidth+25 : MaxWidth)+'px';
					//console.warn(ListDiv.style.width);
					var height = (this.ShowItems > 5 ? 100 : ItemHeight * this.ShowItems);
					if(height > 0)
						ListDiv.style.height = height+'px';
					
					if(this.HasFocus === false) {
						ListDiv.style.display = 'none';
						break;
					}
					if(ListDiv.style.display != 'block') ListDiv.style.display = 'block';	
					if(this.ShowItems != 0 && this.ShowItems % 60 == 0) break;
				}
				if(ListDiv.innerHTML == '') ListDiv.style.display = 'none';
			}
			else {
				var ListLength = this.WordList.length;
				var DisplayLength = 0;
				var _this = this;
				if(cwautocompletiontest !== null) {
					clearTimeout(cwautocompletiontest);
					cwautocompletiontest = null;
				}
				var wordlist = {};
				for(var i=0;i<this.WordList.length;i++) wordlist[(typeof(this.WordList[i])=='string'?this.WordList[i]:this.WordList[i][0]).replace(/\s/g, '_')] = {'w': this.WordList[i], 'u':true};
				                                                 
				for(var i=0;i<ListDiv.childNodes.length;i++) {
					if(this.HasFocus === false) {
						ListDiv.style.display = 'none';
						return;
					}
					
					var item = (ListDiv.childNodes[i].childNodes[0].innerText?ListDiv.childNodes[i].childNodes[0].innerText:ListDiv.childNodes[i].childNodes[0].textContent).replace(/\s/g, '_');
					var itemDOM = ListDiv.childNodes[i];
					if(typeof(wordlist[item]) == 'object') {
						var Value1 = null; var Value2 = null;
						if(typeof(wordlist[item]['w']) === 'object') {
							Value1 = wordlist[item]['w'][0];
							Value2 = wordlist[item]['w'][1];
						}
						else {
							Value1 = wordlist[item]['w'];
						}
						var rx = new RegExp('^'+(this.SearchMode != 0 ? '.*' : '')+value+'.*', 'i');
	
						var CurrentWidth = parseInt(itemDOM.offsetWidth)-10;
						if(CurrentWidth > MaxWidth) MaxWidth = CurrentWidth+20;   
						if((rx.test(Value1) || (Value2 != null && rx.test(Value2))) && DisplayLength <= this.ShowItems) {
							var nv = Value1.replace(new RegExp(value, 'i'), '<b>'+value+'</b>') + (Value2 != null ? ' '+Value2.replace(new RegExp(value, 'i'), '<b>'+value+'</b>')+'': '');
							if(nv !== itemDOM.childNodes[1].innerHTML) itemDOM.childNodes[1].innerHTML = nv;
							itemDOM.style.display = '';
							wordlist[item]['u'] = false;
							DisplayLength++;
	
							if(Value1 == value)
			               {
               				  itemDOM.IsSelected = true;
			   				  itemDOM.className = 'CwAutoComp_SelectedItem';
						   }
						   else
						   {
               				  itemDOM.IsSelected = false;
							  itemDOM.className = 'CwAutoComp_UnSelectedItem';				   
						   }
							ItemHeight = itemDOM.offsetHeight;
							
							var CurrentWidth = parseInt(itemDOM.childNodes[1].offsetWidth)-('v'=='\v'?20:10);
							//console.warn(CurrentWidth);
							if(CurrentWidth > MaxWidth) MaxWidth = CurrentWidth+('v'=='\v'?20:10);
							
							ListDiv.style.width = (DisplayLength > 5 ? MaxWidth+25 : MaxWidth)+'px';
    // Weil ItemHeight 0 ist kann man in der WebAppIDE nicht richtig suchen!
							ListDiv.style.height = (DisplayLength > 5 ? 100 : ItemHeight * DisplayLength)+'px';
    
							if(ListDiv.style.display != 'block') ListDiv.style.display = 'block';	
						}
						else {
							itemDOM.style.display = 'none';
							//ListDiv.removeChild(itemDOM);
						}
						
					}
					else {
						itemDOM.style.display = 'none';
						//ListDiv.removeChild(itemDOM);
					}
					itemDOM = null;
				}
				
				if(DisplayLength == 0)  {
					ListDiv.style.display = 'none';	
					if(document.getElementById("CwAutoCompletionBoxList_iframe")) 
						document.getElementById("CwAutoCompletionBoxList_iframe").style.display = 'none';
				}
				  
				var createList = function(_tthis, rLeft, wordlist) {
					
					var ElementHeight = 0;
					var ListLength2 = _tthis.WordList.length;
					var divSum = document.createElement('span');
					if(!rLeft && rLeft !== 0) rLeft = ListLength2;
			
					var fL = ListLength2 - rLeft + 20;
					var fI = ListLength2 - rLeft;
					for(i = fI; i < fL; i++)
					{
						if(_tthis.HasFocus === false) {
							_this = null;
							_tthis = null;
							ListDiv.style.display = 'none';
							return;
						}
						
						if(DisplayLength >= _tthis.ShowItems) break;
						if(--rLeft < 0) break;
						var Word = _tthis.WordList[i];
			
						var Value1 = null;
						var Value2 = null;
			
						if(typeof Word === 'object')
						{
							Value1 = Word[0];
							Value2 = Word[1];
						}
						else
						{
							Value1 = Word;
						}
	
						if(wordlist && Value1 && typeof(wordlist[Value1.replace(/\s/g, '_')]) === 'object' && wordlist[Value1.replace(/\s/g, '_')]['u'] === false) {
							//i--;
							continue;
						}
			
						var RegExVal = '^'+(_tthis.SearchMode != 0 ? '.*' : '')+value;
			
						var rx = new RegExp(RegExVal+'.*', 'i');
			
						if(rx.test(Value1) || (Value2 != null && rx.test(Value2)))
						{
							var nDiv = document.createElement('div');
							ListDiv.appendChild(nDiv); 
							nDiv.style.cursor = "pointer";
							nDiv.onmouseover = CwAutoCompletionBox.prototype.OnMouseOver;
							nDiv.onmouseout = CwAutoCompletionBox.prototype.OnMouseOut;
							nDiv.onmousedown = CwAutoCompletionBox.prototype.OnMouseDown;
							nDiv.AutoComplete = _tthis;
							
							var HiddenValue = document.createElement('div');
							nDiv.appendChild(HiddenValue);
							HiddenValue.style.display = "none";
							HiddenValue.innerHTML = Value1;
			
							var VisibleValue = document.createElement('div');
							nDiv.appendChild(VisibleValue);
							VisibleValue.innerHTML = Value1.replace(new RegExp(value, 'i'), '<b>'+value+'</b>') + (Value2 != null ? ' '+Value2.replace(new RegExp(value, 'i'), '<b>'+value+'</b>')+'': '');
							VisibleValue.style.whiteSpace = 'nowrap';
	
							var CurrentWidth = 0;

							if (navigator.appVersion.indexOf("Win")!=-1) {
								CurrentWidth = parseInt(ListDiv.scrollWidth)-('v'=='\v'?20:10);
							}
							else {
								CurrentWidth = parseInt(VisibleValue.offsetWidth)-('v'=='\v'?20:10);
							}
							if(CurrentWidth > MaxWidth) MaxWidth = CurrentWidth+('v'=='\v'?20:10);
							
							// Set DIVS with innerHTML
							nDiv = null;
							HiddenValue = null;
							VisibleValue = null;
							
							DisplayLength++;
							
	
							_this.CheckLeftPosition();
	
							ItemHeight = ListDiv.lastChild.offsetHeight;
							ListDiv.style.width = (DisplayLength > 5 ? MaxWidth+25 : MaxWidth)+'px';
							ListDiv.style.height = (DisplayLength > 5 ? 100 : ItemHeight * DisplayLength)+'px';
							//console.warn(ListDiv.style.width);
							if(ListDiv.style.display != 'block') ListDiv.style.display = 'block';	
						}
						Word = null;
						Value1 = null;
						Value2 = null;
					}
					divSum = null
					if(rLeft > 0 && DisplayLength < _tthis.ShowItems) {
						cwautocompletiontest = setTimeout(function() {createList( _tthis, rLeft, wordlist);}, 20);
					}
					else {
						if(DisplayLength == 0) ListDiv.style.display = 'none';	
						_tthis.ShowItemsLoaded = true;
						_this.CheckLeftPosition();
						cwautocompletiontest = null;
						_this = null;
						_tthis = null;   
						createList = null;
						wordlist = null;
					}
				}
				cwautocompletiontest = setTimeout(function() {createList(_this, null, wordlist);}, 150);
			}
		}
		if('v'=='\v') {
			ListDiv.attachEvent('onmousedown', function(e) {
				var e = e || window.event;
				var c = e.srcElement?e.srcElement:e.target;
				setTimeout(function() {
					if(/_cw2autocomlition$/.test(c['id']) && ie_hide_comlitionbox !== null) {
						clearTimeout(ie_hide_comlitionbox);
						ie_hide_comlitionbox = null;
						var func = function() {
							if(ie_ctrl_comlitionbox != null && ie_ctrl_comlitionbox.AutoComplete) {
								ie_ctrl_comlitionbox.AutoComplete.HideBox();
								ie_ctrl_comlitionbox = null;
							}
							window.document.detachEvent('onclick', func);
							func = null;
						};
						window.document.attachEvent('onclick', func);
					}
					c = null;
					e = null;
				}, 100);
			});
		}
	 
		this.CheckLeftPosition();

		if(document.getElementById("CwAutoCompletionBoxList_iframe") && ItemHeight) {
			var iframe = document.getElementById("CwAutoCompletionBoxList_iframe");
			iframe.style.width = ((DisplayLength > 5 || 'v'=='\v'? MaxWidth+25 : MaxWidth))+'px';
			iframe.style.height = ((DisplayLength > 5 ? 100 : ItemHeight * DisplayLength))+'px';
			//iframe.style.top = absTop(this.TextElement) + (this.TextElement.offsetHeight?this.TextElement.offsetHeight:0)+'px';
			//iframe.style.left = absLeft(this.TextElement)+'px';
			var ListX = parseInt(ListDiv.style.left) + parseInt(ListDiv.style.width);
			var WindowWidth = ('v' == '\v' ? document.body.clientWidth : window.innerWidth);
			if(ListX > WindowWidth) {
				iframe.style.left = (parseInt(ListDiv.style.left) - (ListX - WindowWidth))+'px';
			}
			iframe.style.zIndex = '0';
			iframe.style.display = '';
			iframe = null;
		}
		
//		value = null;
//		ListDiv = null;
		ListX = WindowWidth = null;
		this.Updated = false;
	}

function RemoveControlIDsFromHTML(ids)
{                                                                
	if(CKEDITOR && CKEDITOR.instances['cwAutoControl[Designer]'])
	{
		var oEditor = CKEDITOR.instances['cwAutoControl[Designer]'] ; 
		var Data = oEditor.getData();
		
		for(var i = 0; i < ids.length; i++)
		{
			var rx = '\\sid=[\'"]'+ids[i]+'[\'"]';
			Data = Data.replace(new RegExp(rx, 'i'), "");
		}
		oEditor.setData(Data);
	}
	else
	{
		var oEditor = FCKeditorAPI.GetInstance('cwAutoControl[Designer]') ;
		var Data = oEditor.GetData();
	
		for(var i = 0; i < ids.length; i++)
		{
			var rx = '\\sid=[\'"]'+ids[i]+'[\'"]';
			Data = Data.replace(new RegExp(rx, 'i'), "");
		}
	
		oEditor.SetData(Data);
	}
	document.getElementById('cwAutoControl[DesignerMessage]').innerHTML = '';
	
	Data = null;
	oEditor = null;
}

function CallConfirmation(ControlID, ActionID, Event)
{
	var i = 0;
	for(i = 0; i < GlobalInformation.RegistredConfirmations.length; i++)
	{
		var GIObj = GlobalInformation.RegistredConfirmations[i];
		if(ActionID == GIObj[3] && (typeof(ControlID)=='string'?ControlID:ControlID[2]) == GIObj[1])
		{
			var check = confirm(GIObj[0]);
			check = (check) ? "TRUE" : "FALSE";

			var obj = null;
			if(typeof(ControlID) == 'string')
			{
				obj = document.getElementById('cwAutoControl['+ControlID+']');
			}
			else
			{
				obj = document.getElementById('cwAutoRepControl[_'+ControlID[0]+'_'+ControlID[1]+'_'+ControlID[2]+']');
			}
			if(obj)
			{
				var Controls = cwOffice.util.clone(obj.getCwOfficeObject().c);

				Controls.push({"n":obj.id,"a":{"v":true}});
				Controls.push({"n":"CONF"+GIObj[3],"a":{"v":check}});
				Controls.push({"n":"CwConfirmNextAction","a":{"v":ActionID}});
				Controls.push({"n":"GlobalCwAppID","a":{"v":true}}); 
				Controls.push({"n":"GlobalCwAppVersion","a":{"v":true}}); 

				jS.queue.pA.set(
					{"name":"JavaScriptWindow",
						"php":["BerkeRenderer","RunAction"],
						"event":Event.substr(2),
						"getControls":Controls});
				
				Controls = null;
			}
			obj = null;
		}
		GIObj = null;
	}
}
// Alias CallConfirmation
function CC(ControlID, ActionID, Event)
{
	CallConfirmation(ControlID, ActionID, Event);
}
function SetUserVariable(Name, Value)
{
	var object = document.getElementById('cwAutoControl[CwUserVariables]');
	if(object)
	{
		var VariableName = 'cwAutoControl[CwUserVar_' + Name + ']';
		var Variable = document.getElementById(VariableName);
		if(!Variable)
		{
			Variable = document.createElement('div');
			Variable.id = VariableName;
			object.appendChild(Variable);
		}
		Variable.innerHTML = Value;
		Variable = null;
	}
	object = null;
}
function GetVariableControl(ControlID, VariableName)
{
	var ControlName = 'cwAutoControl['+ControlID+']';
	var vRet = '';
	var obj = document.getElementById(ControlName);
	if(!obj)
	{
		obj = document.getElementsByName(ControlName)[0];
	}

	if(obj && obj.tagName)
	{
		switch(obj.tagName.toLowerCase())
		{
			case 'select':
				if(obj.selectedIndex != null && obj.length > 0)
				{
					vRet += '<input type="hidden" name="'+VariableName+'" value="'+obj.options[obj.selectedIndex].value+'" />';
				}
			break;
			default:
				if(obj.getRawValue)
				{
					vRet += '<input type="hidden" name="'+VariableName+'" value="'+obj.getRawValue()+'" />';
				}
				else if (obj.value != null)
				{
					if (obj.type.toLowerCase() != "checkbox" || obj.checked)
					{
						vRet += '<input type="hidden" name="'+VariableName+'" value="'+obj.value+'" />';
			        }
				}
				else if(obj.innerHTML != null)
				{
					vRet += '<input type="hidden" name="'+VariableName+'" value="'+obj.innerHTML+'" />';
				}
		}
	}
	obj = null;
	return vRet;
}
function GetCustomWorkflowVariable(ControlID)
{
	var ControlName = 'cwAutoControl['+ControlID+']';
	var vRet = '';
	var obj = document.getElementById(ControlName);
	if(!obj)
	{
		obj = document.getElementsByName(ControlName)[0];
	}

	if(obj && obj.tagName)
	{
		switch(obj.tagName.toLowerCase())
		{
			case 'select':
				if(obj.selectedIndex != null && obj.length > 0)
				{
					vRet = obj.options[obj.selectedIndex].value;
				}
			break;
			default:
				if(obj.getRawValue)
				{
					vRet = obj.getRawValue();
				}
				else if (obj.value != null)
				{
					if (obj.type.toLowerCase() != "checkbox" || obj.checked)
					{
						vRet = obj.value;
			        }
				}
				else if(obj.innerHTML != null)
				{
					vRet = obj.innerHTML;
				}
		}
	}
	obj = null;
	return vRet;
}
function HighlightSidebarItem(obj)
{
	if(typeof(obj) == 'string')
	{
		if(obj != '')
		{
			var elem = document.getElementById('CwSideBar');
			var i=0;
			for(i=0;i<elem.childNodes.length;i++)
			{
				if(elem.childNodes[i].tagName == 'LI')
				{
					var Item = elem.childNodes[i].childNodes[0];
					for(var a = 0;a< Item.childNodes.length; a++)
					{
						if(Item.childNodes[a].innerHTML == obj)
						{
							elem.childNodes[i].className = 'active';
						}
					}
					Item = null;
				}
			}
			elem = null;
		}
	}
	else
	{
		var Objects = obj.parentNode.childNodes[0].childNodes;
		for(var i = 0; i < Objects.length; i++)
		{
			if(Objects[i].innerHTML == 'NOHIGHLIGHTING')
			{
				return;
			}
		}
		
		var node=obj.parentNode.parentNode.childNodes;
		var i=0;
		for(i=0;i<node.length;i++)
		{
			if(node[i].tagName=='LI')
				node[i].className='';
		}
		obj.parentNode.className='active';
		obj = null;
		Objects = null;
		node = null;
	}
}
function MaximizeLogicEditor()
{
	var obj = document.getElementById('CwLogicEditor');
	obj.style.position = 'absolute';
	obj.style.top = '25px';
	obj.style.left = '0px';
	obj.style.width = '100%';
	obj.style.zIndex = '100000';
	
	obj.style.backgroundColor = 'white';
	
	
	var MyResize = function()
	{
		var obj3 = document.getElementById('CwLogicEditor');
		if(obj3.Fullscreen)
		{
			var WindowHeight = (top.document.body.clientHeight ? top.document.body.clientHeight : top.window.innerHeight);
			obj3.style.height = (WindowHeight-25)+'px';
		}
		obj3 = null;
	}
	if(typeof(obj.Fullscreen) == 'undefined')
	{
		cwOffice.util.event.add(window, 'resize', function(){MyResize();}, false);
	}
	obj.Fullscreen = true;
	MyResize();
	
	var obj2 = document.getElementById('CwLogicEditorToolbar');
	obj2.style.display = 'block';
	
	obj = null;
	obj2 = null;
	document.body.style.overflowY = 'hidden';
}
function MinimizeLogicEditor()
{
	var obj = document.getElementById('CwLogicEditor');
	obj.style.position = '';
	obj.style.top = '';
	obj.style.left = '';
	obj.style.width = '';
	obj.style.height = '';
	obj.style.backgroundColor = '';
	obj.Fullscreen = false;
	obj.onload();
	obj = null;
	obj = document.getElementById('CwLogicEditorToolbar');
	obj.style.display = 'none';

	obj = null;
	document.body.style.overflowY = '';
}
function CancelEvent(event)
{
	if('v'=='\v')
	{
	}
	else
	{
		event.stopPropatation();
	}
}

ArrowKeysTableMovement = new function() {
	var keybinds = [
		{key: 'up', modifier: 'ctrl', fn: 'ArrowKeysTableMovement.up()'},
		{key: 'down', modifier: 'ctrl', fn: 'ArrowKeysTableMovement.down()'},
		{key: 'left', modifier: 'ctrl', fn: 'ArrowKeysTableMovement.left()'},
		{key: 'right', modifier: 'ctrl', fn: 'ArrowKeysTableMovement.right()'},
		{key: 'enter', modifier: 'ctrl', fn: 'ArrowKeysTableMovement.enter()'},
		{fn: function() {
			if(selected !== null) {
				var element = selected.getElementsByTagName('select');
				if(element.length > 0) {
					element[0].focus();
				}
				element = null;
			}
		}}
	];
	var _options = {
		"steps": {
			"down": 1,
			"right": 1,
			"left": 1,
			"top": 1
		},
		"column": 0
	}
	var selected = null;
	var table = null;
	var column = null;
	var options = null;
	var interval = 800;
	var timeout = null;
	
	this.setKeybinds = function() {
		cwOffice.keybind.init(keybinds, true);
	};
	this.init = function(id, user_options) {
		var foo = document.getElementById(id);
		//console.warn(foo);
		if(foo) {
			// reset
			options = cwOffice.util.extend({}, _options, user_options);
			selected = null;
			table = null;
			table = foo;
			column = options['column'];
			ArrowKeysTableMovement.setKeybinds();
		}
		foo = null;
	}
	this.up = function() {
		cwOffice.keybind.lostfocus(true);
		if(selected == null) {
			selected = table.getElementsByTagName('td')[column];
		}
		else {
			unheighlight();
			org = selected;
			selected = getNext(selected.parentNode, options['steps']['up'], true);
			if(selected == null) {
				var trs = table.getElementsByTagName('tr');
				selected = trs[trs.length-options['steps']['up']];
				trs = null;
			}
			selected = selected.getElementsByTagName('td')[column];
			org = null;
		}
		heighlight();
		keydown(ArrowKeysTableMovement.up);
	};
	this.down = function() {
		cwOffice.keybind.lostfocus(true);
		if(selected == null) {
			selected = table.getElementsByTagName('td')[column];
		}
		else {
			unheighlight();

			org = selected;
			selected = getNext(selected.parentNode, options['steps']['down']);
			if(selected == null) selected = getNext(org.parentNode.parentNode.firstChild);
			org = null;

			selected = selected.getElementsByTagName('td')[column];
			
		}
		heighlight();
		keydown(ArrowKeysTableMovement.down);
	};
	this.right = function() {
		cwOffice.keybind.lostfocus(true);
		if(selected == null) {
			selected = table.getElementsByTagName('td')[column];
		}
		else {
			unheighlight();
			org = selected;
			selected = getNext(selected, options['steps']['right']);
			if(selected == null) { 
				selected = getNext(org.parentNode.firstChild, options['steps']['right']);
				column = -1;
			}
			org = null;
			column++;
		}
		heighlight();
		keydown(ArrowKeysTableMovement.right);
	};
	this.left = function() {
		cwOffice.keybind.lostfocus(true);
		if(selected == null) {
			selected = table.getElementsByTagName('td')[column];
		}
		else {
			unheighlight();
			org = selected;
			selected = getNext(selected, options['steps']['left'], true);
			if(selected == null) { 
				selected = getNext(org.parentNode.lastChild, options['steps']['left'], true);
				column = org.parentNode.getElementsByTagName('td').length;
			}
			org = null;
			column--;
		}
		heighlight();
		keydown(ArrowKeysTableMovement.left);
	};
	this.enter = function() {
		cwOffice.keybind.lostfocus(true);
		var span = selected.getElementsByTagName('span')[0];
		if(!span) {
			span = selected.getElementsByTagName('a')[0];
			if(span) {
				var match = span.href.match(/^javascript:(.*)$/i);
				if(match) {
					eval('('+match[1]+')');
					return;
				}
			}
			else {
				span = selected.getElementsByTagName('select')[0];
				if(span) {
					if(span.tagName.toLowerCase() == 'select' && span.size > 1) {
						span.size = 1;
						//ArrowKeysInputMovement.setKeybinds();
						//window.focus();
					}
					else if(span.tagName.toLowerCase() == 'select') {
						span.size = span.getElementsByTagName('option').length;
						span.focus();
//						top.cwOffice.keybind.init([
//			        		{key: 'up', modifier: 'ctrl', fn: function() {}},
//			        		{key: 'down', modifier: 'ctrl', fn: function() {}},
//			        		{key: 'left', modifier: 'ctrl', fn: function() {}},
//			        		{key: 'right', modifier: 'ctrl', fn: function() {}},
//			        		{key: 'enter', modifier: 'ctrl', fn: ArrowKeysInputMovement.enter}
//			        	]);
					}	
				}
			}
		}
		if(span.fireEvent) {
			span.fireEvent('onclick');
		}
		else
		{
			var ChangeEvt = document.createEvent("MouseEvents");
			ChangeEvt.initEvent("click", true, true);
			span.dispatchEvent(ChangeEvt);
		}
		span = null;
	};
	
	function getNext(element, steps, reverse) {
		steps = steps || 1;
		while(element = (reverse==true?element.previousSibling:element.nextSibling)) {
			if(element.nodeType == 1 && element.tagName != 'TBODY')
				if(--steps == 0) break;
		}
		return element;
	}
	
	function heighlight() {
		if(selected) selected.style.backgroundColor = "#B8AB97";
	}
	function unheighlight() {
		if(selected) selected.style.backgroundColor = "";
	}
	
	function keydown(func) {
		if(cwOffice.keybind.keydown === true && cwOffice.keybind.keysPressed === 2 && timeout === null) {
			timeout = setTimeout(function() {
				if(cwOffice.keybind.keydown === true && cwOffice.keybind.keysPressed === 2 && timeout !== null) {
					timeout = null;
					func();
				}
				else {
					timeout = null;
					interval = 800;
				}
			}, interval);
			interval = 300;
		} 
		else {
			clearTimeout(timeout);
			timeout = null;
			interval = 800;
		}
	}
}

ArrowKeysInputMovement = new function() {
	this.down = function() {
		cwOffice.keybind.lostfocus(true);
		if(selected == null) {
			selected = {
				"id": getNext(-10, -10, false, false)
			};
		}
		else {
			unhighlight();
			var element = document.getElementById(selected['id']);
			if(!element) { ArrowKeysTableMovement.setKeybinds(); ArrowKeysTableMovement.down(); return; }
			selected['id'] = getNext(absLeft(element),absTop(element),null,false,selected['id']);
			element = null;
		}
		highlight();
	};
	this.up = function() {
		cwOffice.keybind.lostfocus(true);
		if(selected == null) {
			selected = {
				"id": getNext(-10, 99999, false, true)
			};
		}
		else {
			unhighlight();
			var element = document.getElementById(selected['id']);
			if(!element) { ArrowKeysTableMovement.setKeybinds(); ArrowKeysTableMovement.up(); return; }
			selected['id'] = getNext(absLeft(element),absTop(element),null,true,selected['id']);
			element = null;
		}
		highlight();
	};
	this.left = function() {
		cwOffice.keybind.lostfocus(true);
		if(selected == null) {
			selected = {
				"id": getNext(99999, -10, true, false)
			};
		}
		else {
			unhighlight();
			var element = document.getElementById(selected['id']);
			if(!element) { ArrowKeysTableMovement.setKeybinds(); ArrowKeysTableMovement.left(); return; }
			selected['id'] = getNext(absLeft(element),absTop(element),true,null,selected['id']);
			element = null;
		}
		highlight();
	};
	this.right = function() {
		cwOffice.keybind.lostfocus(true);
		if(selected == null) {
			selected = {
				"id": getNext(-10, -10, false, false)
			};
		}
		else {
			unhighlight();
			var element = document.getElementById(selected['id']);
			if(!element) { ArrowKeysTableMovement.setKeybinds(); ArrowKeysTableMovement.right(); return; }
			selected['id'] = getNext(absLeft(element),absTop(element),false,null,selected['id']);
			element = null;
		}
		highlight();
	};
	this.enter = function() {
		cwOffice.keybind.lostfocus(true);
		var element = document.getElementById(selected['id']);
		if(element) {
			if(element.tagName.toLowerCase() == 'select' && element.size > 1) {
				element.size = 1;
				ArrowKeysInputMovement.setKeybinds();
				cwOffice.keybind.lostfocus(true);
			}
			else if(element.tagName.toLowerCase() == 'select') {
				element.size = element.getElementsByTagName('option').length;
				element.focus();
				top.cwOffice.keybind.init([
	        		{key: 'up', modifier: 'ctrl', fn: function() {}},
	        		{key: 'down', modifier: 'ctrl', fn: function() {}},
	        		{key: 'left', modifier: 'ctrl', fn: function() {}},
	        		{key: 'right', modifier: 'ctrl', fn: function() {}},
	        		{key: 'enter', modifier: 'ctrl', fn: ArrowKeysInputMovement.enter}
	        	]);
			}
		}
		element = null;
	};/*
	this.up_select = function() {
		var element = document.getElementById(selected['id']);
		var opts = element.getElementsByTagName('option');
		for(var i=0;i<opts.length;i++) {
			if(opts[i].selected == true) {
				break;
			}
		}
		element.selectedIndex = --i;
		opts = null;
		element = null;
	};
	this.down_select = function() {
		var element = document.getElementById(selected['id']);
		var opts = element.getElementsByTagName('option');
		for(var i=0;i<opts.length;i++) {
			if(opts[i].selected == true) {
				break;
			}
		}
		element.selectedIndex = ++i;
		opts = null;
		element = null;		
	};*/
	this.focus = function() {
		if(selected !== null) {
			var element = document.getElementById(selected['id']);
//			console.warn(element);
			if(element && element.focus) {
				element.focus();
			}
			element = null;
		}
	};
	
	var keybinds = [
		{key: 'up', modifier: 'ctrl', fn: this.up},
		{key: 'down', modifier: 'ctrl', fn: this.down},
		{key: 'left', modifier: 'ctrl', fn: this.left},
		{key: 'right', modifier: 'ctrl', fn: this.right},
		{key: 'enter', modifier: 'ctrl', fn: this.enter},
		{fn: this.focus}
	];
	var targets = ['input', 'select', 'textarea'];
	var selected = null;
	var eObjects = {};
	
	var borderWidth = 2;
	var borderColor = 'darkgreen';
	
	this.init = function(element) { 
		var element = (typeof(element).toLowerCase()=='string'?document.getElementById(element):element);  
		selected = null;
		eObjects = {};
		setTimeout(function() {
			elements = {};
			for(var i=0;i<targets.length;i++) {
				var tg = element.getElementsByTagName(targets[i]);
				for(var x=0;x<tg.length;x++) {
					if(tg[x] && tg[x].type &&tg[x].type.toLowerCase() == 'hidden') continue;
					var pX = absLeft(tg[x]);
					var pY = absTop(tg[x]);
					if(!elements[pX]) elements[pX] = {};
					eObjects[tg[x].id] = {x:pX,y:pY};
				}
			}
			ArrowKeysInputMovement.setKeybinds();
			element = null;
		}, 1);
	}
	this.setKeybinds = function() {
		try {
		top.cwOffice.keybind.init(keybinds, true);
		} catch(e) {
			cwOffice.keybind.init(keybinds, true);
		}
	};
	
	function getNext(posX, posY, left, top, id) {
		var vRet = {'d':99999};
		var divX = 0;var divY = 0;var div = 0;
		for(var e in eObjects) {
			var o = eObjects[e];
			divX = posX - o['x'];
			divY = posY - o['y'] + borderWidth;
			if(left === false && divX >= 0) continue;
			if(left === true && divX <= 0) continue;
			if(top === false && divY >= 0) continue;
			if(top === true && divY <= 0) continue;
			divX = divX>0?divX:divX*-1;
			divY = divY>0?divY:divY*-1;
			div = (divX + divY) / 2;
			if(div < vRet['d'] && e !== id) { //  && z != posX
				vRet['d'] = div;
				vRet['e'] = e;
			}
		}
		return (vRet['e']!=undefined?vRet['e']:id);
	}

	function highlight() {
		var element = document.getElementById(selected['id']);
		if(element) {
			selected['border'] = element.style.border;
			element.style.border = borderWidth+'px solid '+borderColor;
			//if(element.focus) element.focus();
		}
		element = null;
	}
	function unhighlight() {
		var element = document.getElementById(selected['id']);
		if(element) {
			element.style.border = selected['border'];
		}
		element = null;
	}
}
function OpenURL(url, NoQueryString)
{
	if(!NoQueryString)
	{
		var AppID = document.getElementById('cwAutoControl[GlobalCwAppID]');
		var AppVersion = document.getElementById('cwAutoControl[GlobalCwAppVersion]');
		if(AppID && AppID.innerHTML)
		{
			url += '?CwAppID='+AppID.innerHTML+'&CwAppVersion='+AppVersion.innerHTML;
		}
	}
	window.location = url;	
}

function CreateAppMenuStructure(appID, struct, parent, parentID, clear) {
	var parent = (typeof(parent)=='string'?document.getElementById(parent):parent);
	if(!parent) return;
	if(clear === true) {
		parent.innerHTML = '';
		AppMenuStructureAddButton(parent, appID, parentID, false, ServerVars.Language.CreateNewMenuItem);
	}
	
	var struct = struct || [];
	
	for(var i=0;i<struct.length;i++) {
		var item = document.createElement('div');
		parent.appendChild(item);
		item.className = 'MenuStructureItem';
		item.onmouseover = function() { this.style.backgroundColor = 'Gainsboro'; }
		item.onmouseout = function() { this.style.backgroundColor = ''; }

		AppMenuStructureAddButton(item, appID, struct[i]['MenuID'], true);
		
		var name = document.createElement('span');
		item.appendChild(name);
		name.innerHTML = struct[i]['Label'];
		if(struct[i]['TemplateID'] == null) name.className = 'MenuStructureItemNoTemplate'
		
		var ren = document.createElement('a');
		item.appendChild(ren);
		ren.className = 'MenuStructureItemAction MenuStructureItemEdit';
		ren.innerHTML = '&nbsp;';//[ RENAME ] ';
		cwOffice.util.event.add(ren, 'click',  (function(app, menuID, row) {
				return function() {
					var oA = document.getElementById('cwAutoControl[RenameMenuStructureItem]');
					if(oA) {
						oA.parentNode.firstChild.style.display = '';
						oA.parentNode.removeChild(oA);
					}
					oA = null;

					var top = absTop(row.firstChild)+18;//+this.offsetWidth;
					var left = absLeft(row.firstChild)+18;//+this.offsetHeight;
					
					var span = document.createElement('span');
					this.parentNode.appendChild(span);
					span.id = span.name = 'cwAutoControl[RenameMenuStructureItem]';
					span.style.height = '16px';
					span.style.position = 'absolute';
					span.style.top = top + 'px';
					span.style.left = left + 'px';
					span.style.border = '1px solid #000';
					span.style.backgroundColor = '#FFF';
					span.style.height = '40px';
					span.style.minWidth = '200px';
					span.style.padding = '20px 2px 0 2px';
					//span.innerHTML = '<input type="text" value="'+row.childNodes[1].innerHTML+'" name="" id=""> <div>Save</div>';
					//span.style.lineHeight = '40px';
					//this.style.display = 'none';
					var cancel = document.createElement('div');
					this.parentNode.appendChild(cancel);
					cancel.style.position = 'absolute';
					cancel.style.top = top+2+'px';
					cancel.style.left = left+4+'px';
					cancel.style.cursor = 'pointer';
					cancel.style.color = 'gray';
					cancel.innerHTML = '[ x ]';
					cancel.onclick = function() {
						this.parentNode.childNodes[this.parentNode.childNodes.length-2].style.display = 'none';
						this.style.display = 'none';
					}
					//this.style.display = 'none';
		
					jS.queue.pA.set({
							"name":"AddTemplateMenuItem",
							"php":["ManageApps","RenameAppMenuItem"],
							"event":"click",
							"getControls":[{"n":"MenuID","a":{"v":menuID}}, {"n":"AppID","a":{"v":app}}]});
				}
			})(appID, struct[i]['MenuID'], item), false);
		
		if(!struct[i]['Items'] || !struct[i]['Items'].length || struct[i]['Items'].length == 0) {
			var del = document.createElement('a');
			item.appendChild(del);
			del.className = 'MenuStructureItemAction MenuStructureItemDelete';
			del.innerHTML = '&nbsp;';//[ REMOVE ] ';
			cwOffice.util.event.add(del, 'click', (function(app, menuID) {
					return function() {
						jS.queue.pA.set({
								"name":"RemoveTemplateMenuItem",
								"php":["ManageApps","RemoveAppMenuItem"],
								"event":'click',
								"getControls":[{"n":"MenuID","a":{"v":menuID}}, {"n":"AppID","a":{"v":app}}]});
					}
				})(appID, struct[i]['MenuID']), false);
		}
		
		var div = document.createElement('div');
		parent.appendChild(div);
		div.className = 'MenuStructureItem';
		
		//if(struct['Items'] != null) {
		CreateAppMenuStructure(appID, struct[i]['Items'], div, struct[i]['MenuID']);
		//}
	}
}

function AppMenuStructureAddButton(parent, appID, parentID, floatLeft, title) {
	var title = title || '';
	var addContainer = document.createElement('div');
	parent.appendChild(addContainer);
	if(floatLeft == true) addContainer.className = 'MenuStructureItemNew';

	var add = document.createElement('div');
	addContainer.appendChild(add);
	add.className = 'MenuStructureItemADD';
	add.innerHTML = '&nbsp;'+title;//[ + ] ADD ';
	cwOffice.util.event.add(add, 'click', function() {
		var oA = document.getElementById('cwAutoControl[AddMenuStructureItem]');
		if(oA) {
			oA.parentNode.firstChild.style.display = '';
			oA.parentNode.removeChild(oA);
		}
		oA = null;
		
		var top = absTop(this)+18;//+this.offsetWidth;
		var left = absLeft(this)+18;//+this.offsetHeight;   
		var span = document.createElement('div');
		this.parentNode.appendChild(span);
		span.id = span.name = 'cwAutoControl[AddMenuStructureItem]';
		span.style.height = '16px';
		span.style.position = 'absolute';
		span.style.top = top + 'px';
		span.style.left = left + 'px';
		span.style.border = '1px solid #000';
		span.style.backgroundColor = '#FFF';
		span.style.height = '40px';
		span.style.minWidth = '200px';
		span.style.padding = '20px 2px 0 2px';
		//span.style.lineHeight = '40px';
		//this.style.display = 'none';
		var cancel = document.createElement('div');
		this.parentNode.appendChild(cancel);
		cancel.style.position = 'absolute';
		cancel.style.top = top+2+'px';
		cancel.style.left = left+4+'px';
		cancel.style.cursor = 'pointer';
		cancel.style.color = 'gray';
		cancel.innerHTML = '[ x ]';
		cancel.onclick = function() { 
			this.parentNode.childNodes[1].style.display = 'none';
			this.style.display = 'none';
		}

		jS.queue.pA.set({
				"name":"AddTemplateMenuItem",
				"php":["ManageApps","AddAppMenuItem"],
				"event":"click",
				"getControls":[{"n":"ParentID","a":{"v":parentID}}, {"n":"AppID","a":{"v":appID}}]});
	}, false);
}
function StartDownload(DownloadID)
{
	
	var obj = document.getElementById("DownloadProgress"); 
	if(!obj)
	{
		obj = document.createElement('span');
		document.body.appendChild(obj);
		obj.style.display = 'block';  
		obj.style.position = 'absolute';
		obj.style.top = '0px';
		obj.style.left = '0px';
		obj.style.width = '100%';
		obj.style.height = '100%';
		
		obj.innerHTML = '<div style="text-align:center; width:100%; top:40%; left:0px; z-index:1001; position:fixed;margin:auto;padding-top:-50px;"> \
<div style="width:300px;height:100px;background-color:white;border: solid 1px black;text-align:center;vertical-align:middle;display:inline-block;margin:auto;"> \
<b>'+ServerVars.Language.StartExport+'</b><br><img src="'+ServerVars.Config.WebPath+'/templates/modules/BerkeWebflowStyle/loading/bar.gif" >\
</div> \
</div> \
<div style="background-color:black;width:100%;height:100%;opacity:0.5;filter:alpha(opacity=50);">&nbsp;</div>';		
			
		obj.id = "DownloadProgress";
	}
	else
	{
		obj.style.display = 'block'; 	
	}
		
	window.setTimeout(function() {
		jS.queue.pA.set({ 
					"php":["ManageApps", "CheckExportProgress"],
					"event": "click",
					"getControls":[{"n":"DownloadID", "a":{"v":DownloadID}}]
		});
	}, 1000);

	//obj = null;
}
function FinishInstallWizard(AppID, AppVersion)
{
	jS.queue.pA.set({
			"p":["ManageApps","LoadApp"],
			"e":"click",
			"c":[
					{"n":"AppID","a":{"v":AppID}},
					{"n":"Version","a":{"v":AppVersion}}
				]
			});
}
function HighlightLEControl(event, control)
{
	if('v' == '\v')
	{
		event.cancelBubble = true;	
	}
	else
	{
		event.stopPropagation();
	}
	control.orgborder = control.style.border;
	control.style.border='2px green solid';
}
function UnhighlightLEControl(event, control)
{
	if('v' == '\v')
	{
		event.cancelBubble = true;	
	}
	else
	{
		event.stopPropagation();
	}
	control.style.border = control.orgborder;
}
function ShowAppOptions(AppContainer)
{
	var elems = AppContainer.childNodes;
	for(var i = 0; i < elems.length; i++)
	{
		var elem = elems[i];
		if(elem && elem.id=='toolbox')
		{
			elem.style.display='block';
		}
		elem = null;
	}
	elems = null;
}
function ShowAppOptionsSubMenue(img)
{
	var elems = img.parentNode.childNodes;
	for(var i = 0; i < elems.length; i++)
	{
		var elem = elems[i]; 
		if(elem && elem.id == 'subtoolbox')
		{
			elem.style.display = 'block';
		}
		elem = null;
	}
	elems = null;	
}
function HideAppOptions(AppContainer)
{
 	var elems = AppContainer.childNodes;
	for(var i = 0; i < elems.length; i++)
	{
		var elem = elems[i];
		if(elem && elem.id=='toolbox')
		{
			elem.style.display='none';
		}
		elem = null;
	}
	elems = null;
}
function HideAppOptionsSubMenue(event, elem)
{
	
	elem.style.display = 'none';

	if (event.stopPropagation) { 
		event.stopPropagation(); 
	} else {
		event.cancelBubble = true;
	} 
}
function ShowAppOptionBox()
{
	document.getElementById('AppOptionBox').style.display='block';
}
function EditControlAliasName()
{
	var ControlID = document.getElementById('DataboxControlID');
	var ControlIDEdit = document.getElementById('cwAutoControl[ObjectIDEdit]');
	if(ControlID && ControlIDEdit)
	{
		ControlID.style.display = 'none';
		ControlIDEdit.style.display = '';
		ControlIDEdit.focus();
	}
	ControlID = null;
	ControlIDEdit = null;
}
function EditControlAliasNameFinish()
{
	var ControlID = document.getElementById('DataboxControlID');
	var ControlIDEdit = document.getElementById('cwAutoControl[ObjectIDEdit]');
	if(ControlID && ControlIDEdit)
	{
		ControlID.style.display = '';
		ControlIDEdit.style.display = 'none';

 		ControlID.innerHTML = (ControlIDEdit.value != "" ? ControlIDEdit.value : document.getElementById('cwAutoControl[ObjectID]').innerHTML);
	}
	ControlID = null;
	ControlIDEdit = null;
}

var SimpleRequestObject = null;
if (typeof XMLHttpRequest != 'undefined'){
	SimpleRequestObject = new XMLHttpRequest();
}
if (!SimpleRequestObject){
	try{
		SimpleRequestObject = new ActiveXObject("Msxml2.XMLHTTP");
	}
	catch(e){
		try{
			SimpleRequestObject = new ActiveXObject("Microsoft.XMLHTTP");
		}
		catch(e){
			SimpleRequestObject = null;
		}
	}
}
			
function SimpleWebAppRequest(json, func)
{
	SimpleRequestObject.open('POST', info.SimpleRequest+'?'+new Date().getTime());
	SimpleRequestObject.onreadystatechange = function()
	{
		if (SimpleRequestObject.readyState == 4) {
			if(SimpleRequestObject.status !== 200 && SimpleRequestObject.status !== 0)
			{
				jS.showErrorBox("Server Error!", "Status Code:" + SimpleRequestObject.status);
			}
			
			var Response = null;
			try{
				eval('Response = ' + SimpleRequestObject.responseText);
			}
			catch(e){
			}
			func(Response);
			func = null;
			Response = null;
		} 
	}
	SimpleRequestObject.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	SimpleRequestObject.send('ajaxObject='+encodeURIComponent(json_encode(json)));
}
function CopyAction(ActionIDControl)
{
	var ActionID = document.getElementById(ActionIDControl).innerHTML;
	SelectMultiElementsControl('CopyActionToControl', null, ActionID); 
}
function MoveAction(ActionIDControl)
{
	var ActionID = document.getElementById(ActionIDControl).innerHTML;
	SelectControl('MoveActionToControl', null, ActionID);
}

function ShowMultiElementOptionMenue()
{
	document.getElementById('MultiElementOptions').style.display = 'block';
}
function HideMultiElementOptionMenue()
{
	document.getElementById('MultiElementOptions').style.display = 'none';
}
function MultiFieldOptions()
{
    ShowDataBox();
    jS.func = function() {
		var databox = document.getElementById('cwAutoControl[Databox]');
		var option = {"ignore":{'middle':true,'autocompletion_box':true}};
		window.cwOffice.drag(databox, option);
		window.cwOffice.resize(databox, {
			"trigger":document.getElementById('databox_resize_corner'), 
			"addSize": {"width":0, "height":100},
			"min-width":440});
		databox = null;
	}
	jS.queue.pA.set({"php":["BerkeWebflowEditorLogicDatabox","LoadMultiFieldOptions"],"event":"click","getControls":[
		    {"Name":"TemplateEditor_config","getAttributes":{"value":true}},
		    {"Name":"MultiElements", "getAttributes":{"value":CurrentInformation.CtrlMultiElement.join('|')}},
		    {"Name":"GlobalCwAppID","getAttributes":{"value":true}},
		    {"Name":"GlobalCwAppVersion","getAttributes":{"value":true}}
		    ]});
}
function EditTemplate(TemplateID)
{
	jS.queue.pA.set({
		"php":["ManageTemplates","ShowEditor"],
		"event":"click",
		"getControls":[
			{"Name":"Sender","getAttributes":{"value":""}}, // DummyElement, weil es keinen 'sender' gibt!
		    {"Name":"EditIncludeID_"+TemplateID,"getAttributes":{"value":TemplateID}},
		    {"Name":"GlobalCwAppID","getAttributes":{"value":true}},
		    {"Name":"GlobalCwAppVersion","getAttributes":{"value":true}}
		]});	
}
// ErrorBox
(function() {
	var CW2ErrorBox = window.CW2ErrorBox = new function(){
		this.ErrCount = 0;
		this.Type = new function(){
			this.Critical = 0;
			this.Warning = 1;
		}
		this.AddError = function(type, shortmessage, message){
			var ErrorBox = document.getElementById('CW2ErrorBox');
			if(!ErrorBox)
			{
				ErrorBox = document.createElement('SPAN');
				ErrorBox.id = 'CW2ErrorBox';
				ErrorBox.style.zIndex = 1000000;
				ErrorBox.style.position = 'absolute';
				ErrorBox.style.top = '0px';
				ErrorBox.style.left = '0px';
				ErrorBox.style.width = '100%';
				document.body.appendChild(ErrorBox);
			}
			ErrorBox.style.display = 'block';
			var Error = document.createElement('SPAN');
				Error.id = 'CW2ErrorBox_Error_'+CW2ErrorBox.ErrCount++;
				Error.style.display = 'block';
				Error.style.width = '100%';
				Error.onmouseover = function(){
					this.className = 'CW2ErrorBox_ErrorMouseOver';
				}
				Error.onmouseout = function(){
					this.className = 'CW2ErrorBox_Error';
				}
				ErrorValue  = '<span style="display:block;">';
				switch(type){
					case this.Type.Warning:
						ErrorValue += '<img width="16" height="16" src="'+ServerVars.Config.WebPath+'/templates/modules/BerkeWebflowStyle/images/warning.png" />&nbsp;';
					break;
					default:
					case this.Type.Critical:
						ErrorValue += '<img width="16" height="16" src="'+ServerVars.Config.WebPath+'/templates/modules/BerkeWebflowStyle/images/critical.png" />&nbsp;'
					break;
				}
				ErrorValue += '<span>'+shortmessage+'</span>';
				ErrorValue += '&nbsp;<span style="cursor:pointer;" onclick="CW2ErrorBox.Details(\''+Error.id+'\')" id="'+Error.id+'_DetailBtn">'+(ServerVars.Config.ErrorBox_ShowDetails ? ServerVars.Config.ErrorBox_HideDateilsValue : ServerVars.Config.ErrorBox_ShowDateilsValue)+'</span>';
				ErrorValue += '<span style="cursor:pointer;float:right;" onclick="CW2ErrorBox.RemoveError(\''+Error.id+'\')"><img src="'+ServerVars.Config.WebPath+'/templates/modules/BerkeWebflowStyle/images/close.png" /></span>';
				ErrorValue += '</span>';
				ErrorValue += '<span style="margin:3px;display:'+(ServerVars.Config.ErrorBox_ShowDetails ? 'block' : 'none')+';" id="'+Error.id+'_Details"><textarea style="width:100%;height:250px;">'+message+'</textarea></span>';
				Error.innerHTML = ErrorValue;
			
			ErrorBox.appendChild(Error);
			
			Error = null;
			ErrorBox = null;
		};
		this.RemoveError = function(ErrorID){
			var Error = document.getElementById(ErrorID);
			var ErrorBox = document.getElementById('CW2ErrorBox');
			ErrorBox.removeChild(Error);
			if(ErrorBox.childNodes.length == 0)
			{
				ErrorBox.style.display = 'none';
			}
			Error = null;
			ErrorBox = null;
		}
		this.Details = function(ErrorID){
			var DetailBtn = document.getElementById(ErrorID+'_DetailBtn');
			var Details = document.getElementById(ErrorID+'_Details');
			if(Details.style.display == 'none'){
				Details.style.display = 'block';
				DetailBtn.innerHTML = ServerVars.Config.ErrorBox_HideDateilsValue;
			}
			else{
				Details.style.display = 'none';
				DetailBtn.innerHTML = ServerVars.Config.ErrorBox_ShowDateilsValue;
			}
			DetailBtn = null;
			Details = null;
		}
		this.Error = function(shortmessage, message){
			this.AddError(CW2ErrorBox.Type.Critical, shortmessage, message);
		}
		this.Warning = function(shortmessage, message){
			this.AddError(CW2ErrorBox.Type.Warning, shortmessage, message);
		}
	}
})();

// CW2 Dialog
(function(){
	var CW2Dialog = window.CW2Dialog = new function(){
		this.Show = function(Name, Title, Content, parent){
			var dlg = document.getElementById('CW2Dialog_'+Name);
			if(!dlg)
			{
				dlg = document.createElement('DIV');
				dlg.id = 'CW2Dialog_'+Name;
				document.getElementsByTagName('body')[0].appendChild(dlg);
				dlg.style.position = 'fixed';
				dlg.style.top = '0px';
				dlg.style.left = '0px';
				dlg.style.width = '100%';
				dlg.style.height = '100%'; 
				dlg.style.zIndex = '100002';                                         
			}
			dlg.style.display = '';
			
			var elem = document.createElement('DIV');
			elem.id = dlg.id+'_Win';
			dlg.appendChild(elem);
			
			elem.innerHTML = '<span onclick="CW2Dialog.Close(\''+dlg.id+'\');" style="cursor:pointer;">[X]</span>&nbsp;<span id="'+dlg.id+'_Title">'+Title+'</span><br>';
			
			var content = document.createElement('DIV');
			content.id = dlg.id+'_Content'; 
			content.backgroundColor = 'green';
			content.style.padding = '3px';
			content.style.overflow = 'auto';
			elem.appendChild(content);
			content = null;
			
			var resize = document.createElement('DIV');
			elem.appendChild(resize);
			
			resize.style.backgroundColor = 'black';
			resize.style.background = 'url("'+ServerVars.Config.WebPath+'/templates/modules/BerkeWebflowStyle/img/resize-corner2.png") no-repeat scroll left bottom transparent';
			resize.style.width = '15px';
			resize.style.height = '15px';
			resize.style.right = '0px';
			resize.style.bottom = '0px';
			resize.style.position = 'absolute';
			resize.style.cursor = 'se-resize';
			
			window.cwOffice.drag(elem, {"ignore":{'middle':true,'autocompletion_box':true}});
			window.cwOffice.resize(elem, {"trigger":resize, "addSize": {"width":0, "height":-15}, "min-width":440, "min-height":150, "cookie":false} );
			
			resize = null;					
				
			elem.style.backgroundColor = 'white';
			elem.style.zIndex = 10000;
			elem.style.position = 'absolute';
			elem.style.top = '50px';
			elem.style.left = '50px';                
			elem.style.width = '450px';
			elem.style.height = '300px';
			elem.style.border = 'solid 1px black'; 
			elem.style.display = 'block';
			
			var background = document.createElement('DIV');
			background.innerHTML = '&nbsp;';
			background.style.backgroundColor = 'black';
			background.style.width = '100%';
			background.style.height = '100%';
			background.style.opacity = '0.5';
			background.style.filter = 'alpha(opacity=50);';
			background.style.zIndex = '9999';                                            
			dlg.appendChild(background);
			
			var content = document.getElementById(dlg.id+'_Content');
			content.innerHTML = Content;
			var title = document.getElementById(dlg.id+'_Title'); 
			title.innerHTML = Title;
			content = null;
			title = null;
			elem = null;
			dlg = null;
			background = null;
		}
		this.Close = function(Name){
			var elem = document.getElementById(Name);
			if(elem)
			{
				elem.style.display = 'none';	
			}
			elem.innerHTML = null;	
			elem = null;
		}	
	}
})();
