smilieboxOver = false;

function hideSmiliebox() {
	if (!smilieboxOver) {
		$('smiliebox').setStyle('display', 'none');
	}
}

function hideSmilieboxDelayed() {
	smilieboxOver = false;
	setTimeout("hideSmiliebox()", 250);
}

function showSmiliebox() {
	if (!smilieboxOver) {
		smilieboxOver = true;
		$('smiliebox').setStyle('display', 'block');
	}
}

function winWidth() {
  if (window.innerWidth) {
    return window.innerWidth;
  } else if(document.documentElement && document.documentElement.clientWidth) {
    return document.documentElement.clientWidth;
//  } else if (document.body && document.body.offsetWidth) {
  //  return document.body.offsetWidth;
  } else {
    return 0;
  }
}

function winHeight() {
  if (window.innerHeight) {
    return window.innerHeight;
  } else if(document.documentElement && document.documentElement.clientHeight) {
    return document.documentElement.clientHeight;
//  } else if (document.body && document.body.offsetHeight) {
//    return document.body.offsetHeight;
  } else {
    return 0;
  }
}



APE.Chat = new Class({

	Extends: APE.Client,

	Implements: Options,

	options: {
		container: null,
		logs_limit: 10,
		container: document.body
	},

	test: function () {
		alert("test");
	},

	preloadSmilies: function () {
		this.preloadedSmilies = new Array();
		this.smilies.each(function (val, key) {
			val = val['n'];
			tmp = new Asset.image('/images/chat/emoticons/' + val, {
				'alt': key,
				'title': key,
				'styles': {
					'opacity': 0.6
				},
				'events': {
					'click': function () {
						s = $("sendbox_input");
						l = s.length;
						if (l > 0 && s.value[l] == " ") s.value += " ";

						s.value += key + " ";
						s.focus();
					},
					'mouseover': function () {
						this.style.opacity = 1;
					},
					'mouseout': function () {
						this.style.opacity = 0.6;
					}

				}
			});
			this.preloadedSmilies.extend([tmp]);
		}.bind(this));
	},


	initialize: function (options) {
		this.setOptions(options);

		this.els = {};
		this.chatToolbarVisible = false;

		this.currentPipe = null;
		this.logging = true;

		this.bannedWords = [
			"fotze", "wixer", "hurensohn", "schwanzlutscher"
		];

		this.smilies = new Hash({
			":-)": new Hash({
				n: "smile.gif",
				r: /\:\-?\)/g
			}),
			";-)": new Hash({
				n: "wink.gif",
				r: /\;\-?\)/g
			}),
			":-D": new Hash({
				n: "biggrin.gif",
				r: /\:\-?D/g
			}),
			":-P": new Hash({
				n: "tongue.gif",
				r: /\:\-?P/g
			}),
			":-(": new Hash({
				n: "sad.gif",
				r: /\:\-?\(/g
			}),
		});


		this.preloadSmilies();

		this.onRaw('data', this.rawData);
		this.onCmd('send', this.cmdSend);
		this.onRaw('authorized', this.authorized);
		this.onError('004', this.reset);

		this.onError('006', this.promptName);
		this.onError('007', this.promptName);
		this.onError('109', this.unknownPipe);
		this.onError('710', this.floodDetected);
		this.onError('711', this.tooLongMessageDetected);

		this.addEvent('load', this.start);
		this.addEvent('ready', this.createChat);
		this.addEvent('uniPipeCreate', this.setPipeName);
		this.addEvent('uniPipeCreate', this.createPipe);
		this.addEvent('multiPipeCreate', this.createPipe);
		this.addEvent('userJoin', this.createUser);
		this.addEvent('userLeft', this.deleteUser);
	},

	floodDetected: function(errorRaw) {
		if (this.currentPipe) {
			this.writeMessage(this.currentPipe, "Zu viele Nachrichten. Die Nachricht wurde nicht zugestellt.");	
		}
	},

	tooLongMessageDetected: function(errorRaw) {
		if (this.currentPipe) {
			this.writeMessage(this.currentPipe, "Zu lange Nachricht. Die Nachricht wurde nicht zugestellt.");	
		}
	},


	authorized: function (data) {
		this.core.join(this.options.chat_name + "_" + this.options.chat_room);
	},

	unknownPipe: function(errorRaw) {
		if (this.currentPipe) {
			this.writeMessage(this.currentPipe, "Benutzer ist nicht mehr online. Die Nachricht konnte nicht zugestellt werden.");
//		this.writeMessage(pipe, raw.data.msg, raw.data.from);

		}
	},

	promptName: function (errorRaw) {
		this.els.namePrompt = {};
		this.els.namePrompt.div = new Element('form', {
			'class': 'ape_name_prompt',
			'text': 'Wähle ein Pseudonym: '
		}).inject(this.options.container)
		this.els.namePrompt.div.addEvent('submit', function (ev) {
			ev.stop();
			this.options.name = this.els.namePrompt.input.get('value');
			this.els.namePrompt.div.dispose();
			this.start()
		}.bindWithEvent(this));
		this.els.namePrompt.input = new Element('input', {
			'class': 'text'
		}).inject(this.els.namePrompt.div);
		new Element('input', {
			'class': 'submit',
			'type': 'submit',
			'value': 'LOS!'
		}).inject(this.els.namePrompt.div)
		var error;
		if (errorRaw) {
			if (errorRaw.data.code == 007) error = 'Dieser Name wird bereits benutzt';
			if (errorRaw.data.code == 006) error = 'Dein Name darf nur aus Buchstaben und Zahlen bestehen';
			if (error) {
				new Element('div', {
					'styles': {
						'padding-top': 5,
						'font-weight': 'bold'
					},
					'text': error
				}).inject(this.els.namePrompt.div);
			}
		}
	},

	start: function (config) {
		//If name is not set & it's not a session restore ask user for his nickname
		if (this.options.chat_name == '' && !config.options.name && !this.core.options.restore) {
			alert('Konfigurationsfehler');
		} else {
			var opt = {
				'sendStack': false,
				'request': 'stack'
			};

			//			this.core.start({'name':this.options.name}, opt);

			if (config) {
				this.options.chat_name = config.options.chat_name;
				this.options.chat_room = config.options.chat_room;
				this.options.name = config.options.name;
				this.options.user_id = config.options.user_id;
				this.options.chat_user_id = config.options.chat_user_id;
				this.options.password = config.options.password;
			}

			this.core.start({
				'name': this.options.name,
				'user_id': this.options.user_id,
				'chat_user_id': this.options.chat_user_id,
				'chat_name': this.options.chat_name,
				'chat_room': this.options.chat_room,
				'password': this.options.password
			},
			opt);

			if (this.core.options.restore) {
				this.core.getSession('currentPipe', function (resp) {
					if (resp.data.sessions.currentPipe != "null") 
						this.setCurrentPipe(resp.data.sessions.currentPipe);
				}.bind(this), opt);
			}

			this.core.request.stack.send();
		}
	},

	setPipeName: function (pipe, options) {
		if (options.name) {
			pipe.name = options.name;
			return;
		}
		if (options.from) {
			pipe.name = options.from.properties.name;
		} else {
			pipe.name = options.pipe.properties.name;
		}
	},

	getCurrentPipe: function () {
		return this.currentPipe;
	},

	addChatToolbar: function () {
		els = {};
		els.tab = new Element('div', {
			'class': '',
			'id': 'emoticon_tab'
		}).inject(this.els.chatToolbar);

		//Add smiliebox to chatToolbar
		tmp = new Element('a', {
			'alt': "Emoticons",
			'title': "Emoticons",
			'href': 'javascript:void(0)',
			'events': {
				'mouseover': showSmiliebox,
				'mouseout': hideSmilieboxDelayed
			}
		}).inject(els.tab);
		new Element('img', {
			'src': '/images/chat/emoticons/smile.gif'
		}).inject(tmp);

		tmp = new Element('div', {
			'class': '',
			'id': 'smiliebox',
			'events': {
				'mouseover': showSmiliebox,
				'mouseout': hideSmilieboxDelayed
			}
		}).inject(this.els.chatToolbar);

		// add smilies to smiliebox
		this.preloadedSmilies.each(function (val, index) {
			val.inject(tmp);
		});
	},

	setCurrentPipe: function (pubid, save) {
		save = !save;
		if (this.currentPipe) {
			this.currentPipe.els.tab.addClass('unactive');
			this.currentPipe.els.container.addClass('ape_none');
		}
		this.currentPipe = this.core.getPipe(pubid);
		this.currentPipe.els.tab.removeClass('new_message');
		this.currentPipe.els.tab.removeClass('unactive');
		this.currentPipe.els.container.removeClass('ape_none');
		this.scrollMsg(this.currentPipe);
		if (save) {
			this.core.setSession({
				'currentPipe': this.currentPipe.getPubid()
			});

			if (this.currentPipe.users) {
				if (!this.chatToolbarVisible) {
					this.addChatToolbar();

					this.chatToolbarVisible = true;
				}
			}
			/*
			else if (this.emoticonsTabShown) {
				// remove tab
//				this.els.tabs.getChildren()
//document.getElementById("emoticon_tab").destroy();
				var par = document.getElementById("tabbox_container");
				var chi = document.getElementById("emoticon_tab");
				par.removeChild(chi);
				this.emoticonsTabShown = false;
			}
			*/

		}
		return this.currentPipe;
	},

	cmdSend: function (data, pipe) {
		//this.writeMessage(pipe, data.msg, this.core.user);
	},

	rawData: function (raw, pipe) {
		this.writeMessage(pipe, raw.data.msg, raw.data.from);
	},

	parseMessage: function (message) {
		msg = message;
		msg = decodeURIComponent(msg);
		msg = msg.replace(/\</g, '&lt;');
		this.smilies.each(function(val, key) {
			msg = msg.replace(val['r'], '<img src="/images/chat/emoticons/' + val['n'] + '" border="0"/>');
		});
		this.bannedWords.each(function(val) {
			var word = "";
			for (var i = 0; i<val.length; ++i) {
				word += val[i]+"+"
			}

			msg = msg.replace((new RegExp(''+word+'', 'gi')), "<i>*zensiert*</i>");
		});
		return msg;
	},

	notify: function (pipe) {
		pipe.els.tab.addClass('new_message');
	},

	scrollMsg: function (pipe) {
		var scrollSize = pipe.els.message.getScrollSize();
		pipe.els.message.scrollTo(0, scrollSize.y);
	},

	writeMessage: function (pipe, message, from) {
		//Append message to last message
		if (from && pipe.lastMsg && pipe.lastMsg.from && pipe.lastMsg.from.pubid == from.pubid) {
			var cnt = pipe.lastMsg.el;
		} else { //Create new one
			//Create message container
			var msg = new Element('div', {
				'class': 'ape_message_container'
			});
			var cnt = new Element('div', {
				'class': 'msg_top'
			}).inject(msg);
//			if (from) {
				new Element('div', {
					'class': 'ape_user',
					'text': (from) ? from.properties.name.split("_")[1] + ':' : 'System:'
				}).inject(msg, 'top');
//			}
			new Element('div', {
				'class': 'msg_bot'
			}).inject(msg);
			msg.inject(pipe.els.message);
		}
		new Element('div', {
			'html': this.parseMessage(message),
			'class': 'ape_message'
		}).inject(cnt);

		this.scrollMsg(pipe);

		pipe.lastMsg = {
			from: from,
			el: cnt
		};

		//notify 
		if (this.getCurrentPipe().getPubid() != pipe.getPubid()) {
			this.notify(pipe);
		}
	},

	createUser: function (user, pipe) {
		user.el = new Element('div', {
			'class': 'ape_user'
		}).inject(pipe.els.users);
		new Element('a', {
			'text': user.properties.name.split("_")[1],
			'href': 'javascript:void(0)',
			'events': {
				'click': function (ev, user) {
					this.core.getPipe(user.pubid)
					this.setCurrentPipe(user.pubid);
				}.bindWithEvent(this, [user])
			}
		}).inject(user.el, 'inside');
		this.writeMessage(pipe, user.properties.name.split("_")[1] + " betritt den Chat", pipe);
	},

	deleteUser: function (user, pipe) {
		this.writeMessage(pipe, user.properties.name.split("_")[1] + " verlässt den Chat", pipe);
		user.el.dispose();
	},

	createPipe: function (pipe, options) {
		var tmp;

		//Define some pipe variables to handle logging and pipe elements
		pipe.els = {};
		pipe.logs = new Array();

		//Container
		pipe.els.container = new Element('div', {
			'class': 'ape_pipe ape_none '
		}).inject(this.els.pipeContainer);

		//Message container
		pipe.els.message = new Element('div', {
			'class': 'ape_messages'
		}).inject(pipe.els.container, 'inside');

		//If pipe has a users list 
		if (pipe.users) {
			pipe.els.usersRight = new Element('div', {
				'class': 'users_right',
				'styles': {
					'height': "390px"
				}
			}).inject(pipe.els.container);

			pipe.els.users = new Element('div', {
				'class': 'ape_users_list',
				'styles': {
					'height': "390px"
				}
			}).inject(pipe.els.usersRight);
		}
		//Add tab
		pipe.els.tab = new Element('div', {
			'class': 'ape_tab unactive'
		}).inject(this.els.tabs);

		new Element('a', {
			'text': pipe.name.split("_")[1],
			'href': 'javascript:void(0)',
			'events': {
				'click': function (pipe) {
					this.setCurrentPipe(pipe.getPubid())
				}.bind(this, [pipe])
			}
		}).inject(pipe.els.tab);


		if (pipe.type == 'uni') {

			new Element('span', {
				'html': "&nbsp;"
			}).inject(pipe.els.tab);


			new Element('a', {
				'text': "x",
				'href': 'javascript:void(0)',
				'styles': {
						'color':'#aaa'		
				},
				'events': {
					'click': function (pipe) {
						if (pipe.type == 'uni') {
							this.core.delPipe(pipe.getPubid());
							this.core.saveSessionPipe();
						}
						else {
							pipe.left();
						}


						pipe.els.container.dispose();
						pipe.els.tab.dispose();		

						if (this.core.pipes.getLength() > 0) {
							var opipe;
							this.core.pipes.each(function(val, key) {
								opipe = key;
							});
							this.setCurrentPipe(opipe);
						}				
					}.bind(this, [pipe])
				}
			}).inject(pipe.els.tab);
		}

		//Hide other pipe and show this one
		this.setCurrentPipe(pipe.getPubid());
	},

	createChat: function () {
		this.els.pipeContainer = new Element('div', {
			'id': 'ape_container',
			'styles': {
				'height': "400px"
			}
		});
		this.els.pipeContainer.inject(this.options.container);

		this.els.more = new Element('div', {
			'id': 'more'
		}).inject(this.options.container, 'after');
		this.els.tabs = new Element('div', {
			'id': 'tabbox_container'
		}).inject(this.els.more);
		this.els.chatToolbar = new Element('div', {
			'id': 'chat_toolbar'
		}).inject(this.els.more);
		this.els.sendboxContainer = new Element('div', {
			'id': 'chat_sendbox_container',
			'class': 'rbox_container'
		}).inject(this.els.more);

		this.els.sendBoxTop = new Element('div', {
			'class': 'rbox_top',
			'events': { 'click' : function() { $('sendbox_input').focus(); }}
		}).inject(this.els.sendboxContainer, 'bottom');
		this.els.sendBoxTopSpan = new Element('span').inject(this.els.sendBoxTop, 'bottom');

		this.els.sendBox = new Element('div', {
			'id': 'chat_sendbox',
			'class': 'rbox_center',
			'events': { 'click' : function() { $('sendbox_input').focus(); }}
		}).inject(this.els.sendboxContainer, 'bottom');
		this.els.sendboxForm = new Element('form', {
			'events': {
				'submit': function (ev) {
					ev.stop();
					var val = this.els.sendbox.get('value');
					if (val != '') {
						this.getCurrentPipe().send(val);
						this.els.sendbox.set('value', '');
					}
				}.bindWithEvent(this)
			}
		}).inject(this.els.sendBox);
		this.els.sendbox = new Element('input', {
			'type': 'text',
			'id': 'sendbox_input',
			'autocomplete': 'off',
			'maxlength': 300
		}).inject(this.els.sendboxForm);
		this.els.sendbox.focus();

		this.els.sendBoxBottom = new Element('div', {
			'class': 'rbox_bottom',
			'events': { 'click' : function() { $('sendbox_input').focus(); }}
		}).inject(this.els.sendboxContainer, 'bottom');
		this.els.sendBoxBottomSpan = new Element('span').inject(this.els.sendBoxBottom, 'bottom');

		/*
		this.els.send_button = new Element('input',{
							'type':'button',
							'id':'sendbox_button',
							'value':''
						}).inject(this.els.sendboxForm);
*/
	},

	reset: function () {
		this.core.clearSession();
		if (this.els.pipeContainer) {
			this.els.pipeContainer.dispose();
			this.els.more.dispose();
		}
		this.core.initialize(this.core.options);
	}
});

