var ChatApp = function() {
    var firstChannel;
    var onInit = null;
    var daemonTimerId;
    var previewMode = false;
    var initialized = false;
    var currentChat = null;
    
    return {
        init : function() {
        	if (this.initialized) return false;
        	ChatApp.daemonTimeout = 15;
        	ChatApp.guestIdStart = 1000000;
        	
        	channels = new Array();
        	ChatLayout.init();
        	ChannelManager.init();
        	if (this.onInit) this.onInit();
        	this.openFirstChannel();
        	
        	this.loadMessages();
        	
        	window.setTimeout ("ChatApp.pingServer()", 300*1000);
        	
        	ChatApp.myPicSuffix = "";
        	ChatApp.needReloadUserlist = false;
        	this.initialized = true;
        },
        	
        pingServer: function () {
        	var conn = new Ext.data.Connection();
        	conn.request({method : 'POST', url : '/pages/channel/_json.ping.php'}); 
        	window.setTimeout ("ChatApp.pingServer()", 300*1000);
        },
        	
        openFirstChannel: function () {
        	var channel = new ChannelManager.getChannel(this.currentChat.id, this.currentChat.name);
        	channel.authorId = this.currentChat.authorId;
        	channel.moderators = this.currentChat.moderators;
        	channel.supermoders = this.currentChat.supermoders;
					this.firstChannel = channel;
        },
        	
        selectChannel: function(channelId) {
        	this.currentChat = ChannelManager.getChannel(channelId);
        	ChatLayout.chatSelected(this.currentChat);
        },
        	
       	login: function(login, password) {
       		return null;
       	},
       		
       	getCurrentChannel: function() {
       		return ChannelManager.getChannel(this.currentChat.id, this.currentChat.name);
       	},
       		
       	getCurrentChat: function() {
       		return this.currentChat;
       	},

		setCurrentChat: function(current) {
			this.currentChat = current;
		},
       		
       	changeNick: function() {
       		ChatLayout.showChangeNick();
       	},
       		
       	enterWithNick: function (nick) {
       		var conn = new Ext.data.Connection();
					conn.on('requestcomplete', function(trans, response, options) {
						var result = Ext.decode(response.responseText);
						if (result.success) {
							CurrentUser.setNick (result.nick);
							ChatLayout.entered ();
						}
						else {
							ChatApp.showErrors (result.errors);
						}							
					});
					conn.on('requestexception', function() {alert("Ajax error")});
					conn.request({method : 'POST', url : '/pages/channel/_json.set_nick.php', params: {nick: nick, channelId: this.currentChat.id}}); 
       	},
       		
       	enter: function () {
       		if (!CurrentUser.IsTempNick) ChatLayout.entered ();
       	},
       		
       	tryLogin: function (dialog,ccc) {
       		alert(dialog.query("#"));
       	},
       		
       	sendMessage: function (message) {
       		Ext.getDom("putMessageText").value = ChatLayout.getMessageTargetValue() + message;
       		Ext.getDom("putMessageThread").value = this.currentChat.id;
       		Ext.getDom("putMessageForm").action = "http://" + daemonUrl + "/message-put";
       		Ext.getDom("putMessageForm").submit();
       		ChatLayout.messageSended ();
       	},
       		
       	tryClearChat: function() {
       		var conn = new Ext.data.Connection();
					conn.on('requestcomplete', function(trans, response, options) {
						var result = Ext.decode(response.responseText);
						if (result.success)
							location.href = location.href;
						else
							ChatApp.showErrors (result.errors);
					});
					
					conn.on('requestexception', function() {alert("Ajax error")});
					conn.request({method : 'POST', url : '/pages/channel/_json.clear_chat.php', params: {channelId: ChatApp.getCurrentChat().id}});
       	},
       	
       	goToChatSettings: function () {
       		location.href = "/my/chat.html?chatId=" + ChatApp.getCurrentChat().id;
       	},
       		
       	showErrors: function (errors) {
       		var errorsStrs = new Array ();;
       		for (var i = 0; i < errors.length; i++) {
       			if (locStrings["error_" + errors[i].name])
       				errorsStrs.push(locStrings["error_" + errors[i].name]);
       			else
       				errorsStrs.push(errors[i].name);
       		}
       		alert(errorsStrs.join("\n"));
       	},
       		
       	loadMessages: function() {
       		if (ChatApp.previewMode) {
       			channel = this.getCurrentChannel();
       			channel.addUser(0, 3, {"nick":"Admin","gender":"","hidden":"0","city":"","avatar":"","age":"0"});
						channel.addUser(1, 4, {"nick":"Chat Bot","gender":"","hidden":"0","city":"","avatar":"","age":"0"});
       			channel.addMessage(2,3,"Admin","20:15:00","Hello World");
						channel.addMessage(3,4,"Chat Bot","20:15:15","Hello Admin!");
       			return;
       		}
       		if (daemonTimerId != null) window.clearTimeout(daemonTimerId);
       		channelsIds = ChannelManager.getChannelsIds();
       		var cChannel = null;
       		var threadsStr = "";
       		for (i = 0; i < channelsIds.length; i++) {
       			cChannel = ChannelManager.getChannel(channelsIds[i]);
       			threadsStr += cChannel.id + ":" + cChannel.lastMessageId + ";";
       			//alert(cChannel.id);
       		}
       		var url = "http://" + daemonUrl + "/message-get?thread=" + threadsStr + "&timeout=" + ChatApp.daemonTimeout;
       		if (Ext.isIE) url += "&ieHack=1";
       		window.frames["frm2"].location.href = url;
       		daemonTimerId = window.setTimeout("ChatApp.loadMessages()", (ChatApp.daemonTimeout+1)*1000);
       	},
       		
       	doLogout: function() {
       		location.href = "http://" + document.domain + "/logout.html";
       	},
       		
       	banUser: function(channelId, userId) {
       		BanDialog.show(channelId, userId);
       	},
       		
       	setUserModerator: function (channelId, userId, action) {
       		var conn = new Ext.data.Connection();
					conn.on('requestcomplete', function(trans, response, options) {
						var result = Ext.decode(response.responseText);
						if (result.success)
							alert(locStrings["user_moderator_setted"]);
						else
							ChatApp.showErrors (result.errors);
					});
					
					conn.on('requestexception', function() {alert("Ajax error")});
					conn.request({method : 'POST', url : '/pages/channel/_json.set_user_moderator.php', params: {channelId: channelId, userId: userId, action: action}});
       	},
       		
       	accessForbidden: function () {
       		location.href = "http://" + document.realDomain + "/unauth.php";
       	}
	}
}();

//Ext.onReady(ChatApp.init, ChatApp, true);

