/*JONAS*/

GlobalInformation = new function() {
    this.RegistredConfirmations = new Array();
}

info = new function() {
    this.File = "index.php";
    this.FilePath = "//index.php";
    this.GET = "";
};

/**
 *	Last-Modifyed: 	01.09.08
 *	Author:			Jan Guth
 **/
(function() {
    var cwOffice = window.cwOffice = {};
    //
	cwOffice.lib = new function() {
		var isLoading = false;
		var options = {
			protocol: window.location.protocol,
			host: window.location.host,
			root: "JavaScript/cwOffice"
		};
		this.setOptions = function(root, host, protocol) {
			var root = root || options.root;
			var host = host || options.host;
			options.protocol = protocol || options.protocol;
			options.host = host.replace(new RegExp("^("+options.protocol+"//)"), "");
			if((new RegExp("^("+options.protocol+"//)")).test(root))
				options.root = root.replace(new RegExp("^(?:"+options.protocol+"//)?[^/]+/?"), "");
			else
				options.root = root;
		};
		this.load = function(lib, dyn) {
			isLoading = true;
			if (!dyn) {
				document.write('<script type="text/javascript" src="'+options.protocol+'//' + options.host + "/" + options.root + "/" + lib +'"></script>');
			}
			else {
				var e = document.createElement("script");
				e.src = options.protocol+"//" + options.host + "/" + options.root + "/" + lib;
				e.type = "text/javascript";
				document.getElementsByTagName("head")[0].appendChild(e);
			}
//			var erg = /.*cwOffice\.([^\.]+)\.js$/.exec(lib);
//			if(erg) {
//				var i = 0;
//				while(isLoading) {
//					i++;
//					if(i > 999) break;
//				}
//			}
		};
		this.loaded = function() {
			isLoading = false;
		}
	}

    /**
     *	Core functions start ... (old jSconup.js)
     **/
    jS = cwOffice.jS = window.jS = new function() {
        this.session = new function() {
            var sessionObject = {};

            var prefs = this.preferences = {
                autoFlush: true,
                toJson: cwOffice.toJSONString
            };

			function init() {
				try {
					eval('sessionObject = ' + top.name);
					if (!sessionObject) {
						sessionObject = {};
					}
				}
				catch (e) {
					sessionObject = {};
				}

//				var f = function() {
//					if (prefs.autoFlush) {
//						cwOffice.jS.session.flush();
//					}
//				};
//
//				if (window["addEventListener"]) {
//					addEventListener("unload", f, false);
//				}
//				else if (window["attachEvent"]) {
//					window.attachEvent("onunload", f);
//				}
//				else {
//					prefs.autoFlush = false;
//				}
			}
            this.flush = function() {
                var jsonStr = prefs.toJson(sessionObject);
                top.name = jsonStr;
            };
            this.clear = function() {
                sessionObject = {};
                cwOffice.jS.session.flush();
            };
            this.set = function(key, value) {
                sessionObject[key] = value;
            };
            this.get = function(key) {
                return sessionObject[key];
            };

			init();
        };

        this.hashListener = new function() {
            var sto = null;
            var frameName = null;
            this.run = function(hash, interval) {
                if (window.location.hash == hash) {
                    sto = setTimeout(function() {
                        cwOffice.jS.hashListener.run(hash, interval);
                    }, interval);
                }
                else {
                    //cwOffice.jS.req(window.location.hash.substr(1));
					cwOffice.jS.hashListener.parse();
                }
            };
            this.set = function(hashValue) {

                // TODO: logic edotr iframe -- IE (Access dinied..)
                var key = (new Date()).getTime();//parseInt(Math.random() * 999999999999999);
                var oldKey = top.location.hash.substr(1);

                var cwoHistory = cwOffice.jS.session.get('cwoHistory') || {};
				for(var cwoKey in cwoHistory) {
					if(oldKey < cwoKey) delete cwoHistory[cwoKey];
				}
                cwoHistory[key] = hashValue;
                cwOffice.jS.session.set('cwoHistory', cwoHistory);
				cwOffice.jS.session.flush();

                top.location.hash = key;

                if ('\v' == 'v' && !document.getElementById(frameName)) {
                    cwOffice.jS.hashListener.init();
                }
            };
            this.start = function(interval) {
                var interval = interval || 1000;

                cwOffice.jS.hashListener.stop();
                cwOffice.jS.hashListener.run(window.location.hash, interval);
            };
            this.stop = function() {
                clearTimeout(sto);
                sto = null;
            };
            /**
             * IE workaround for history object
             * @param {String} pFrame
             */
            this.init = function(pFrame) {
                frameName = pFrame || 'cwoHistoryFrameIE';
                var frame = document.getElementById(frameName);
                if (!frame && '\v' == 'v') {
                    frame = window.document.getElementsByTagName('body')[0].appendChild(document.createElement('iframe'));
                    frame.setAttribute('id', frameName);
                    frame.src = '/JavaScript/cwOffice/cwoHistoryIE.html?' + window.location.hash.substr(1);
                    frame.style.visibility = 'hidden';
                    frame.style.position = 'absolute';
                }
				//alert(frame);
            };
            this.issetHashObject = function() {
                var key = top.location.hash.substr(1);
                if (key) {
					var cwoHistory = cwOffice.jS.session.get('cwoHistory');
                    return (cwoHistory && cwoHistory[key] ? true : false);
                }
                return false;
            };
            this.parse = function() {
                var key = top.location.hash.substr(1);
                if (key) {
					var cwoHistory = cwOffice.jS.session.get('cwoHistory');
                    var jsonStr = cwoHistory[key];
                    if (jsonStr) {
                        cwOffice.jS.req(jsonStr);
						//delete cwoHistory[key];
						cwOffice.jS.session.set('cwoHistory', cwoHistory);
                        return true;
                    }
                }
				else {
					// Reload if there is no hash code
					window.location.reload();
				}
                return false;
            };
        };
        this.showErrorBox = function(message, stack) {
            var body = document.getElementsByTagName("body")[0];

            var div = document.createElement("div");
            div.id = "xhrError";

            div.innerHTML = "<div>" +
            "<h4 id='xhrErrorTitle'>An Error Occured:</h4>" +
            "<textarea>" +
            message +
            "\nStack:\n" +
            stack.replace(/</g, "&lt;") +
            "</textarea>" +
            "<br /><br /></div>" +
            "<div id='xhrErrorBackground'>&nbsp;</div>";
            var a = document.createElement("a");
            a.onclick = function() {
                body.removeChild(div);
            }
            a.innerHTML = "<b><h1>[ CLOSE ERROR WINDOW ]</h1></b>";
            div.childNodes[0].appendChild(a);
            body.appendChild(div);
        };
        this.xhr = new function() {
            this.isExec = false;
            this.ispA = false;
            this.ispB = false;
            this.ispC = false;
            this.obj = new function() {
                if (window.XMLHttpRequest)
                    return new window.XMLHttpRequest();
                else
                    try {
                        return new window.ActiveXObject("MSXML2.XMLHTTP");
                    }
                    catch (ex) {
                        try {
                            return new window.ActiveXObject("Microsoft.XMLHTTP");
                        }
                        catch (ex) {
                            alert("Faild to generate a new XMLHTTPREQUEST");
                        }
                    }
            };
            this.cfg = new function() {
                this.async = true;
                this.method = "POST";
            };
        };
        this.queue = new function() {
            this.pA = new function() {
                var items = [];
                this.set = function(item) {
                    items.push(item);
                    jS.req();
                };
                this.get = function() {
                    return items;
                };
                this.clear = function() {
                    items = [];
                };
            };
            this.pB = new function() {
                var items = [];
                this.set = function(item) {
					//console.info(item);
                    items.push(item);
                    jS.req();
                };
                this.get = function() {
                    return items;
                };
                this.clear = function() {
                    items = [];
                };
            };
            this.pC = new function() {
                var items = [];
                this.set = function(item) {
                    items.push(item);
                    jS.req();
                };
                this.get = function() {
                    return items;
                };
                this.clear = function() {
                    items = [];
                };
            };
            this.check = function() {
                if (jS.queue.pA.get().length > 10) {
                    //location.reload();
                }
                if (jS.queue.pB.get().length > 20) {
                    jS.queue.pB.clear();
                }
                if (jS.queue.pC.get().length > 30) {
                    jS.queue.pC.clear();
                }
				
                if (jS.queue.pA.get().length != 0) {
                    jS.xhr.ispA = true;
                    return jS.queue.pA.get().shift();
                }
                else if (jS.queue.pB.get().length != 0) {
                    jS.xhr.ispB = true;
                    return jS.queue.pB.get().shift();
                }
                else if (jS.queue.pC.get().length != 0) {
                    this.ispC = true;
                    return jS.queue.pC.get().shift();
                }
                else {
                    return false;
                }
            };
        };
        this.RepeaterPrototypes = null;
        this.req = function(base64string) {
        	if(typeof(cwOffice.util) == 'undefined') {
        		setTimeout(function() {cwOffice.jS.req(base64string);}, 100);
        		return;
        	}
            //window.jS.hashListener.stop();
            var base64string = base64string || false;
            if (!base64string) {

                if (jS.xhr.isExec) {
                    if (!jS.xhr.ispA) {
                        if (jS.xhr.ispB || jS.xhr.ispC) {
                            jS.xhr.ispB = false;
                            jS.xhr.ispC = false;
                            try {
                                jS.xhr.obj.abort();
                            }
                            catch (e) {
                            }
                        }
                        else {
                            return false;
                        }
                    }
                    else {
                        return false;
                    }
                }
                jS.xhr.isExec = true;

                var obj = jS.queue.check();
			//	console.warn(obj);
				obj = jS.convertToShortVars(obj);
				if(cwOffice.debug) cwOffice.debug.out('Get next queue obj ...');
			//	console.warn(obj);
                if (!obj) {
                    jS.xhr.isExec = false;
                    //window.jS.hashListener.start();
                    return false;
                }

                var element = $c(cwName(obj));
                if (element && element.cwoDisable && element.cwoDisable.event === obj.e) {
                    jS.xhr.isExec = false;
                    element.cwoDisable = false;
                    //window.jS.hashListener.start();
                    cwOffice.util.loading.hide();
                    return false;
                }

            }
                 var sendObj = null;
            jS.xhr.obj.open(jS.xhr.cfg.method, (info.File!=null?info.File:window.location.pathname) + "?" + (new Date()).getTime() + "&" + (info.GET != "" ? "&" + info.GET : location.search.replace(/^\??(.*)$/, "$1")), jS.xhr.cfg.async);
            jS.xhr.obj.onreadystatechange = function() {
				
			//
                // try {
				//cwOffice.debug.out('onreadystatechange ['+jS.xhr.obj.readyState+']');
                if (jS.xhr.obj.readyState == 4) {
			 	//if(console)console.timeEnd('request send');
				//if(console) console.warn(jS.xhr.obj.responseText);
                	if('v' == '\v') {
                	 	if(jS.xhr.obj.status == 12030) {
						 		try {
									//cwOffice.debug.out('resend request (IE) ['+jS.xhr.obj.status+']');
						 			jS.xhr.obj.send(null);
							   		jS.xhr.obj.send(sendObj);
						 		} catch(e) {}
						 		return;
                	 	}
						 }
                    if (jS.xhr.obj.responseText != "" && jS.xhr.obj.responseText != "0") {
					var foo;
                        if (!obj || obj.n != "Ignore") {
                        	 try {
					//		 	if(console)console.time('eval');
                        	eval("foo = " + jS.xhr.obj.responseText);
					//		 	if(console)console.timeEnd('eval');
                             }
                    catch (e) {
						foo = false;
                       //jS.showErrorBox("Invalid json response!", jS.xhr.obj.responseText);
                    }
                            //var foo = parseJSON(jS.xhr.obj.responseText);
                            if (foo != false) {
                               // jS.showErrorBox("No valid json response!", jS.xhr.obj.responseText);
                          //  }
                           //else {

						//	 	if(console)console.time('parse json');
                            	//obj.$cs = foo.cs;
									//cwOffice.debug.out('parse response');
									
								//console.info('jScc.parse');
                            	jScc.parse(foo);
						//	 	if(console)console.timeEnd('parse json');

//							 	if(console)console.time('render');
//                            	document.getElementById('MjA4fDF8dGFibGV8MTI0ODMzNDE2MC40MTF8').style.display = "";
//							 	if(console)console.timeEnd('render');
//								console.warn(document.getElementById('MjA4fDF8dGFibGV8MTI0ODMzNDE2MC40MTF8').style.display);
                            }



                            if (jS.func != null) {
                                jS.func();
                                jS.func = null;
                            }
                        }
                        else {
                            $c("cwAutoControl[GlobalRequest]").innerHTML = "";
                        }
                    }
					//console.info('hide');
                    cwOffice.util.loading.hide();
                    jS.xhr.isExec = false;
                    jS.xhr.ispA = false;
                    jS.xhr.ispB = false;
                    jS.xhr.ispC = false;
                    jS.req();
                }
                //                }
                //                catch (e) {
                //                }
            };
            jS.xhr.obj.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
			if('v' != '\v')
            jS.xhr.obj.setRequestHeader("Connection", "close");
            //if(jS.xhr.obj.readyState != 1) return false;
            //jS.xhr.obj.overrideMimeType("text/html; charset=ISO-8859-1");

		//	 	if(console)console.time('create json object');
            if (!base64string) {

                var sendObj = "ajaxObject=" + encodeURIComponent(toJson(obj).replace(/\\/g, "\\"));
            }
            else {
                //sendObj = Base64.decode(base64string);
				sendObj = eval('('+base64string+')');
            }
		//	 	if(console)console.timeEnd('create json object');

				if(cwOffice.debug) cwOffice.debug.out('send request...');
            jS.xhr.obj.send(sendObj); //escape(obj.toJson())
		//	 	if(console)console.time('request send');
            /*if (obj && obj.e == 'click') {
                //window.jS.hashListener.set(Base64.encode(sendObj));
				//window.jS.hashListener.set(cwOffice.toJSONString(sendObj));
            }
            window.jS.hashListener.start();*/
        };
        this.func = null;

		var patterns = {
			"name":"n",
			"Name":"n",
			"RepeaterName":"r",
			"RepeaterRepID":"i",
			"setAttributes":"s",
			"getAttributes":"a",
			"attributes":"a",
			"php":"p",
			"event":"e",
			"getControls":"c",
			"value":"v",
			"IsChecked":"c"
		};
		this.convertToShortVars = function(tthis) {
			if(/(string|number|boolean|undefined)/i.test(typeof(tthis)) || !tthis) return tthis;
			var tmp = null;
			//console.info(tthis);
	        if (tthis.length) {
				tmp = [];
				for (var i = 0; i < tthis.length; i++)
					tmp[i] = jS.convertToShortVars(tthis[i]);
			}
			else {
				tmp = {};
				for (var a in tthis) {
					if (patterns[a]) {
						tmp[patterns[a]] = jS.convertToShortVars(tthis[a]);
					}
					else {
						tmp[a] = tthis[a];
					}
				}
			}
		    return tmp;
		}
    };

    jScc = window.jScc = cwOffice.jScc = new function() {
        //        this.pA = [];
        //        this.pB = [];
        //        this.pC = [];

        this.parse = function(json) {
            if (typeof(json) == 'string') {
                json = cwOffice.parseJSON(json);
            }
            //		json.each(function(val, attr){
            //			switch(attr)
            //			{
            //				case "Controls":

			 //	if(console)console.time('parse controls');
            each(json["c"], function(value) {
                control(value);
			 	//if(console)console.time('value.control.merge()');
                value.control.merge();
			 //	if(console)console.timeEnd('value.control.merge()');
			 //	if(console)console.time('value.control.setEvent()');
                value.control.setEvent();
			 //	if(console)console.timeEnd('value.control.setEvent()');
                value.$ = "control";
            });
			// 	if(console)console.timeEnd('parse controls');
            //jScc.pA.merge(json[attr]);
            //					break;
            //				case "Tickers":
//console.info('parse c done');
		//	 	if(console)console.time('parse tickers');
            each(json["t"], function(value) {
                ticker(value);
                value.ticker.start();
                value.$ = "ticker";
            });
		//	 	if(console)console.timeEnd('parse tickers');
            //jScc.pB.merge(json[attr]);
            //					break;

            //				case "Media":
			// 	if(console)console.time('parse media');
            each(json["m"], function(value, key) {
				//console.warn(value);
                media(value);
                value.media.init();
                value.$ = "media";
            });
			// 	if(console)console.timeEnd('parse media');
            //jScc.pC.merge(json[attr]);
            //					break;
            //				default:
            //			}
            //		});
//console.info('parse m done');
        };
    };
    function $typeof(type) {
        switch (typeof(type)) {
            case 'string':
            return String;
            case 'number':
            return Number;
            case 'array':
            return Array;
            case 'object':
            return Object;
            case 'boolean':
            return Boolean;
            default:
            return false;
        }
    }
    function each(tthis, handler) {
        if (typeof(tthis) === "array") {
            for (var i = 0; i < tthis.length; i++) {
                handler(tthis[i], i);
            }
        }
        else if (typeof(tthis) == "object") {
            if (typeof(handler) === "function") {
                for (attr in tthis) {
                    if ($typeof(tthis[attr]) && !$typeof(tthis[attr]).prototype[attr]) {
                        handler(tthis[attr], attr);
                    }
                }
            }
        }
    }

    function clone(tthis) {
        var tmp = tthis.constructor();
        if (tthis.length)
            for (var i = 0; i < tthis.length; i++)
                tmp[i] = tthis[i];
        else
            for (var a in tthis)
                tmp[a] = tthis[a];
        return tmp;
    }
    toJson = window.toJson = cwOffice.toJson = function(tthis) {

		if(cwOffice.debug) cwOffice.debug.out('get controls of obj');
		//console.warn(tthis);
        var vRet;
        var php = tthis.php;
        var obj = tthis;
        var AdditionalCode = '';
		var bodyInnerHTML = "";
		var RepeaterName = "";

		var ignoreControl = [];
			//console.warn(obj.c);
		//if(console)console.time("GlobalInformation.RegistredConfirmations");
        if (obj.c != null && GlobalInformation.RegistredConfirmations != null) {
            var ActualConfirmationCounter = 0;
            for (var i = 0; i < GlobalInformation.RegistredConfirmations.length; i++) {
                if (GlobalInformation.RegistredConfirmations[i][1] == obj.c[0].n &&
                "on" + obj.e == GlobalInformation.RegistredConfirmations[i][2]) {
                    var check = confirm(GlobalInformation.RegistredConfirmations[i][0]);
                    check = (check) ? "TRUE" : "FALSE";
                    if (ActualConfirmationCounter != 0) {
                        // add the prefix when not in first repetition
                        AdditionalCode += ",{";
                    }
                    var RepInfo = "";
                    // add repeater info if needed
                    if (obj.c[0].r != "") {
                        RepInfo = "_" + obj.c[0].i;
                    }
                    AdditionalCode += "\"n\":\"CONF" + GlobalInformation.RegistredConfirmations[i][3] + RepInfo + "\",\"a\" :{\"v\":\"" + check + "\"}}";
                    ActualConfirmationCounter++;
                }
            }
        }
	//	if(console)console.timeEnd("GlobalInformation.RegistredConfirmations");
try {
        vRet = '{"p":' + cwOffice.toJSONString(obj.p) + ',"e":' + (obj.e ? cwOffice.toJSONString(obj.e) : 'null') + ',"c":[{';
} catch(e) { }
        if(jS.RepeaterPrototype)
        {
        	var getPrototypeControls = jS.RepeaterPrototype[obj.n];
        	if(getPrototypeControls)
        	{
        		var getControls = [];
				each(getPrototypeControls.c, function(key, value){
					getControls[getControls.length] = {n:key,r:obj.r,i:obj.i,a:{value:true,IsChecked:true}};
				});
				obj.c = getControls;
        	}
        }
        if (obj.c && typeof(obj.c) != "string" && obj.c.length && obj.c.length > 0) {
            //	var RepeaterElement = new Array();

			//console.info(obj.c);
            //alert(this.getControls.length);
          //  var pushlist = new Array();
            //alert("GetControls :"+this.getControls.length);
			var pushlist = [];
		//if(console)console.time("document.getElementsByName(cwName(obj.getControls[i]))[0] == null");
            for (var i = 0; i < obj.c.length; i++) {
                if (obj.c[i] != null && obj.c[i].n) {
		//if(console)console.time("stuff");
                    if (obj.c[i].n.substr(0, 9) == "_GRABALL_") {
                        obj.c[i].n = obj.c[i].n.substr(9);
                        obj.c[i].r = "";
                        obj.c[i].i = "";
                    }
                    //alert(this.getControls[i].cwName());

                    // this is a workaround if a control from a repeater tries to grab a outter repeater control
					//if(console)console.debug(cwName(obj.getControls[i]));
					//if(console)console.debug(obj.getControls[i])
                    if (document.getElementsByName(cwName(obj.c[i]))[0] == null && obj.c[i].r != "") {
                        obj.c[i].r = "";
                        obj.c[i].i = "";
                    }

                    if (document.getElementsByName(cwName(obj.c[i]))[0] == null && obj.c[i].n != null) {

                        //alert(this.getControls[i].cwName());
                        var CopyObject = clone(obj.c[i]);

                        // First delete all the controls with this name who have repeater information with them
                        // to make sure that no control is added twice

                        for (var c = obj.c.length - 1; c > 0; c--) {
                            if (obj.c[c] != null && obj.c[i] != null) {

                                if (obj.c[c].n == obj.c[i].n && obj.c[c].r != null && obj.c[c].r != "") {
                                    //alert(this.getControls[c].Name+" REP: "+this.getControls[c].RepeaterName);
                                    //alert("Delete: "+this.getControls[c].Name+" REP: "+this.getControls[c].RepeaterName);

                                    obj.c[c] = null;
                                }
                            }
                        }


//console.info( obj.c);
	//	if(console)console.timeEnd("stuff");
						if (obj.c[i] != null && obj.c[i]['a']['v'] == true) {
						
							if(bodyInnerHTML == "") {
		//if(console)console.time("bodyInnerHTML = document.body.innerHTML;");
								bodyInnerHTML = document.body.innerHTML;
		//if(console)console.timeEnd("bodyInnerHTML = document.body.innerHTML;");
							}

	//	if(console)console.time("var erg = Exp.exec(document.body.innerHTML);");
							var Exp = new RegExp('cwAutoRepControl\\[\\_([a-zA-Z0-9=]+)\\_([0-9]+)\\_(' + obj.c[i].n + ')\\]', 'i');
							var erg = Exp.exec(bodyInnerHTML);
	//	if(console)console.timeEnd("var erg = Exp.exec(document.body.innerHTML);");
							//console.warn(erg);
							if (erg) {
								var RepeaterName = erg[1];
								if (RepeaterName != "") {
									var t = 0;
									var control = null;
									//if(console) console.warn("cwAutoRepControl[_" + RepeaterName + "_" + t + "_" + obj.c[i].n + "]");
	//	if(console)console.time("pushlist[pushlist.length] = clone(CopyObject);");
									while (control = document.getElementById("cwAutoRepControl[_" + RepeaterName + "_" + t + "_" + obj.c[i].n + "]")) {
										CopyObject.r = RepeaterName;
										CopyObject.i = t++;
										// only push if not existing

										pushlist[pushlist.length] = clone(CopyObject);; //{"Name":obj.getControls[i].Name,"RepeaterName":RepeaterName,"RepeaterRepID":t++};//clone(CopyObject);
										//pushlist.push(clone(CopyObject));
									}
									ignoreControl[i] = true;
	//	if(console)console.timeEnd("pushlist.push(clone(CopyObject));");
								}
							}
						}

						/*
                        var ControlTypes = new Array('input', 'span', 'select', 'textarea');
var d = 0;
                        for (var d = 0; d < ControlTypes.length; d++) {
                            var tagEle = document.getElementsByTagName(ControlTypes[d]);
                            if (tagEle != null) {
                                for (var g = 0; g < tagEle.length; g++) {
									d++;
                                    if (tagEle[g].id != null) {
                                        if (obj.getControls[i] != null) {

                                            //alert(RepeaterElement[x]);
                                            var match = "cwAutoRepControl\[\_[a-zA-Z0-9=]+\_[0-9]+\_" + obj.getControls[i].Name + "\]";
                                            //alert(RepeaterElement[x].name);

                                            var context = (tagEle[g].name == "" || tagEle[g].name == null) ? tagEle[g].id : tagEle[g].name;

                                            if (!context.search(match) || !context.search(match)) {

                                                //alert("IN: "+RepeaterElement[x].name + " -- ");
                                                var Exp = /cwAutoRepControl\[\_([a-zA-Z0-9=]+)\_([0-9]+)\_([a-zA-Z0-9=]+)\]/i;
                                                Exp.exec(context);

                                                var RepeaterName = RegExp.$1;
                                                var RepeaterRepID = RegExp.$2;
                                                var ControlName = RegExp.$3;
                                                //alert(RepeaterElement[x].id+" "+RepeaterName+" "+RepeaterRepID);
                                                CopyObject.RepeaterName = RepeaterName;
                                                CopyObject.RepeaterRepID = RepeaterRepID;
                                                // only push if not existing
                                                pushlist.push(clone(CopyObject));
                                                //}
                                            }
                                        }
                                    }
                                }
                            }
                        }
						console.warn(d);
						*/
                    }
                }
            }
		//if(console)console.timeEnd("document.getElementsByName(cwName(obj.getControls[i]))[0] == null");
//if(console && console.info) console.info(obj.c);
            obj.c = obj.c.concat(pushlist);

		//if(console)console.time("get control("+obj.getControls.length+") attributes");
		for (var i = 0; i < obj.c.length; i++) {

			//console.warn(obj.c[i]);
                if (/(object|array)/i.test(typeof(obj.c[i])) && obj.c[i] != null && ignoreControl[i] !== true) {
					//if($c(cwName(obj.c[i]), obj.eventHolder) == undefined) continue;

                    vRet += '"n":' + cwOffice.toJSONString(obj.c[i]["n"]) + ',';
                    if (obj.c[i]["r"] && obj.c[i]["r"] != "") {
                        vRet += '"r":' + cwOffice.toJSONString(obj.c[i]["r"]) + ',';
                        vRet += '"i":' + cwOffice.toJSONString(obj.c[i]["i"]) + ',';
                    }

                    vRet += '"a":{';
                    var el = $c(cwName(obj.c[i]), obj.eventHolder);
						var attr = jS.convertToShortVars(obj.c[i]["a"]);
						//console.info(typeof(el.getRawValue));
						var value = null;
						if (el && typeof(el.getRawValue) == 'function') {
							value = el.getRawValue();
						}
						else {
							var AttrName = (el?getAttr("value", el):null);
							value = (el && AttrName ? (typeof(el[AttrName]) != 'undefined' ? el[AttrName] : el.getAttribute(AttrName)) : false);
						}
						//
						// TODO: attr['value'] must be v!!
						if ((el && value) && (attr && attr["v"] === true) || CKEDITOR && CKEDITOR.instances[cwName(obj.c[i])]) {
							//if(console && console.info) console.info(CKEDITOR.instances[cwName(obj.c[i])]);
							if(CKEDITOR && CKEDITOR.instances[cwName(obj.c[i])]) {
								value = CKEDITOR.instances[cwName(obj.c[i])].getData();
							}
							vRet += '"v":' + cwOffice.toJSONString(value) + ',';
						}
						else
							if (attr && attr["v"] && attr["v"] !== true) {
								vRet += '"v":' + cwOffice.toJSONString(attr["v"]) + ','; // .replace(/"/g,"")
							}

						if (el && el[getAttr("IsChecked", el)]) {
							vRet += '"c":' + cwOffice.toJSONString(el[getAttr("IsChecked", el)]) + ',';
						}

					if(obj.vars) {
						for(key in obj.vars) {
							vRet += '"'+key+'":' + cwOffice.toJSONString(obj.vars[key]) + ',';
						}
					}

                    vRet = rtrim(vRet, ',') + '}},{';
                }
            }
		//if(console)console.timeEnd("get control("+obj.getControls.length+") attributes");
        }

        if (AdditionalCode != "") {
            vRet += AdditionalCode;
        }
        vRet = rtrim(vRet, '{', ',') + ']}';


        if (tthis.$cs) {
            vRet = rtrim(vRet, "}") + ',"cs":' + tthis.$cs + '}';
        }
        //alert(vRet);

		if(cwOffice.debug) cwOffice.debug.out('get controls of obj -> finished');
		//	jS.showErrorBox("foo send", vRet);
        return vRet;
    };
    function getAttr(attr, obj) {
        if (/(div|span)/i.test(obj.tagName)) {
            switch (attr.toLowerCase()) {
				case 'v':
                case 'value':
                return 'innerHTML';
                    break;
                default:
                return attr;
            }
        }
        else if (/(input)/i.test(obj.tagName)) {
            switch (attr.toLowerCase()) {
				case 'v':
                case 'value':
                if (obj.type.toLowerCase() != "checkbox") {
                    if (obj.type == 'hidden') {
                        if (typeof(FCKeditorAPI) != "undefined") {
							//console.info(obj);
                            var oEditor = FCKeditorAPI.GetInstance(obj.name);
                            var fcktxt = oEditor.GetHTML(true);
                            obj.FCK = fcktxt;
                        }
                        return "FCK";
                    }
					else if (obj.type.toLowerCase() == "file") {
						return "tmpname";
					}

                    return 'value';
                }
                else {
                    return (obj.checked) ? 'value' : '';
                }

                    break;
				case 'c':
                case 'ischecked':
                return 'checked';
                    break;
                default:
                return attr;
            }
        }
        return attr;
    };
    cwName = window.cwName = function(tthis) {
        return (tthis.r && tthis.r != "") ? "cwAutoRepControl[_" + tthis.r + "_" + tthis.i + "_" + tthis.n + "]" : "cwAutoControl[" + tthis.n + "]";
    };
    control = function(tthis) {
    	try {
        tthis.control = new function() {
            this.setEvent = function() {
                var obj = tthis;
				if(obj.e && obj.p[0] === "JavaScript") {
					setTimeout(function() { 
						setEvent(cwName(obj), obj.e, function(e) { cwOffice.MediaLibrary[obj.p[1]]["Add"](obj); }, true); 
					}, 200 );
				}
				else if(obj.e)
				{
					window.setTimeout(function() {
						var el = $c(cwName(obj));
		                    if(el) {
							   el.getCwOfficeObject = function() {
							   		return obj;
							   }
		                    }
	                        setCw(obj);
                    }, 300);
				}
            };
            this.merge = function() {
                var obj = tthis;
                if (obj.s) {
                    var el = $c(cwName(obj));

                    if (el == null) {
                        obj.r = "";
                        var el = $c(cwName(obj));

                    }

                    if (el == undefined) {
						//if(console) console.warn(obj);
						jS.showErrorBox("Element is undefined", "Name: " + cwName(obj));

						return;
                    	//window.location.href = window.location.pathname;
                   }

				   // gets the cwoffice object (send response php)
                    each(obj.s, function(value, key) {

			// 	if(console)console.time('each(obj.setAttributes ('+key+')');
                        switch (key.toLowerCase()) {
							case 'v':
                            case 'value':
							try {
								if (!el.getFormatType && obj.s['FormatDisplay'] != null) {
									//console.info(value);
									cwOffice.format.init(obj.s['FormatDisplay'], obj.s['FormatIO'], el);
									value = cwOffice.format.io(obj.s['FormatDisplay'], obj.s['FormatIO'], value, el);
								}
								else if(el.getFormatType) {
									//console.info('a');
									//console.info(value);
									value = el.setValue(value);
									//break;
								}
							} catch(e) {console.warn(e);}
                            if (/(div|span)/i.test(el.tagName)) {
                                if (isset(obj.s.AttachValue)) {
                                    if (obj.s.AttachValue == 'top') {
                                        el.innerHTML = value + el.innerHTML;
                                    }
                                    else if (obj.s.AttachValue == 'bottom') {
                                        el.innerHTML = el.innerHTML + value;
                                        if (obj.s.Scroll) {
                                            el.scrollTo(el.pageYOffset, 0);
                                        }
                                    }
                                    else if (obj.s.AttachValue != 'nothing' && value != null) {
                                        el.innerHTML = value;
                                    }
                                }
                                else {
								//	console.time("innerHTML");
                                    el.innerHTML = value;

								//	var newEl = el.cloneNode(false);
								//	newEl.innerHTML = value;
								//	el.parentNode.replaceChild(newEl, el);

								//	console.timeEnd("innerHTML");
                                }
								var re = /<script\sexec\b[\s\S]*?>([\s\S]*?)<\//ig;
								var match;
								while (match = re.exec(value)) {
									eval(match[1]);
								}
                            }
                            else if (/(input|textarea)/i.test(el.tagName)) {

                                if (el.type == 'hidden') {
                                    if (typeof(FCKeditorAPI) != "undefined") {
                                        var oEditor = FCKeditorAPI.GetInstance(el.name);
                                        //console.info(el);
                                        oEditor.SetHTML(value);
                                    }
                                    break;
                                }
								else if (el.type == "file") {
									el.setAttribute('tmpname', value);
								}
                                else if (el.type == 'checkbox') {
                                    if (el.value == value) {
                                        el.checked = true;
                                    }
                                    else {
                                        el.checked = false;
                                    }
                                }
                                else {
                                    if (isset(obj.s.AttachValue)) {
                                        if (obj.s.AttachValue == 'top') {
                                            el.value = value + el.value;
                                        }
                                        else if (obj.s.AttachValue == 'bottom') { 
                                            el.value = el.value + value;
                                            if (obj.s.Scroll) {
                                                el.scrollTo(el.pageYOffset, 0);
                                            } 
                                        }
                                        else if (obj.s.AttachValue != 'nothing' && value != null) {
                                            el.value = value;
                                        }
                                    }
                                    else {
                                        el.value = value;
                                    }
                                    //el.value = value;
                                }
                            }
                            else if (/(select)/i.test(el.tagName)) {
                                if (value != "") {

                                    // syntax value1~readablevalue1|value2~readablevalue2
                                    if (value.indexOf("|") != -1 || value.indexOf("~") != -1) {

                                        var options = value.split("|");
                                        if (isset(obj.s.AttachValue)) {
                                            if (obj.s.AttachValue == 'top') {

                                            }
                                            else if (obj.s.AttachValue == 'bottom') {

                                            }
                                            else if (obj.s.AttachValue != 'nothing' && value != null) {
                                                el.options.length = 0;
                                            }
                                        }
                                        else {
                                            el.options.length = 0;
                                        }

                                        if (options.length > 0) {

                                            for (var f = 0; f < options.length; f++) {
                                                // now get the values
                                                var values = options[f].split("~");

                                                if (values.length > 0) {
                                                    // clear the list first

                                                    //optionsCache.push(new Option(values[1], values[0], false, (values[2] == "true")));
                                                    el.options[el.options.length] = new Option(values[1], values[0], false, (values[2] == "true"));
                                                }
                                            }
                                        }
                                    }
                                    else {

                                        // try to set value
                                        for (var f = 0; f < el.options.length; f++) {
                                            if (el.options[f].value == value) {
                                                el.options[f].selected = true;
                                            }
                                        }
                                    }
                                }
                                else {
                                    el.options.length = 0;
                                }

                            }

                                break;
                            default:
                            el[getAttr(key, el)] = value;

                        }

			 //	if(console)console.timeEnd('each(obj.setAttributes ('+key+')');
                    });
                }
            };
        };
		//rewrite shot informations
        } catch(e) {}

        tthis.control._this = tthis;
    }
    ticker = function(tthis) {
        tthis.ticker = new function() {
            this.start = function() {
                var t = tthis;
                this.pointer = setInterval(function() {
                    jS.queue.pB.set(t);
                }, t.interval);
            };
            this.stop = function() {
                var t = tthis;
                claerInterval(t.pointer);
            };
            this.pointer = null;
        };
        tthis.ticker._this = tthis;
    };
    rtrim = window.rtrim = function(tthis, ch) {
    	try {
        var vRet = tthis;
        for (var i = 1; i < arguments.length; i++) {
            vRet = vRet.replace(new RegExp(arguments[i] + "$", ""), "");
        }
    	}
        catch(e) {}
        return vRet;
    };
    ltrim = window.ltrim = function(tthis, ch) {
        var vRet = tthis;
        for (var i = 1; i < arguments.length; i++) {
            vRet = vRet.replace(new RegExp("^" + arguments[i], ""), "");
        }
        return vRet;
    };
    addslashes = window.addslashes = function(tthis) {
        return tthis.replace(/(["'])/g, '\\"');//'
    };
    cc = window.cc = function(tthis, String) {
        for (var i = 0; i < String.split("").length; i++) {
            tthis.push(String.split("")[i]);
        }
    };
    media = function(tthis) {
        tthis.media = new function() {
            this.init = function(func) {
                each(tthis, function(value, key) {
                	//console.info(MediaLibrary[key].Add);
                    if (cwOffice.MediaLibrary[key]) {
                        cwOffice.MediaLibrary[key].Add(value);
                    }
                });
            };
        };
    };

    /**
     * data: misc.js
     */
    com = new function() {
        this.innerWidth = function() {
            if (Stuff.Browser.isIE) {
                return document.body.offsetWidth;
            }
            else {
                return window.innerWidth;
            }
        }
        this.innerHeight = function() {
            if (Stuff.Browser.isIE) {
                return document.body.offsetHeight;
            }
            else {
                return window.innerHeight;
            }
        }
    }

    function $e(element) {
        return document.getElementById(element);
    }
    function $t(tag) {
        return document.getElementsByTagName(tag);
    }
    function $n(name) {
        return document.getElementsByName(name);
    }

    function setCw(obj) {
		obj = jS.convertToShortVars(obj);
        var el = $c(cwName(obj));
        if (el) {
			// AJAX UPLOAD
			if (el.type && el.type == "file" && obj.e == "upload") {
				cwOffice.upload.prepare($c(cwName(obj)), {restore: (obj.rc?obj.rc:0), url: (info.File!=null?info.File:window.location.pathname), onComplete: function(fi) {
					var el = $c(cwName(obj));
					var el = $c(cwName(obj));
					var p = el.getAttribute('upload');
					el.setAttribute('tmpname', fi['tmp_name']);
					obj.vars = fi;
					if(p) {
						jS.func = function(){
							setTimeout(function() {
								var o = cwOffice.util.extend({}, obj, {php:p.toString().split(','),event:'change'});
								cwOffice.util.loading.show();
								jS.queue.pA.set(o);
							}, 200);
						}
					}
					cwOffice.util.loading.show();
					jS.queue.pA.set(obj);
				}});
				return el;
			}
			else if (el.type && el.type == "file" && obj.e == "change") {
				el.setAttribute('upload', obj['p']);
			}
			else {
				//console.info(obj);
				setEvent(cwName(obj), obj.e, function(){
					//if(console) console.info('as');
					if(cwOffice.debug) cwOffice.debug.out('Start Event ...');
					cwOffice.util.loading.show();
					jS.queue.pA.set(obj);
				}, false);
				return el;
			}
        }
        else {
            return null;
        }
    }
    function $c(ident, cEvent) {

        if (cEvent != undefined && typeof(cEvent) == "number") {
            var el = isNull($e(ident)) ? $n(ident)[0] : $e(ident);

            /*if(Stuff.Browser.isIE) {
             var mu = document.getElementsByTagName(el.tagName);

             var x = 0;
             for(var i=0;i<mu.length;i++) {
             if(mu[i].name == ident) {
             if(cEvent == x) {
             return mu[i];
             }
             else x++;
             }
             }
             }
             else {*/
            return $n(ident)[cEvent];
            //}
        }
        else {
            return isNull($e(ident)) ? $n(ident)[0] : $e(ident);
        }
    }
    function $cw(element) {
        return !isNull($e('cwAutoControl[' + element + ']')) ? $c('cwAutoControl[' + element + ']') : isset($n('cwAutoControl[' + element + ']')[0]) ? $c('cwAutoControl[' + element + ']') : $c('cwAutoRepControl[' + element + ']');
    }
    function $a() {
        var foo = new Array;
        for (i = 0; i < arguments.length; i++)
            foo.push(arguments[i]);
        return foo;
    }
    function $evT(event) {
        return event.target ? event.target : event.srcElement;
    }
    function $ev(event) {
        return event ? event : window.event;
    }
    function $evPx(event) {
        return event.pageX ? event.pageX : event.clientX;
    }
    function $evPy(event) {
        return event.pageY ? event.pageY : event.clientY;
    }
    function $evLx(event) {
        return event.layerX ? event.layerX : event.x;
    }
    function $evLy(event) {
        return event.layerY ? event.layerY : event.y;
    }

    function isset() {
        var vRet = arguments.length != 0 ? true : false;
        for (var i = 0; i < arguments.length; i++) {
            vRet = typeof(arguments[i]) === "undefined" ? false : true;
        }
        return vRet;
    }
    function isNull() {
        var isNull = arguments.length != 0 ? true : false;
        for (var i = 0; i < arguments.length; i++) {
            isNull = arguments[i] !== null ? false : isNull;
        }
        return isNull;
    }

    /*
     Object.prototype.setEvent = function(eventN, handler, bubble){
     var element = typeof(this)=="object" ? this : $e(this);
     var bubble = bubble ? bubble : false;
     try {
     element.addEventListener(eventN, handler, bubble);
     } catch(e) {
     try {
     element.attachEvent("on" + eventN, handler );
     } catch(e) { alert(this + ".setEvent Error!"); }
     }
     }
     */
    setEvent = function(tthis, eventN, handler, bubble) {
        //alert(isset($e(this)) + " this = " + this + " !! " + $e(this) + ' !! ' + handler);
        //alert(this);
        if (tthis != 'window' && tthis != 'document') {
            var element = $c(tthis);
            if (element == null)
                return;
            //if(element.innerHTML == "Test") handler = function() { alert("test"); } ;
            var bubble = bubble ? bubble : false;
            try {
                element.addEventListener(eventN, handler, bubble);
            }
            catch (e) {
                try {
                    element.attachEvent("on" + eventN, handler);
                }
                catch (e) { /*alert(this + ".setEvent Error!");*/
                }
            }
        }
        else {
            eval(tthis + '.on' + eventN + ' = '.handler + ';');
        }
    }
    /*function setEvent(eventN, handler, bubble, obj) {
     var bubble = bubble ? bubble : false;
     try {
     obj.addEventListener(eventN, handler, bubble);
     }
     catch (e) {
     try {
     obj.attachEvent("on" + eventN, handler);
     }
     catch (e) {
     }
     }
     }
    ' */
    Stuff = new function() {
        this.Loading = new function() {
            this.Active = true;
            this.Center = true;
            this.IgnoreEvents = ['keyup', 'ticker', 'blur'];

            this.Show = function(EventType) {
				//console.info(EventType);
                if (!isNull($e('Loading')) && Stuff.Loading.Active /*&& Stuff.Loading.CheckEventType(EventType)*/) {
                    if (Stuff.Loading.Center) {
                        //	var left = ((com.innerWidth()/2)>90)?(com.innerWidth()/2) - 90:1;
                        //	var top = ((com.innerHeight()/2)>42)?(com.innerHeight()/2) - 42:1;

                        //	left = (Math.round(left) + 'px');
                        //	top = (Math.round(top) + 'px');
                        //alert("top:" + top + " !! " + "left:" + left + " !! " + com.innerWidth());
                        //	$e('Loading').style.left = left;
                        //	$e('Loading').style.top = top;
                    }
                    //$e('Loading').style.display = 'block';
                    if (document.getElementById('sys_winy') != null) {
                        if (getCoord("y") != null) {
                            // call function from berke editor
							var LoadingIcon = $e('Loading');
							if(LoadingIcon)
							{
								if(LoadingIcon.style.left)
									LoadingIcon.style.left = getCoord("x") + 15;
								if(LoadingIcon.style.top)
									LoadingIcon.style.top = getCoord("y");
								LoadingIcon.style.position = "absolute";
								LoadingIcon.style.zIndex = 10;
								LoadingIcon.style.display = 'block';
							}
                        }
                    }
                }
            }
            this.Hide = function() {
                if (!isNull($e('Loading')) && Stuff.Loading.Active) {
                    $e('Loading').style.display = 'none';
                }
            }
            this.CheckEventType = function(EventType) {
                for (var i = 0; i < Stuff.Loading.IgnoreEvents.length; i++) {
                    if (Stuff.Loading.IgnoreEvents[i] == EventType) {
                        //break -----
                        return false;
                    }
                }
                return true;
            }
        }
        this.Browser = new function() {
            this.isIE = navigator.appName == "Microsoft Internet Explorer" ? true : false;
            this.isFF = navigator.appName == "Netscape" ? true : false;
            this.appName = navigator.appName;
            this.appVersion = navigator.appVersion;
        }
    }

})();