ChatLayout = function(){
  var layout;
  var showUsers;
  var loginDialog;
  var loginBtn;
  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 showAdv =  (currentChat.id == 1728 || currentChat.id == 216 || currentChat.id == 23 || currentChat.id == 5601 || currentChat.id == 16389);
			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_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}
	    	];
	    }
    	
    	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 ();
			
			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});
				
			toolbar.add({icon: '/_common/cimg/icons/items.gif', cls: 'x-btn-text-icon', text: locStrings["menu_chat"], menu: chatMenu});
			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});
    	}    	
 		},
 			
 		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) {
			
 		},
 			
 		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");
 		}
	};
}();

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;
}