Chat = new Class ({
	morphTabs: null,
	activeIndex: null,
	IDs: new Array(),

	buildRoom: function (id, room) {
		txt = '';
	
		if(!$defined($('containerUL'))) {

			$('container').set('html', '');

			ul = new Element('ul', {
				'id': 'containerUL',
				'class': 'morphtabs_title'
			});
			$('container').adopt(ul);		

			li = new Element('li', {
				'title': 'room' + id,
				'html': room
			});
			$('containerUL').adopt(li);

			div = new Element('div', {
				'id': 'room' + id,
				'html': '',
				'class': 'morphtabs_panel'
			});
			$('container').adopt(div);

			options = {
				width: '588px',
    				height: '270px',
		    		changeTransition: ''
			}

			this.morphTabs = new MorphTabs('container', options);

			span = new Element('span', {
				'title': 'zamknij',
				'html': '&nbsp;&nbsp;X',
				'styles': {
					'color': '#9C1A2A',
					'font-weight': 'bold'
				}
			});
			li.adopt(span);
		
			span.addEvent('click', function() {
				if(this.morphTabs.titles.length == 1) {alert('Nie możesz usunąć ostatniej zakładki'); return;}
				this.morphTabs.titles.each(function(el, index){
					if(this.morphTabs.titles[index].title.toString() == 'room' + id) {
						i = index;				
					}
				}.bind(this));

				this.morphTabs.titles.splice(i, 1);
				this.morphTabs.removeTab('room' + id);
				this.IDs[id] = [];

				request = { 'room_id' : id, 'text': 'Opuścił pokój'};

				new Request({
					encoding: 'utf-8',   
            			method: 'post',   
            			url: '/portal/index.php?id=1727',   
            			data: request,   
            			onRequest: function() {},   
            			onSuccess: function(response) {},
            			onFailure: function() {} 
        			}).send();

			}.bind(this));

			this.IDs[id] = [];

			div = new Element('div', {
				'styles': {
					'height': '10px'
				}
			});
			$('container').adopt(div);

			input = new Element('input', {
				'type': 'text',
				'id': 'dialogueText',
				'size': '80',
				'class': 'field'				
			});
			$('container').adopt(input);

			input.addEvent('keydown', function(event) {
				event = new Event(event);
				if (event.key == 'enter') {
					room_id = this.morphTabs.panel.id.replace('room', '');
				
					request = { 'room_id' : room_id, 'text': $('dialogueText').value};
					this.makeRequest(request, null);

					$('dialogueText').value = ''; 
				}
			}.bind(this));

			input = new Element('input', {
				'type': 'button',
				'id': 'dialogueButton',
				'class': 'button',
				'value': 'wyślij'				
			});
			$('container').adopt(input);

			input.addEvent('click', function() {
				room_id = this.morphTabs.panel.id.replace('room', '');
				
				request = { 'room_id' : room_id, 'text': $('dialogueText').value};
				this.makeRequest(request, null);

				$('dialogueText').value = ''; 
			}.bind(this));	

			txt = 'Dołączył';	
		}
		else if($$('li[title=room' +id+ ']').length == 0){			
			this.morphTabs.addTab('room' + id, room, '');
			$$('li[title=room' +id+ ']').each(function(e, i){
				span = new Element('span', {
					'title': 'zamknij',
					'html': '&nbsp;&nbsp;X',
					'styles': {
						'color': '#9C1A2A',
						'font-weight': 'bold'
					}
				});
				e.adopt(span);

				span.addEvent('click', function() {
					if(this.morphTabs.titles.length == 1) {alert('Nie możesz usunąć ostatniej zakładki'); return;}
					this.morphTabs.titles.each(function(el, index){
						if(this.morphTabs.titles[index].title.toString() == 'room' + id) {
							i = index;				
						}
					}.bind(this));

					this.morphTabs.titles.splice(i, 1);
					this.morphTabs.removeTab('room' + id);
					this.IDs[id] = [];

					request = { 'room_id' : id, 'text': 'Opuścił pokój'};

					new Request({
						encoding: 'utf-8',   
            				method: 'post',   
            				url: '/portal/index.php?id=1727',   
            				data: request,   
            				onRequest: function() {},   
            				onSuccess: function(response) {},
            				onFailure: function() {} 
        				}).send();
				
				}.bind(this));
			}.bind(this));

			this.IDs[id] = [];

			txt = 'Dołączył';		
		}

		this.morphTabs.activate('room' + id);	

		request = { 'room_id' : id, 'text': txt};
		this.makeRequest(request, null);

		$$('.morphtabs_panel').each(function(el, index){
			el.scrollTop = el.scrollHeight;
		});
	},

	setDialogues: function(txt, id) {
		if(txt == 'logout'){
			document.location.href='/portal/index.php?id=1724';
			return;
		}
		eval('data = (' + txt + ')');
		room_id = id ? id : this.morphTabs.panel.id.replace('room', '');

		down = true;

		$$('.morphtabs_panel').each(function(el, index){
			if(el.scrollTop + el.clientHeight != el.scrollHeight){
				down = false;
			}
		});


		this.morphTabs.titles.each(function(el, index){
			if(el.title == 'room' + room_id){
				html = el.retrieve('panel:html');
			}
		}.bind(this));

		data.each(function(el, index){
			if($defined(this.IDs[room_id])){
				interval = false;
				if(!this.IDs[room_id].some(function(num){return (el.id == num)})) {
					interval = true;
					this.IDs[room_id].push(el.id);
					text = el.text.toString();
					text = text.replace(':P', '<img src="assets/images/chat/icon_razz.gif" border="0" />');
					text = text.replace(':p', '<img src="assets/images/chat/icon_razz.gif" border="0" />');
					text = text.replace(':)', '<img src="assets/images/chat/icon_smile.gif" border="0" />');
					text = text.replace(':(', '<img src="assets/images/chat/icon_sad.gif" border="0" />');
					text = text.replace(':D', '<img src="assets/images/chat/icon_lol.gif" border="0" />');
					text = text.replace(':d', '<img src="assets/images/chat/icon_lol.gif" border="0" />');

					html = html + '<span class="row">' +el.time+ ' <font color="#175FA6"><strong>' +el.user+ ':</strong></font>&nbsp;&nbsp;&nbsp;' +text+ '</span><div class="clear"></div>';
				}
				if(interval && this.morphTabs.panel.id != ('room' + room_id.toString())){
					this.morphTabs.titles.each(function(e, i){
						if($(e).get('title').toString() == ('room' + room_id.toString())){
							e.interval = chat.blink.periodical(500, chat.blink, [e]);
						}
					});
				}	
			}
		}.bind(this));
		
		this.morphTabs.titles.each(function(el, index){
			if(el.title == 'room' + room_id && html != el.retrieve('panel:html')){
				el.store('panel:html', html);
				this.morphTabs.activate(this.morphTabs.activeTitle);
			}
		}.bind(this));

		if(down) {
			$$('.morphtabs_panel').each(function(el, index){
				el.scrollTop = el.scrollHeight;
			});
		}
	},

	intervalRequest: function(){
		chat.IDs.each(function(el, index){
			request = { 'room_id' : index, 'text': ''};
			chat.makeRequest(request, index);
		});
	}.periodical(3000),

	makeRequest: function(request, index) {
		new Request({
			encoding: 'utf-8',   
            	method: 'post',   
            	url: '/portal/index.php?id=1727',   
            	data: request,   
            	onRequest: function() {},   
            	onSuccess: function(response) { chat.setDialogues(response, index) }.bind(this),
            	onFailure: function() {alert('Błąd wczytywania danych!')} 
        	}).send();
	},

	blink: function(el) {
		if($defined(el) && el.interval){
			if(el.get('class') != 'over' && el.get('class') != 'active' && el.get('class') != 'blink'){
				el.set('class', 'blink');
			}
			else if(el.get('class') == 'blink') {
				el.set('class', '');;
			}
		}
	}
});

chat = new Chat();


window.addEvent('domready', function() {
	$$('a.openLink').each(function(el, index){
		el.addEvent('click', function(event){
			event.stop();
			rel = el.get('rel');
			rev = el.get('rev');
			chat.buildRoom(rev, rel);
		});
	});	
});

