// vim: tabstop=4 softtabstop=4 shiftwidth=4 noexpandtab nowrap
ChatLayout = function() {
	var layout;
	var showUsers;
	var loginDialog;
	var loginBtn;
	var linksBtn;
	var registerBtn;
	var registerDialog;
	var myAccountBtn;
	var logoutBtn;
	var myAccountDlg;
	var logoutBtn;
	var memberBtn;
	var innerLayout;
	var isFullscreen = false;
	var oldValues = new Array ();
	var messageTarget = new Array ();

	return {
		init : function() {
			var loadingBlock = document.getElementById("loading-block");
			if (loadingBlock) {
				loadingBlock.parentNode.removeChild(loadingBlock);
			}
			myLayout = Ext.get ("chat-layout");
			if (ChatLayout.isFullscreen) myLayout = document.body;
			
			var usersSize =ChatLayout.showUsers ? 200 : 1;
			
			layout = new Ext.BorderLayout(myLayout, {
				north: {initialSize: 28, titlebar: false},
				east: {split: true, titlebar: false, title: "Users", initialSize: usersSize, autoScroll: true},
				center: {titlebar: false}
			});
			
			this.innerLayout = new Ext.BorderLayout('inner-layout', {
				south: {initialSize: 70, titlebar: false, split: true, title: "Your menu"},
				center: { autoScroll:true, closeOnTab: true }
			});
			
			var currentChat = ChatApp.getCurrentChat();
			var showAdv = (currentChat.id - 1+10000000000);
			var height = currentChat.id == 16389 ? 320 : 130;
		
			if (showAdv) {
				this.usersLayout = new Ext.BorderLayout ("users-layout", {
					south: {initialSize: height, titlebar: false, split: false},
					center: { autoScroll:true, closeOnTab: true}
				});
			} else {
				this.usersLayout = new Ext.BorderLayout ("users-layout", {
					center: { autoScroll:true, closeOnTab: true}
				});
			}
			
			this.innerLayout.beginUpdate ();
			this.innerLayout.add('south', new Ext.ContentPanel('user-message-panel', {closable: false}));
			//innerLayout.add('center', new Ext.ContentPanel('chat-panel', {title: 'Chat', closable: true}));
			this.innerLayout.endUpdate ();
			
			this.usersLayout.beginUpdate ();
			this.usersLayout.add('center', new Ext.ContentPanel('users-list', {closable: false}));
			if (showAdv) this.usersLayout.add('south', new Ext.ContentPanel('adv-block'));
			this.usersLayout.endUpdate ();
			
			//if (showAdv)
				//document.getElementById("adv-block").innerHTML = '<iframe scrolling="no" src="http://partner.gameboss.ru/ep/?elm_out_rows=1&elm_max_text_size=100&qu-type=1%2C2%2C3%2C4&elm_out_cols=1&qu-style=3&elm_text_align=justify&type_out=0&affiliate_id=37548" width="100%" height="130" frameborder="0" marginwidth=0 marginheight=0></iframe>';

			layout.beginUpdate();
			layout.add ('north', new Ext.ContentPanel ('title-panel', {closable: false}));
			layout.add('center', new Ext.NestedLayoutPanel(this.innerLayout));
			//layout.add ('east', new Ext.ContentPanel ('users-list', {closable: false}));
			layout.add ('east', new Ext.NestedLayoutPanel(this.usersLayout));
			layout.endUpdate();
			
			enterBtn = new Ext.Button('enter-btn', {text: locStrings["enter_btn"], handler: ChatLayout.tryEnterNick});
			smilesBtn = new Ext.Button('smiles-btn', {text: ":-)", menuAlign: 'bl-tl', menu: this.getSmilesPanel()});
			sendBtn = new Ext.Button('send-btn', {text: locStrings["send_btn"], handler: ChatLayout.trySendMessage});
			
			/*var viewMenu = new Ext.menu.Menu({
				id: 'mainMenu',
				items: [
					{text: locStrings["menu_fullscreen"], handler: ChatLayout.onFullscreenClick}
					//,{text: 'Change Direction', handler: ChatLayout.onItemClick}
			]
			});*/
			
			var chatMenuItems = null;
			if (ChatApp.getCurrentChat().authorId == 22364)	{
				chatMenuItems = [
					{text: locStrings["menu_get_chat"], handler: ChatLayout.onItemClick, handler: ChatLayout.showGetChat},
					{text: locStrings["menu_become_member"], handler: ChatRelation.becomeMember},
					{text: locStrings["menu_create_chat"], handler: ChatLayout.onItemClick, handler: ChatLayout.showCreateChat}/*,
					"-",
					{text: locStrings["menu_moderator_request"], handler: ChatRelation.moderatorRequest}*/
				];
			} else {
				chatMenuItems = [
					{text: locStrings["menu_get_chat"], handler: ChatLayout.onItemClick, handler: ChatLayout.showGetChat},
					{text: locStrings["menu_become_member"], handler: ChatRelation.becomeMember},
					{text: locStrings["menu_create_chat"], handler: ChatLayout.onItemClick, handler: ChatLayout.showCreateChat}
				];
			}

			var chatMenu = new Ext.menu.Menu({
				id: 'mainMenu', items: chatMenuItems        
			});
			ChatLayout.chatMenu = chatMenu;
			
			var toolbar = new Ext.Toolbar('toolbar', null, {align: "right"});

			toolbar.addItem (new Ext.Toolbar.TextItem(ChatApp.getCurrentChat().name));
			toolbar.addFill ();
			
			/*vk*/
			if (ChatApp.getCurrentChat().authorId == 22364 || ChatApp.getCurrentChat().authorId == 666) {
				ChatLayout.GroupVk = toolbar.addButton({icon: '/_common/cimg/icons/vk.png', cls: 'x-btn-text-icon', text: locStrings["vk"], handler: ChatLayout.onItemClick, handler: ChatLayout.showGroupVk});
			}

			if (ChatApp.getCurrentChat().authorId == 438248) {
				ChatLayout.GroupRVk = toolbar.addButton({icon: '/_common/cimg/icons/vk.png', cls: 'x-btn-text-icon', text: locStrings["vk"], handler: ChatLayout.onItemClick, handler: ChatLayout.showGroupRVk});
			}

			if (ChatApp.getCurrentChat().id == 167452) {
				ChatLayout.GroupWotradioVk = toolbar.addButton({icon: '/_common/cimg/icons/vk.png', cls: 'x-btn-text-icon', text: locStrings["vk"], handler: ChatLayout.onItemClick, handler: ChatLayout.showGroupWotradioVk});
			}

			if (ChatApp.getCurrentChat().id == 222334)  {
				ChatLayout.Chatiumbiz = toolbar.addButton({icon: 'http://chatium.biz/favicon.ico', cls: 'x-btn-text-icon', text:"Блог о Chatium", handler: ChatLayout.onItemClick, handler: ChatLayout.showChatiumbiz});
			}

			if (ChatApp.getCurrentChat().authorId == 438364) {
				ChatLayout.GroupGoodFMVk = toolbar.addButton({icon: '/_common/cimg/icons/vk.png', cls: 'x-btn-text-icon', text: locStrings["vk"], handler: ChatLayout.onItemClick, handler: ChatLayout.showGroupGoodFMVk});
			}
			
			if (ChatApp.getCurrentChat().id == 165600 || ChatApp.getCurrentChat().id == 164326 || ChatApp.getCurrentChat().id == 164393) {
				ChatLayout.GroupGoodApofigVk = toolbar.addButton({icon: '/_common/cimg/icons/vk.png', cls: 'x-btn-text-icon', text: locStrings["vk"], handler: ChatLayout.onItemClick, handler: ChatLayout.showGroupGoodApofigVk});

			}
			/*end vk*/

			if (ChatApp.getCurrentChat().id != 155707) {
				ChatLayout.linksBtn = toolbar.addButton({icon: '/_common/cimg/icons/add.png', cls: 'x-btn-text-icon', text: locStrings["menu_links"], handler: ChatLayout.onItemClick, handler: ChatLayout.showAddLink});
			}
			

			if (ChatLayout.isFullscreen && !ChatLayout.windowSize) {
				toolbar.add({icon: '/_common/cimg/icons/application.gif', cls: 'x-btn-text-icon', text: locStrings["menu_fullscreen_off"], handler: ChatLayout.onFullscreenClick});
			} else {
				toolbar.add({icon: '/_common/cimg/icons/application.gif', cls: 'x-btn-text-icon', text: locStrings["menu_fullscreen"], handler: ChatLayout.onFullscreenClick});
			}
			if (ChatApp.getCurrentChat().id != 155707) {
				toolbar.add({icon: '/_common/cimg/icons/items.gif', cls: 'x-btn-text-icon', text: locStrings["menu_chat"], menu: chatMenu});
			} else {
				ChatLayout.chatMenu.add = toolbar.addButton({icon: '/_common/cimg/icons/items.gif', cls: 'x-btn-text-icon', text: locStrings.menu_chat_clear, handler: ChatApp.tryClearChat});
			}
			toolbar.add("-");
			ChatLayout.loginBtn = toolbar.addButton({icon: '/_common/cimg/icons/key.gif', cls: 'x-btn-text-icon', text: locStrings["menu_login"], handler: LoginDialog.show});
			ChatLayout.registerBtn = toolbar.addButton({cls: 'x-btn-text', text: locStrings["menu_register"], handler: RegisterDialog.show});
			ChatLayout.myAccountBtn = toolbar.addButton({icon: '/_common/cimg/icons/user.gif', cls: 'x-btn-text-icon', text: locStrings["menu_my_account"], handler: MyAccountDialog.show});
			ChatLayout.logoutBtn = toolbar.addButton({cls: 'x-btn-text', text: locStrings["menu_logout"], handler: ChatApp.doLogout});
			ChatLayout.myAccountBtn.hide ();
			ChatLayout.logoutBtn.hide ();
			
			ChatLayout.messageTarget = new Array ();
		},
		
		onAfterAppInitialized: function() {
			if (ChatApp.getCurrentChat().authorId == CurrentUser.Id) {
				ChatLayout.chatMenu.add("-");
				/*ChatLayout.chatMenu.add({text: locStrings.menu_chat_settings, handler: ChatApp.goToChatSettings});*/
				ChatLayout.chatMenu.add({text: locStrings.menu_chat_clear, handler: ChatApp.tryClearChat});
				ChatLayout.chatMenu.add({text: locStrings.faq, handler: ChatLayout.showfaq});
			}
		},
		
		tryEnterNick: function () {
			nick = Ext.getDom("user-nick").value;
			if (nick == yourNickMessage) {
				alert (locStrings["error_empty_nick"]);
				return false; 
			}
			ChatApp.enterWithNick(nick);
		},
		
		trySendMessage: function () {
			message = Ext.getDom("messageText").value;
			
			var now = new Date ();
			if (ChatLayout.lastSendTimestamp && Math.round((now-ChatLayout.lastSendTimestamp)/1000) < 4) {
				alert(locStrings["message_time_limit"].replace("%d", 4));
				return false;
			}
			ChatLayout.lastSendTimestamp = now;
			
			ChatApp.sendMessage(message);
		},
		
		messageSended: function () {
			Ext.getDom("messageText").value = "";
			this.canReplaceTarget = true;
		},
		
		onFullscreenClick: function (item) {
			if (ChatLayout.isFullscreen && !ChatLayout.windowSize)
				window.parent.location.href = document.referer;
			else
				window.parent.location.href = ChatApp.FullscreenLink;
		},
		
		onItemClick: function(item){
			alert(item);
			//Ext.example.msg('Menu Click', 'You clicked the "{0}" menu item.', item.text);
		},
		
		showChangeNick: function () {
			var userEnterBlock = Ext.get("user-enter-block");
			userEnterBlock.show ();
			Ext.get("user-enter-block").dom.style.height = "27px";
			
			var userMessageBlock = Ext.getDom("user-message-block");
			userMessageBlock.style.display = "none";
			document.getElementById("user-nick").value = CurrentUser.Nick;
			document.getElementById("user-nick").focus ();
		},
			
		entered: function () {
			if (!CurrentUser.IsTempNick) {
				var userEnterBlock = Ext.get("user-enter-block");
				//userEnterBlock.setVisibilityMode (Ext.Element.DISPLAY);
				userEnterBlock.hide ();

				Ext.get("user-enter-block").dom.style.height = "1px";
				
				document.getElementById("user-nick-block").innerHTML = htmlspecialchars(CurrentUser.Nick);
				
				var userMessageBlock = Ext.getDom("user-message-block");
				userMessageBlock.style.display = "block";
				
				//userMessageBlock.setVisibilityMode (Ext.Element.DISPLAY);
				//userMessageBlock.show ();
				try {
					document.getElementById("messageText").focus();
				} catch (ex) {
				}
			}
			
			if (CurrentUser.IsRegistred) {
				ChatLayout.loginBtn.hide ();
				ChatLayout.registerBtn.hide ();
				ChatLayout.myAccountBtn.show ();
				ChatLayout.logoutBtn.show ();
				ChatApp.loadMessages ();
			}
		},
			
		changeScreenMode: function () {
			var fullDiv = document.createElement("div");
			fullDiv.className = "full-div";
			//document.body.appendChild(fullDiv);
			
			myLayout = Ext.get ("chat-layout");
			var st = myLayout.dom.style;
			
			if (!isFullscreen) {
				//myLayout.anchorTo(document.body, "top");
				myLayout.dom.style.position = "absolute";
				oldValues.width = st.width;
				st.width = document.body.clientWidth + "px";
				st.left = "0px";
				st.top = "0px";
				st.height = document.body.clientHeight + "px";
				oldValues.width = st.height;
				isFullscreen = true;
			} else {
				chatWrapper = Ext.get("chat-wrapper");
				//myLayout.anchorTo(chatWrapper.dom);
				st.position = "static";
				st.width = oldValues.width;
				st.height = oldValues.height;
				st.top = "50px";
				isFullscreen = false;
			}
		},
		
		chatSelected: function(channel) {
			this.currentChat = channel; // UNISED
		},
		
		addMessageTarget: function (user) {
			//Ext.getDom("message-target-view").innerHTML = userNick;
			//Ext.getDom("message-target").value = userNick;
			//Ext.getDom("messageText").value = "[to:" + userId + ":" + userNick + "], " + Ext.getDom("messageText").value;
			//Ext.getDom("messageText").focus ();
			
			if (this.canReplaceTarget) {
				this.messageTarget = new Array ();
				this.canReplaceTarget = false; 				
			}
			
			for (var i = 0; i < this.messageTarget.length; i++) {
				if (ChatLayout.messageTarget[i].id == user.id)
					return;
			}
			if (this.messageTarget.length > 4) {
				alert("Вы не можете добавить более 5 получателей");
				return;
			}
			
			ChatLayout.messageTarget.push (user);
			
			this.showMessageTarget ();
		},
			
		delMessageTarget: function (userId) {
			var newMessageTarget = new Array ();
			for (var i = 0; i < this.messageTarget.length; i++) {
				if (ChatLayout.messageTarget[i].id != userId)
					newMessageTarget.push(ChatLayout.messageTarget[i]);
			}
			this.messageTarget = newMessageTarget;
			this.showMessageTarget (); 			
		},
		
		showMessageTarget: function  () {
			var res = "&gt; " ;
			if (this.messageTarget.length == 0)
				res += locStrings["to_all"];
			else {
				var resStrs = new Array ();
				for (var i = 0; i < this.messageTarget.length; i++) {
					var user = ChatLayout.messageTarget[i];
					resStrs.push("<a class='" + user.gender + "' href='javascript:void(0)' onClick='ChatLayout.delMessageTarget(" + user.id + ")'>" + user.nick + "</a>");
				}
				res = resStrs.join(", ");
			}				
			
			Ext.getDom("messageTarget").innerHTML = res;
			document.getElementById("messageText").focus();
		},
		
		getMessageTargetValue: function () {
			if (this.messageTarget.length == 0)
				return "";
			var res = "";
			var resStrs = new Array ();
			for (var i = 0; i < this.messageTarget.length; i++) {
				var user = this.messageTarget[i];
				resStrs.push("[to:" + user.id + ":" + htmlentities(user.nick) + "]");
			}
			res = resStrs.join("");
			return res;
		},
			
		getSmilesPanel: function () {
			var panel = new Ext.ux.SmilesMenu({});
			panel.on("select", function(menu, smile) {
				ChatLayout.addSmile (smile);
			});
			return panel;
		},
			
		addSmile: function (smile) {
			Ext.getDom("messageText").value = Ext.getDom("messageText").value + "!" + smile + "! ";
			Ext.getDom("messageText").focus ();
		},
			
		getUserMenu: function () {
			if (!this.userMenu)
				this.userMenu = new Ext.ux.UserMenu({});
			return this.userMenu;;
		},
			
		userClicked: function (link, userId) {
			menu = this.getUserMenu();
			menu.show(link);
			menu.selectUser (ChatApp.getCurrentChannel().getUser(userId));
			//ChatLayout.setMessageTarget(" + message.userId + ",\"" + message.userNick + "\");' 
		},
		
		userNickClicked: function (link, userId) {
			var user = ChatApp.getCurrentChannel().getUser(userId);
			ChatLayout.addMessageTarget(user);
		},
			
		showGetChat: function() {
			window.open(ChatApp.MainUrl + "chat/builtin?chatId=" + ChatApp.getCurrentChat().id, "test");
		},
		showAddLink: function() {
			window.open(ChatApp.MainUrl + "chat/share?chatId=" + ChatApp.getCurrentChat().id, "test");
		},
		showGroupVk: function() {
			window.open("http://vkontakte.ru/chatium", "123");
		},
		showCreateChat: function() {
			window.open("http://chatium.com/ru/chat/create.html", "");
		},
		showGroupRVk: function() {
			window.open("http://vkontakte.ru/club19616059", "");
		},
		showGroupGoodFMVk: function() {
			window.open("http://vkontakte.ru/club14237582", "");
		},
		showGroupGoodApofigVk: function() {
			window.open("http://vkontakte.ru/club23456551", "");
		},
		
		showGroupWotradioVk: function() {
			window.open("http://vkontakte.ru/club19306907", "")
		},

		showChatiumbiz: function() {
			window.open("http://chatium.biz", "")
		},

		showfaq: function() {
			window.open("http://chatium.com/info/faq.html", "")
		}
	};
}();

function htmlspecialchars(html) {
	html = html.replace(/&/g, "&amp;");
	html = html.replace(/</g, "&lt;");
	html = html.replace(/>/g, "&gt;");
	html = html.replace(/"/g, "&quot;");
	return html;
}

function htmlentities(html) {
	html = html.replace(/&amp;/g, "&");
	html = html.replace(/&lt;/g, "<");
	html = html.replace(/&gt;/g, ">");
	html = html.replace(/&quot;/g, "\"");

	return html;
}

