var actionCB = {
	'login': function(data){
		xn.reloadPage();
	},
	'logout': function(data){
		xn.goPage('/');
	},
	'register': function(data){
		xn.goPage('/profile');
	},
	'chatMessages': function(data){
		pageChat.onUpdate(data);
	},
	'feedbackPost': function(data){
		xn.toggle('fbBlock');
		xn.toggle('fbOkMsg');
	},
	'forumPost': function(data){
		if(data.topic_id){
			document.location.href = '/forum/topic/' + data.topic_id + '_1';
		}else{
			document.location.reload();
		}
	},
};

var XN = new Class({
	indicatorId: 'processing',
	indicatorEl: null,
	errorsId: 'errors',
	errorsEl: null,
	filter: null,
	
	initialize: function(){
		window.addEvent('domready',this.init.bind(this));
		this.filter = new Filter();
		this.ui = new UI();
	},
	
	init: function(){
		this.indicatorEl = $(this.indicatorId);
		this.errorsEl = $(this.errorsId);
	},
	
	actionCallBack: function(data){
		// disabling process indicator
		this.indicatorEl.setStyle('display', 'none');

		data = JSON.decode(data);
		for(var action in data){
			var el = data[action];
			var actionName = action;
			// checking for errors
			if($defined(el.err) && el.err.length > 0){
				var errOwner = actionName;
				//var errBlock = new Element('div', {'html': errOwner + ' says:<br>' + el.err.join('<br>')});
				var errBlock = new Element('div', {'html': 'Ошибки:<br>' + el.err.join('<br>')});
				this.errorsEl.empty();
				errBlock.inject(this.errorsEl);
				this.showErr();
			}else{
				// checking for action CB handler
				if(actionCB[actionName]){
					var callBack = actionCB[actionName];
					callBack(el);
				}
			}
		}
	},
	
	showErr: function(){
		this.errorsEl.setStyle('display', '');
		setTimeout(this.hideErr.bind(this), 4000);
	},
	
	hideErr: function(){
		this.errorsEl.setStyle('display', 'none');
	},
	
	doAction: function(actionData){
		new Request({
			url:'/',
			data: JSON.encode(actionData),
			method: 'post',
			headers: {'X-Request': 'JSON'},
			onComplete: this.actionCallBack.bind(this)}
		).send();
		// enabling process indicator
		this.indicatorEl.setStyle('display', '');
		return false;
	},
	
	doFormAction: function(f){
		var formData = this.getFormData(f);
		
		if(formData.action){
			var action = formData.action;
			var data = {};
			data[action] = formData;
			return xn.doAction(data);
		}else{
			return false;
		}
	},

	getFormData: function(f) {
//fixme: exclude buttons from form data
		f = $(f);
		var out = {};
		var formInputs;
		formInputs = f.getElementsByTagName("input");
		for (var i = 0; i < formInputs.length; i++){
			if(formInputs[i].type == 'submit') { continue; }
			if(!formInputs[i].name){ continue; }
			if(formInputs[i].type == 'checkbox'){
				out[formInputs.item(i).name] = formInputs[i].checked;
			}else{
				out[formInputs.item(i).name] = formInputs.item(i).value;
			}
		}
		formInputs = f.getElementsByTagName("textarea");
		for (var i = 0; i < formInputs.length; i++){
			out[formInputs.item(i).name] = formInputs.item(i).value;
		}
		formInputs = f.getElementsByTagName("select");
		for (var i = 0; i < formInputs.length; i++){
			out[formInputs.item(i).name] = formInputs.item(i).value;
		}
		return out;
	},
	
	reloadPage: function(){
//		if(window.onbeforeunload == null){
			window.location.reload();
//		}
	},
	
	goPage: function(href){
//		if(window.onbeforeunload == null){
			window.location.href = href;
//		}
	},
	
	toggle: function(el){
		el = $(el);
		if(el.getStyle('display') == 'none'){
			el.setStyle('display', '');
		}else{
			el.setStyle('display', 'none');
		}
	},
	
	showPostForm: function(){
		$('postForm').setStyle('display', '');
		return false;
	},
	
	hidePostForm: function(){
		$('postForm').setStyle('display', 'none');
		return false;
	}
	
});

var TabSet = new Class({
	panes: [],
	currentTab: "",
	
	add: function(tabId){
		if(this.currentTab == ""){
			this.show(tabId);
		}else{
			$(tabId).setStyle('display', 'none');
		}
	},
	
	show: function(tabId){
		if(this.currentTab == tabId){
			return false;
		}
		
		var btnEl = $(tabId + 'Btn');
		if(btnEl){
			btnEl.addClass('selected');
		}
		
		if(this.currentTab != ""){
			var currentBtnEl = $(this.currentTab + 'Btn');
			if(currentBtnEl){
				currentBtnEl.removeClass('selected');
			}
			
			$(this.currentTab).setStyle('display', 'none');
		}
		$(tabId).setStyle('display', '');
		
		this.currentTab = tabId;
		return false;
	}
});

Filter = new Class({
	filterBase: '/filter/',
	
	initialize: function(){
	},
	
	go: function(){
		var fString = $('searchString').value;
		if(fString != null && fString != ''){
			window.location.href = this.filterBase + 'title_0_' + encodeURIComponent(fString);
		}
		return false;
	}
});

UI = new Class({
	show: function(el){
		$(el).setStyle('display', '');
	}
});

// todo: full rewrite with Class();
Pager = new function(){
	this.showExt = function(pager){
		var offset = $(pager).offset();
		$(pager).css('border', '2px solid #ddd');
		$('#pagerExt').css('left', offset.left+200).css('top', offset.top).fadeIn('fast');
	}
	
	this.scroll = function(direction, pager){
		switch(direction){
			case 'back':
				Pager.firstPage -= 5;
				if(Pager.firstPage < 1){
					Pager.firstPage = 1;
				}
				break;
			case 'forward':
				Pager.firstPage += 5;
				if((Pager.firstPage + 5) > Pager.totalPages){
					Pager.firstPage = Pager.totalPages - 5 + 1;
				}
				break;
		}

		var str = '';
		for(var i = 0; i < 5; i++){
			if((Pager.firstPage + i) == Pager.currentPage){
				str += '<span style="padding: 3px; background: #888; color: #fff;">'+(Pager.firstPage+i)+'</span> ';
			}else{
				str += '<a href="/mail/'+(Pager.firstPage+i)+'">'+(Pager.firstPage+i)+'</a> ';
			}
		}

		$('#pagerExt > span').empty(str);
		$('#pagerExt > span').append(str);
	}
}


var Preview = new Class({
	panes: [],
	previewId: '',
	
	initialize: function(previewId){
		this.previewId = previewId;
		window.addEvent('domready', this.init.bind(this));
	},

	init: function(){
		var images = $$('img.' + this.previewId);
		images.each(function(item, index){
			item.addEvent('mouseover', this.onMouseOver.bind(this, item));
		}, this);
			
	},

	onMouseOver: function(item){
		var imgPath = item.src.replace(/small\//, '');
		var paneEl = $('pane_' + this.previewId);
		if(paneEl){
			paneEl.src = imgPath;
		}
	}

});

var Chat = new Class({
	timer: null,
	delay: 20000,
	chatBodyId: 'chatBody',
	chatBodyEl: null,
	lastMsgId: null,
	
	initialize: function(){
		window.addEvent('domready',this.init.bind(this));
	},
	
	init: function(){
		this.chatBodyEl = $(this.chatBodyId);
		this.update();
	},
	
	say: function(userId){
		if(this.timer != null){
			clearTimeout(this.timer);
			this.timer = null;
		}
		$('lastMsgId').value = this.lastMsgId;
		xn.doFormAction('chatSay');
		//xn.doAction({chatSay: {action: 'chatSay', userId: userId, lastMsgId: this.lastMsgId, body: $('chatMsgBody').value}});
		$('chatMsgBody').value = '';
	},
	
	onUpdate: function(data){
		for(var i = 0; i < data.length; i++){
			var el = data[i];
			new Element('p', {id: 'msg' + el.id, text: el.body}).inject(this.chatBodyEl);
			this.lastMsgId = el.id;
		}
		$(this.chatBodyId).scrollTop = 10300;
		this.timer = setTimeout(this.update.bind(this), this.delay);
	},
	
	update: function(){
		if(this.timer != null){
			clearTimeout(this.timer);
			this.timer = null;
		}
		xn.doAction({chatUpdate: {action: 'chatUpdate', lastMsgId: this.lastMsgId, userId: $('userId').value}});
	}
	
});


var Docs = new Class({
	deleteFile: function(pId){
		if(confirm('Удалить файл?')){
			xn.doAction({docsDeleteFile: {id: pId}});
		}
	},
	
	renameFile: function(pId, oldTitle){
		var newTitle = prompt('Введите новое имя:', oldTitle);
		if(newTitle != oldTitle && newTitle != null){
			xn.doAction({docsRenameFile: {id: pId, title: newTitle}})
		}
	},
	
	publishFile: function(pId, published){
		var msg = 'Разрешить общий доступ к файлу?';
		if(published){
			msg = 'Отменить общий доступ?';
		}
		if(confirm(msg)){
			xn.doAction({docsPublishFile: {id: pId, published: published}});
		}
	},
	
	acceptFile: function(pId, cmd){
		if(cmd){
			xn.doAction({docsAcceptFile: {id: pId, cmd: 1}});
		}else{
			if(confirm('Подтверждение отклонения')){
				xn.doAction({docsAcceptFile: {id: pId, cmd: 0}});
			}
		}
	},

	setAsSpot: function(pId, spotId){
//		if(confirm('Использовать в качестве аватарки?')){
			xn.doAction({docsSetAsSpot: {id: pId, spot_id: spotId}});
//		}
	},

	setAsProfile: function(pId){
		if(confirm('Использовать в качестве аватарки?')){
			xn.doAction({docsSetAsProfile: {id: pId}});
		}
	}
});

var docsCB = {
	'docsAddFile': function(data){
		docsUploadOk(data.localId);
	},
	'docsDeleteFile': function(data){
		xn.reloadPage();
	},
	'docsRenameFile': function(data){
		xn.reloadPage();
	},
	'docsSetAsProfile': function(data){
		xn.reloadPage();
	},
	'docsSetAsSpot': function(data){
		xn.reloadPage();
	},
	'docsPublishFile': function(data){
		xn.reloadPage();
	},
	'docsAcceptFile': function(data){
		xn.reloadPage();
	}
};

for(var el in docsCB){
	actionCB[el] = docsCB[el];
}


// start
//window.addEvent('load', function(){ xn = new XN(); });
var xn = new XN();
