function $typeof(type)
	{
		switch(typeof(type))
		{
			case 'string': return String;
			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);
					}
				}
			}
		}	
	}

var CwChat = new function() {
	this.iframe = null;
	this.cUserID = null;
	
	this.smiliePath = '/images/smilies/',
	this.smilies = [
		{ 'pattern': ':)', 'img': 'regular_smile.gif' },
		{ 'pattern': ':(', 'img': 'sad_smile.gif' },
		{ 'pattern': ';)', 'img': 'wink_smile.gif' },
		{ 'pattern': ':D', 'img': 'teeth_smile.gif' },
		{ 'pattern': ':/', 'img': 'confused_smile.gif' },
		{ 'pattern': ':P', 'img': 'tounge_smile.gif' },
		{ 'pattern': ':O', 'img': 'embaressed_smile.gif' },
		{ 'pattern': ':omg:', 'img': 'omg_smile.gif' },
		{ 'pattern': ':|', 'img': 'whatchutalkingabout_smile.gif' },
		{ 'pattern': ':@', 'img': 'angry_smile.gif' },
		{ 'pattern': ':angle:', 'img': 'angel_smile.gif' },
		{ 'pattern': '8-)', 'img': 'shades_smile.gif' },
		{ 'pattern': ':devil:', 'img': 'devil_smile.gif' },
		{ 'pattern': ';(', 'img': 'cry_smile.gif' },
		{ 'pattern': ':light:', 'img': 'lightbulb.gif' },
		{ 'pattern': ':n:', 'img': 'thumbs_down.gif' },
		{ 'pattern': ':y:', 'img': 'thumbs_up.gif' },
		{ 'pattern': ':h:', 'img': 'heart.gif' },
		{ 'pattern': ':u:', 'img': 'broken_heart.gif' },
		{ 'pattern': ':*', 'img': 'kiss.gif' }
	];
	this.getSmilies = function() {
		return this.smilies;
	}
	this.getSmiliePath = function() {
		return this.smiliePath;
	}
	
	this.openChat = function(cID) {
		if(!cID || cID == 'undefined' || cID == undefined) return;
		
		if($("#CwChatWindow"+cID).length > 0) {
			$("#CwChatWindow"+cID).css('display', '');
			return;
		}
		
		var settings = CwChat.readCookie("Settings");
		if(settings != null) {
			if(!settings[cID]) {
				settings[cID] = new Object();
				settings[cID]["min"] = false;
				settings[cID]["cu"] = CwChat.cUserID;
				CwChat.createCookie(settings, "Settings");
			}
//			else if(settings[cID]["position"]) {
//				div.style.position = 'absolute';
//				div.style.left = settings[cID]["position"]['left'];
//				div.style.top = settings[cID]["position"]['top'];
//			}
		}
		else {
			var settings = new Object();
			settings[cID] = new Object();
			settings[cID]["min"] = false;
			settings[cID]["cu"] = CwChat.cUserID;
			CwChat.createCookie(settings, "Settings");
		}
		
		var div = document.createElement('div');
		div.id = 'CwChatWindow'+cID;
		div.className = 'chatBorder';
		div.style.position = 'fixed';
		if(!window.XMLHttpRequest) {	
			div.style.position = 'absolute';
		}
		if (settings[cID]["position"]) {
			div.style.top = settings[cID]["position"]['top'] + 'px';
			div.style.left = settings[cID]["position"]['left'] + 'px';
		}
		else {
			div.style.top = '10px';
			div.style.left = '10px';
		}
		
		
		var hide = (settings[cID]["min"]?'style="display:none;"':'');
		if(hide != '') {
			div.style.height = '22px';
		}
		div.innerHTML = '<div class="chatWindow" style="position:absolute;bottom:0px;left:0px;">' +
			'<div class="chatHeader">' +
				'<div class="chatTitle"></div>' +
				'<div class="chatButtonClose" onclick="CwChat.closeChat('+cID+');"></div>' +
				'<div class="chatButtonHide" onclick="CwChat.toggleMinMax('+cID+');"></div>' +
				'<!-- <div class="chatButtonMin" onclick="chat.toggleMinMax('+cID+');"></div> -->' +
			'</div>' +
			'<div class="chatBody" '+hide+'>' +
				'<div id="chatContent" class="chatContent">' +
'<iframe src="http://'+window.location.host+'/cwoffice42/modules/CwChat/window.php?users='+cID+'" frameborder="0" border="0" marginwidth="0" marginheight="0" scrolling="no" class="chatIFrame" name="CwChatIframe'+cID+'" id="CwChatIframe'+cID+'" style="overflow:hidden;" ></iframe>'+
				'</div>' +
				'<div class="chatNotification">' +
					'<div class="chatSmilieBox"></div>' +
					'<div class="chatSmilies">' +
						'<img src="/images/smilies/regular_smile.gif" />' +
					'</div>' +
				'</div>' +
				'<div class="chatFooter">' +
					'<textarea class="chatInput" id="CwChatInput'+cID+'"></textarea>' +
					'<div class="chatAd">' +
					'</div>' +
				'</div>' +
			'</div>' +
		'</div>';// onload="CwChat.insertCookieMassages('+cID+');"

		$("#CwChatContainer")[0].appendChild(div);
		//if(console) console.info(div.style.top);
		setTimeout(function() {
		if($(div).position().top < 0 || $(div).position().left < 0) {
			div.style.top = '10px';
			div.style.left = '10px';
		}
		}, 50);
		
		$(div).draggable({
			iframeFix: true,
			cursor: 'default',
			containment: 'body',
			opacity: 0.85,
			handle: 'div.chatHeader',
			stop: function(event, ui){
				var settings = CwChat.readCookie("Settings");
			//	if(console) console.info(ui);
				settings[cID]["position"] = {};
				settings[cID]["position"]['left'] = ui.position.left; //absolutePosition
				settings[cID]["position"]['top'] = ui.position.top;
				CwChat.createCookie(settings, "Settings");
			}
		});
		
		//console.info($('.chatSmilies', div));
		$('.chatSmilies > img', div).click(function() {
			if($('.chatSmilieBox:visible', div).length == 0) {
				$('.chatSmilieBox', div).show();
			} else {
				$('.chatSmilieBox', div).hide();
			}
		});
		
		var box = $('.chatSmilieBox', div)[0];
		for(var i=0;i<this.smilies.length;i++) {
			box.innerHTML += '<img src="'+this.smiliePath+this.smilies[i]['img']+'" alt="'+this.smilies[i]['pattern']+'" />';
		}
		$('.chatSmilieBox img', div).click(function() {
			var input = $('.chatInput', div)[0];
			var myValue = $(this)[0].alt;
			if(myValue == null) return;
			
			if (document.selection) {
				input.focus();
				sel = document.selection.createRange();
				sel.text = myValue;
				input.focus();
			}
			else if (input.selectionStart || input.selectionStart == '0') {
				var startPos = input.selectionStart;
				var endPos = input.selectionEnd;
				var scrollTop = input.scrollTop;
				input.value = input.value.substring(0, startPos)+myValue+input.value.substring(endPos,input.value.length);
				input.focus();
				input.selectionStart = startPos + myValue.length;
				input.selectionEnd = startPos + myValue.length;
				input.scrollTop = scrollTop;
			} else {
				input.value += myValue;
				input.focus();
			}
			
			$(this).parent().hide();
		});
		
		
		$('#CwChatInput'+cID).one('keyup', function(e){
			CwChat.checkEnter(e, cID);
		});
		 
		if(settings[cID]["min"]) CwChat.toggleMinMax();
		//if(settings[cID]["cu"] != this.cUserId) CwChat.createCookie(false);
		

		
		$('.chatWindow', div).bind('click', function(){
			CwChat.markAsRead(cID);
		});
		$('.chatInput', div).bind('click', function(){
			CwChat.markAsRead(cID);
		});
		$('.chatInput', div).bind('keyup', function(){
			CwChat.markAsRead(cID);
		});
		//CwChat.adjustIframe();
	};
	
	this.setTitle = function(cid, name) {
		//console.info('#CwChatWindow'+cid+'  div.chatTitle');
		$('#CwChatWindow'+cid+' div.chatTitle').text(name);
	}
	
//	this.insertCookieMassages = function(cID) {
//		var obj = CwChat.readCookie(cID);
//		if (obj != null) {
//			each(obj, function(value, key){
//				window.frames['CwChatIframe'+cID].CwChat.insertMessage(value["name"], value["message"], value["id"], false);
//			});
//		}
//	}
	
	this.closeChat = function(id) {
		var settings = CwChat.readCookie("Settings");
		if(settings[id]) delete settings[id];
		CwChat.createCookie(settings, "Settings");
		
		var div = $("#CwChatWindow"+id)[0];
		$("#CwChatContainer")[0].removeChild(div);
	};
	
	/**
	 * init function (construct)
	 * @param {Object} cUserId
	 */
	this.checkOpenChats = function(cUserId) {
		this.iframe = window.frames['CwChatSystem'];
		//console.info(window.frames['CwChatSystem']);
		this.cUserID = cUserId;
		
		var settings = null;
		var nameEQ = "CwChatSettings=";
		var ca = document.cookie.split(';');
		for(var i=0;i < ca.length;i++) {
			var c = ca[i];
			while (c.charAt(0)==' ') c = c.substring(1,c.length);
			if (c.indexOf(nameEQ) == 0) settings = eval("(" + decodeURIComponent(c.substring(nameEQ.length,c.length)) + ")");
		}
		
		if(settings != null) {
			each(settings, function(value, key) {
				//if(console) console.info(cUserId);
				//console.info(value);
				if (cUserId == value['cu']) {
					CwChat.openChat(key);
				}
			});
		}
		
		CwChat.iframe.cwOffice.jS.queue.pA.set({"name":"CwChatGetLastMessages","php":["CwChat","getLatestMessages"],"getControls":[]});
	};
	
	
	this.markToReadInterval = null;
	this.markAsRead = function(id) {
		$('#CwChatWindow'+id+' .chatHeader').css('background-image', 'url(http://www.cwcity.de/style/img/chat_top.jpg)');
		clearInterval(CwChat.markToReadInterval);
		CwChat.markToReadInterval = null;
		CwChat.changeShortIcon("http://www.cwcity.de/style/img/favicon.ico");
		//CwChat.changeOrgTitle();
	};
	this.markToRead = function(id) {
		$('#CwChatWindow'+id+' .chatHeader').css('background-image', 'url(http://www.cwcity.de/style/img/chat_top_alert.jpg)');
		if(CwChat.markToReadInterval != null) {
			CwChat.markAsRead(id);
		}
		CwChat.markToReadInterval = setInterval(function() {
			if ($('#CwChatWindow'+id+' .chatHeader').css('background-image') == 'url(http://www.cwcity.de/style/img/chat_top.jpg)') {
				$('#CwChatWindow'+id+' .chatHeader').css('background-image', 'url(http://www.cwcity.de/style/img/chat_top_alert.jpg)');
				CwChat.changeShortIcon("http://www.cwcity.de/cwoffice42/templates/modules/CwChat/images/sballoon.ico");
			}
			else {
				$('#CwChatWindow'+id+' .chatHeader').css('background-image', 'url(http://www.cwcity.de/style/img/chat_top.jpg)');
				CwChat.changeShortIcon("http://www.cwcity.de/style/img/favicon.ico");
			}
		}, 1500);
		//CwChat.changeTitle($('#cwAutoControl\\[User\\]').text() + " hat geschrieben! ", true);
	};
	
	this.checkEnter = function(e, cid) {
		var e = e || window.event;
		//console.info(cid);
			if ((('v' == '\v' && e.which == "13") || e.keyCode == "13") && !(e.ctrlKey || e.altKey || e.shiftKey)) {
				if ($('#CwChatInput'+cid).val().replace(/(\n|\r)/g, "") != "") {
					CwChat.sendMessage(cid);
				}
				else {
					if ('v' == '\v') {
						setTimeout(function(){
							$('#CwChatInput' + cid).one('keyup', function(e){
								CwChat.checkEnter(e, cid, '123b');
							});
						}, 100);
					}
					else {
						$('#CwChatInput' + cid).one('keyup', function(e){
							CwChat.checkEnter(e, cid, '123a');
						});
					}
				}
			}
			else {
				if ('v' == '\v') {
					setTimeout(function(){
						$('#CwChatInput' + cid).one('keyup', function(e){
							CwChat.checkEnter(e, cid, '123b');
						});
					}, 100);
				}
				else {
					$('#CwChatInput' + cid).one('keyup', function(e){
						CwChat.checkEnter(e, cid, '123a');
					});
				}
			}
	};
	
	this.sendMessage = function(cid) {
		var chat = window.frames['CwChatIframe'+cid];
		var message = $('#CwChatInput'+cid).val();
		$('#CwChatInput'+cid).val("");
		//console.info(chat.CwChat);
		id = chat.CwChat.insertMessage("me: ", message, '-1', true, (new Date()).getTime());
		
		chat.cwOffice.jS.func = function() {
		 	$('#CwChatInput'+cid).one('keyup', function(e){
				CwChat.checkEnter(e, cid);
			});
		};
		chat.cwOffice.jS.queue.pA.set({"name":"CwChatSend","php":["CwChat","sendMessage"],"getControls":[{"Name":"chatInput","getAttributes":{"value":message}}]});
		
//		//if (cookie == true) {
//		console.info(cid);
//			var obj = CwChat.readCookie(cid);
//			
//			if (obj == null || obj == false) {
//				obj = [];
//			}
//			console.info(obj);
//			obj.push({
//				"name": "me: ",
//				"message": message,
//				"id": id
//			});
//			console.info(obj);
//			
//			if (obj.length > 5) {
//				obj.shift();
//			}
//			console.info(obj);
//			
//			CwChat.createCookie(obj, cid);
//		//}
	};
	
	
	this.createCookie = function(obj, name) {
		var name = name || CwChat.ID;
	//console.info(name);
		
		var date = new Date();
		date.setTime(date.getTime()+(1*24*60*60*1000)); //cwOffice.
		//console.warn(obj);
		var txt = CwChat.iframe.cwOffice.toJSONString(obj);
		//console.info(txt);
		txt = encodeURIComponent(txt);
		document.cookie = "CwChat"+name+"="+txt+"; expires="+date.toGMTString()+"; path=/";
	};

	this.readCookie = function(name) {
		var name = name || CwChat.ID;
		
		var nameEQ = "CwChat"+name+"=";
		var ca = document.cookie.split(';');
		for(var i=0;i < ca.length;i++) {
			var c = ca[i];
			while (c.charAt(0)==' ') c = c.substring(1,c.length);
			if (c.indexOf(nameEQ) == 0) return eval("(" + decodeURIComponent(c.substring(nameEQ.length,c.length)) + ")");
		}
		return null;
	};
	
	this.toggleMinMax = function(cid) {
		var settings = CwChat.readCookie("Settings");
	
		if(!settings[cid]) {
			settings[cid] = {};
		}
		
		//console.info($("#CwChatWindow"+cid+" div.chatBody:visible"));
		if($("#CwChatWindow"+cid+" div.chatBody:visible").length == 0) {
			$("#CwChatWindow"+cid).css('height', null);
			$("#CwChatWindow"+cid+" div.chatBody").show();
			settings[cid]["min"] = false;
		}
		else {
			$("#CwChatWindow"+cid).css('height', '22px');
			$("#CwChatWindow"+cid+" div.chatBody").hide();
			settings[cid]["min"] = true;
		}
		settings[cid]["cu"] = CwChat.cUserID;
		
		CwChat.createCookie(settings, "Settings");
		
		
	};
	
	/* NEW MASSAGE NOTIFICATION */
	this.changeShortIcon = function(icon) {
		try {
//			var si = parent.window.document.getElementById('shortcutIcon');
//			if (si) {
//				si.href = icon;
//			}
			addLink(icon);
		} catch(e) {}
	};
	
	var orgTitle = null;
	this.changeTitle = function(title, move) {
		try {
			if(orgTitle == null) {
				orgTitle = window.document.title;
			}
			if (move == true) {
				window.document.title = "CwCity.de";
				titleAppear(title);
			}
			else {
				window.document.title = title;
			}
		} catch(e) {
			
		}
	};
	this.changeOrgTitle = function() {
		try {
			if (orgTitle != null) {
				window.document.title = orgTitle;
				orgTitle = null;
			}
		} catch(e) {
			
		}
	};
	titleAppearCount = 0;
	function titleAppear(text){
		if (orgTitle != null) {
			if (titleAppearCount != text.length) {
				// Add next character...
				document.title = text.charAt(text.length - (++titleAppearCount)) + document.title;
				setTimeout(function() {
					titleAppear(text);
				}, 50);
			}
			else {
				titleAppearCount = 0;
				setTimeout(function(){
					titleDisappear(text);
				}, 3000);
			}
		}
	}
	function titleDisappear(text){
		if (orgTitle != null) {
			if (titleAppearCount != text.length) {
				// 'Remove' characters
				var len = text.length - (++titleAppearCount);
				var str = text.substr(titleAppearCount, len);
				
				document.title = str + "CwCity.de";
				setTimeout(function(){
					titleDisappear(text);
				}, 50);
				
			}
			else {
				document.title = "CwCity.de";
				titleAppearCount = 0;
				setTimeout(function(){
					titleAppear(text);
				}, 1000);
			}
		}
	}
	
	function addLink(iconURL) {
	  var link = document.createElement("link");
	  link.type = "image/x-icon";
	  link.rel = "shortcut icon";
	  link.href = iconURL;
	  removeLinkIfExists();
	  document.getElementsByTagName("head")[0].appendChild(link);
	}
	
	function removeLinkIfExists() {
	  var links = document.getElementsByTagName("head")[0].getElementsByTagName("link");
	  for (var i=0; i<links.length; i++) {
	    var link = links[i];
	    if (link.type=="image/x-icon" && link.rel=="shortcut icon") {
	      document.getElementsByTagName("head")[0].removeChild(link);
	      return; // Assuming only one match at most.
	    }
	  }
	}

};
