﻿function GetLocalteMonth(month, lang) {
	var mRu = ['янв', 'фев', 'март', 'апр', 'мая', 'июня', 'июля', 'авг', 'сент', 'окт', 'нояб', 'дек'];
	var mMd = ['янв', 'фев', 'март', 'апр', 'мая', 'июня', 'июля', 'авг', 'сент', 'окт', 'нояб', 'дек'];
	if (lang == 'ru')
		return mRu[month];
	else if (lang == 'md')
		return mMd[month];
}

var HttpRequest = {
	lastrequestId: 1,
	nextrequestId: function() {
		return this.lastrequestId++;
	},
	results: [],
	clearresult: function(resultid) {
		var t = [];
		for(var rid in this.results)
			if(rid != resultid)
				t.push(this.results[rid])
		
		this.results = t;
	},

	Get: function(url,callBack) {
		if (document.createElement && document.getElementsByTagName) {
			var s = document.createElement('script');
			var h = document.getElementsByTagName('head');
			if (s && h.length) {
				var rid = this.nextrequestId();
				url += (((url.indexOf("?")>-1) ? "&" : "?") + "RequestId=" + rid);
				s.src = url;
				s.onload = function() { callBack(HttpRequest.results[rid]); HttpRequest.clearresult(rid); };
				s.onreadystatechange = s.onload;
				h[0].appendChild(s);
			}
		}
	}
}

var CHAT_IS_INIALIZED = false;

var Chat = 
{
	User: null,
	NickName: "My",
	Hash: null,
	Host: "http://forum.md:5333/",
	AvatarsPath: "http://forum.md/Storage.Images/Avatars/30x30/",

	Elements: {
		Contacts:null,
		Dialog:null,
		Chat:null,
		WritePH: null,
		DialogPH: null,
		IFramePH: null,
		Send:null
	},
	
	Actions: {
		Check: function() {
			HttpRequest.Get(Chat.Host+"?Action=Check&User="+Chat.User+"&Hash="+Chat.Hash, function(result) {;
				if(result!=null && result.Count > 0) {
					for(var i in result.PerUser) {
						var Contact = $("#CHAT_CONTACT_"+result.PerUser[i].Key);
						
						$(Chat.Elements.Contacts).prepend(Contact);
						
						if(Contact.length == 0) {
							Contact = Chat.Contacts.Add(result.PerUser[i].Key,result.PerUser[i].Value.NickName,result.PerUser[i].Value.Avatar);
						}
						Contact.addClass("New");
						$(Chat.Elements.Button).addClass("New");
						if(Chat.Elements.Chat.style.display != 'none' && result.PerUser[i].Key == Chat.Actions.CurrentContact && Chat.Messages.User[Chat.Actions.CurrentContact] != null) {
							Chat.Actions.Get(Chat.Actions.CurrentContact);
						}
					}
				}
			});
		},
		Get: function(UserId) {
			HttpRequest.Get(Chat.Host+"?Action=Get&User="+Chat.User+"&Hash="+Chat.Hash+"&From="+UserId, function(result) {
				if(Chat.Messages.User[UserId]!=null) {
					for(var i in result) {
						Chat.Messages.Add(UserId,result[i].From,result[i].Date,result[i].Body,result[i].Author);
					}
				}
				$("#CHAT_CONTACT_"+UserId).removeClass("New");
				if($(Chat.Elements.Chat).find(".New").length == 0) $(Chat.Elements.Button).removeClass("New");
			});
		},
		History: function(UserId) {
			HttpRequest.Get(Chat.Host+"?Action=History&User="+Chat.User+"&Hash="+Chat.Hash+"&With="+UserId, function(result) {
				Chat.Messages.User[UserId] = "";
				for(var i in result) {
					Chat.Messages.Add(UserId,result[i].From,result[i].Date,result[i].Body,result[i].Author);
				}
			});
		},
		CurrentContact : null,
		Contacts: function() {
			HttpRequest.Get(Chat.Host+"?Action=Contacts&User="+Chat.User+"&Hash="+Chat.Hash, function(result) {
				for(var i in result) {
					Chat.Contacts.Add(result[i].UserId,result[i].NickName,result[i].Avatar);
					if(result[i].isOnline) {
						$("#CHAT_CONTACT_"+result[i].UserId).addClass("Online");
					}
				}
				setInterval(Chat.Actions.Check, 2000);
			});
		},
		Send: function(body) {
			if(Chat.Actions.CurrentContact!=null) {
			
			
				$(Chat.Elements.Contacts).prepend($("#CHAT_CONTACT_"+Chat.Actions.CurrentContact));
			
				HttpRequest.Get(Chat.Host+"?Action=Send&User="+Chat.User+"&Hash="+Chat.Hash+"&To="+Chat.Actions.CurrentContact+"&Body="+escape(body), function(result) {
					
				});
				Chat.Messages.Add(Chat.Actions.CurrentContact, Chat.User, "Date("+(new Date()).getTime()+")" ,body, null);
			}
		}
	},
	Contacts: {
		Start: function(UserId, NickName, Avatar) {
			if($("#CHAT_CONTACT_"+UserId).length == 0) {
				this.Add(UserId,NickName,Avatar);
			}
			if($(Chat.Elements.Chat).css("display")=="none") {
				Chat.Toogle();
			}
				
			$("#CHAT_CONTACT_"+UserId).mousedown();
		},
		Add: function(UserId, NickName, Avatar) {
			var container = $("<div></div>")
				.addClass("Item")
				.attr("NickName", NickName)
				.attr("UserId", UserId)
				.attr("id","CHAT_CONTACT_"+UserId)
				.html('<b><u></u><img src="'+Chat.AvatarsPath+((Avatar == null)?"no_image.gif":Avatar)+'" align="top"/><span>'+NickName+'</span><div class="Notification"></div></b>');
				
			$(container).mousedown(Chat.Contacts.Click);
			$(Chat.Elements.Contacts).prepend(container);
			return container;
		},
		Click: function() {
			var self = this;
			if(Chat.Actions.CurrentContact != $(self).attr("UserId")) {
				Chat.Actions.CurrentContact = $(self).attr("UserId");
								
				$(Chat.Elements.Header).html($(self).attr("NickName")+'<a href="javascript:void(0);">'+''+'</a>');
				$(Chat.Elements.Dialog).html("");
				
				if(Chat.Messages.User[Chat.Actions.CurrentContact] != null) {
					if($(self).hasClass("New")) {
						Chat.Actions.Get(Chat.Actions.CurrentContact);
					}
					Chat.Messages.RenderAll(Chat.Actions.CurrentContact);
				} else {
					Chat.Actions.History(Chat.Actions.CurrentContact);
				}
				
				$(".Current").removeClass("Current");
				$(self).addClass("Current");
			}
			return false;
		}
	},
	Messages: {
		User : [],
		Add: function(UserId, From, iDate, Body, Author) {
				if(this.User[UserId]!=null) {
					eval("var date = new "+iDate.replace(/\//g,"")+";");
					var mes = GetLocalteMonth(date.getMonth(), 'ru');
					var FormatedDate = ((date.getDate() < 10) ? "0" + date.getDate() : date.getDate()) + " " + mes + " '" + (date.getFullYear().toString().substr(2)) + ", " + ((date.getHours() < 10) ? "0" + date.getHours() : date.getHours()) + ":" + ((date.getMinutes() < 10) ? "0" + date.getMinutes() : date.getMinutes());
					
					My = From == Chat.User ? true : false;
					var newMessage = '<div class="Message'+(My?" My":"")+'"><div class="From">'+(My?Chat.NickName:Author)+'</div><div class="Date">'+FormatedDate+'</div><div class="Body">'+Body.replace(/\n/g,"<br />")+'</div><div class="Clear"></div></div>';
					this.User[UserId] +=  newMessage;
					
					if(UserId == Chat.Actions.CurrentContact) {
						Chat.Elements.Dialog.innerHTML += newMessage;
						Chat.Elements.Dialog.scrollTop = 100000;
					}
				}
		},
		RenderAll: function(UserId) {
			if(this.User[UserId]) {
				Chat.Elements.Dialog.innerHTML += this.User[UserId];
				Chat.Elements.Dialog.scrollTop = 100000;
			}
		}
	},
	
	Initialize: function(user, hash, nickname) {
		Chat.User = user;
		Chat.Hash = hash;
		Chat.NickName = nickname;
		
		Chat.Elements.Contacts = document.getElementById("CHAT_CONTACTS");
		Chat.Elements.Dialog = document.getElementById("CHAT_DIALOG");
		Chat.Elements.Header = document.getElementById("CHAT_HEADER");
		Chat.Elements.Chat = document.getElementById("CHAT");
		Chat.Elements.WritePH = document.getElementById("CHAT_PH_WRITE");
		Chat.Elements.DialogPH = document.getElementById("CHAT_PH_DIALOG");
		Chat.Elements.TextArea = document.getElementById("CHAT_PH_TEXTAREA");
		Chat.Elements.Area = document.getElementById("CHAT_AREA");
		Chat.Elements.Button = document.getElementById("CHAT_BUTTON");
		Chat.Elements.Send = document.getElementById("CHAT_SEND");
			
		$(Chat.Elements.TextArea).focus(function() {
			if(CHAT_IS_INIALIZED == false) {
				$(Chat.Elements.TextArea).keydown(function(event) {
					if (((event.keyCode == 13) || (event.keyCode == 10)) && (event.ctrlKey == true)) {
						Chat.Send();
					}
				});
				CHAT_IS_INIALIZED = true;
			}
		});
			
		$(Chat.Elements.Send).click(Chat.Send);
		
		this.Actions.Contacts();
	},
	CurrentResize: null,
	Resize: function(ResizeScope) {
		Chat.CurrentResize = ResizeScope;
		return false;
	},
	Send: function() {
		if(Chat.Actions.CurrentContact!=null && $(Chat.Elements.TextArea).val() != "") {
			Chat.Actions.Send($(Chat.Elements.TextArea).val());
			$(Chat.Elements.TextArea).val("");
		}
	},
	Toogle: function() {
		if (Chat.Elements.Chat.style.display == "none") {
			var first = $(Chat.Elements.Contacts).find(":first-child");
			if(first!=null) {
				$("#CHAT_CONTACT_"+$(first).attr("UserId")).mousedown();
			}
			if($("#CHAT_CONTACT_"+Chat.Actions.CurrentContact).hasClass("New"))
				Chat.Actions.Get(Chat.Actions.CurrentContact);
            $(Chat.Elements.Chat).css("display","block")
            $(Chat.Elements.Area).height(Chat.Elements.Chat.offsetHeight + 41);
            Chat.Elements.TextArea.focus();
        } else {
            $(Chat.Elements.Chat).css("display","none")
            $(Chat.Elements.Area).height(31);
        }
	}
}

$(document).mousemove(function(e) {
	if(Chat.CurrentResize!=null) {
		var Y = e.pageY != null ? e.pageY : e.y;
		switch(Chat.CurrentResize) {
			case 1:
				var Height = Y - 31 - document.documentElement.scrollTop;
				if(Height>150) {
					$(Chat.Elements.Area).height(Height + 41);
					Chat.Elements.Chat.style.height = (Height + 8) + "px";
					if( Chat.Elements.WritePH.offsetHeight > (Height - 80)) {
						var resize =  Height - 70;
						Chat.Elements.DialogPH.style.bottom = (resize + 10) + "px";
						Chat.Elements.WritePH.style.height =  (resize - 10) + "px";
					}
				}
				break;
			case 2:
				var Height = Chat.Elements.Chat.offsetHeight;
				var resize = Height - Y + 31 - document.documentElement.scrollTop;
				if((resize>50) && (resize < Height - 80)) {
					Chat.Elements.DialogPH.style.bottom = (resize + 10) + "px";
					Chat.Elements.WritePH.style.height =  (resize - 10) + "px";
				}
				break;
		}
	}
});

$(document).mouseup(function() {
	Chat.CurrentResize = null;
});