
var Messages = Class.create();
Messages.prototype = {
	main : null,
	
	msgMaxLimit : 100,
	msgAmount : 20,
	msgType : "all",
	fetchArg : null,
	
	msgOffset : 0,
	msgPageCnt : 0,
	
	lastMessageDate : 0,
	
	firstRender : false,
	
	reportMsgID : null,
	reportMsgStatus : null,
	
	fooMode : false,
	
	uniqueMsgCnt : 0,
	
	initialize : function(main){
		this.main = main;
		 $("msg").value = includes["info_txt"];
		 
		//var back = $("msg_back");
		//back.toggle();
				
		// window.setTimeout("main.messages.foo()",10);
	},
	
	foo : function(){
		var back = $("msg_back");
		back.toggle();
		
		if (this.fooMode == false){
			this.fooMode = true;
			window.setTimeout("main.messages.foo()",10);
		} else {
		
		}
	},
	
	sendMessage : function(){
		var msg = $("msg").value;
		
		var status_id = $("status_id").value;
		var str = "status=" + status_id + "&msg=" + escape(includes["banner"]);
		if (status_id != null && status_id != 0){
			str += status_names[status_id] + ": ";
		}
		str += msg;
		
		//alert("send=" + str);
		
		
		new Ajax.Request('app/post.php', 
			{
				method:'post', 
				postBody:str,

			    onSuccess: function(transport){
					var response = transport.responseText || "no response text";
			      
					if (response == "err"){
					} else {
						//this.main.setUserStatus();
					}
			    }.bind(this),
			    onFailure: function(){ 
				//	alert('Something went wrong...') 
				}
			}
		);
		
		
		var nick = $("logged_user").firstChild.nodeValue;
		
		this.toggleMsgField(false);
		
		
		var d = new Date();
		var day = d.getDate();
		var month = d.getMonth()+1;
		var hours = d.getHours();
		if (hours < 10){
			hours = "0" + hours;
		}
		
		var mins = d.getMinutes();
		if (mins < 10){
			mins = "0" + mins;
		}
		var secs = d.getSeconds();
		if (secs < 10){
			secs = "0" + secs;
		}
		
		var dateStr = d.getFullYear() + "-" + month + "-" + day + " " + hours + ":" + mins + ":" + secs;
		
		
		this.drawMessage(true, nick, $("avatar_pic").src, msg, "", "", status_id, dateStr, -1);
	},
	goBack : function(){
		this.getMessages('all', false);
	},
	toggleBack : function(mode, arg, back_status_id){
		var back = $("msg_back");
		var post = $("msgform");
		if (mode == true){
			back.show();
			post.hide();
			
			if (main.getNick() != ""){
				$("login_top").hide();
			}
		} else {
			back.hide();
			post.show();
			$("login_top").show();
		}
		if (arguments[1]){
			$("msg_back_name").childNodes[0].nodeValue = arg + ":";
			$("msg_back_name").className =  "s_" + back_status_id;
		}
	},
	getMessagesByOwnStatus : function(){
		this.getMessages("status", false, this.main.getStatus());
	},
	getMessagesByOwnNick : function(){
		this.getMessages("user", false, this.main.getNick());
	},
	getMessages : function(type, fetchMore){
		/*
		if ( (type != this.msgType && type != "updated") || ( (this.msgType == "user" || this.msgType == "status") && arguments[2] != this.fetchArg) ){
		*/
		//alert("je=" + $("message_list").childNodes.length);
		// alert("fir="  + this.firstRender);
		
		
		if (!fetchMore){
			$("hilited_holder").hide();
		}
		if (this.firstRender == true){
			if (type != "updated" && fetchMore == false){
				this.clearMessages();
			}
		}
			
		this.msgType = type;
		if (arguments[2]){
			this.fetchArg = arguments[2];
		} else {
			this.fetchArg = null;
		}
		
		var back_name = null;
		var back_status_id = 0;
		
		var str = "?startOffset=" + this.msgOffset + "&amount=" + this.msgAmount;
		if (type == "user"){
			back_name = this.fetchArg;
			str += "&type=user&user=" + this.fetchArg;
		} else if (type == "status"){
			back_name = status_group_names[this.fetchArg];
			back_status_id = this.fetchArg;
			str += "&type=status&status=" + this.fetchArg;
		} else if (type == "updated"){
			str += "&type=updated&lastDate=" + this.lastMessageDate;
		} else {
			str += "&type=all";
		}
		
		this.toggleBack(type != "all", back_name, back_status_id);
		
		new Ajax.Request('app/getMessages.php' + str, 
			{
				method:'post', 
				//postBody:str,
				
				onSuccess: function(transport){
				  var response = transport.responseText || "no response text";
					if (response == "err"){
					} else {
						/*
						if (type == "updated"){
							this.main.feedPoller.start();
						}*/
						
						var j = response.evalJSON();
						if (fetchMore == true){
							j.reverse(true);
						}
						this.insertMessages(j, !fetchMore);
					}
			    }.bind(this)
			}
		);
	},
	toggleMsgField : function(mode){
		var color = mode? "#000000" : "#666666";
		$("msg").style.color = color;
		if (mode == true){
		//if (mode == true && $("msg").value == includes["info_txt"]){
			$("msg").value = "";
		}
		
	},
	msgFieldKeyEvent : function(e){
		/*
		var characterCode;
		if(e && e.which){ //if which property of event object is supported (NN4)
			e = e
			characterCode = e.which //character code is contained in NN4's which property
		} else{
			e = event
			characterCode = e.keyCode //character code is contained in IE's keyCode property
		}

		if(characterCode == 13){ //if generated character code is equal to ascii 13 (if enter key)
			alert("return");
			var txt = $("msg").value;
			$("msg").value = txt.substr(0, txt.length-2);
			e = null;
			//document.forms[0].submit() //submit the form
			return true
		} else {
			return true
		}
		*/
	},
	
	lastMsgContent : "",
	
	insertMessages : function(data, insertAtTop){
		this.lastMessageDate = data[0].published;
		
		var link = $("fetch_more_" + (this.msgPageCnt-1));
		
		if (link){
			link.style.display = "none";
		} 
		
		var s = "";
		var cnt = data.length;
		
		
		//var uniqueMsgCnt = 0;
		//var lastMsgContent = "";
		for (var i=cnt-1; i>=0; i--){
			//alert("msg=" + data[i].title);
			if (data[i].title != this.lastMsgContent){
				this.drawMessage(insertAtTop, data[i].nick, data[i].avatar, data[i].title, data[i].link, data[i].description, data[i].status_id, data[i].published, data[i].id  );
				this.lastMsgContent = data[i].title;
				this.uniqueMsgCnt++;
			}
		}
		
		
		// fetch more...
		if (cnt == this.msgAmount){
			s = this.main.getInclude("separator", [this.msgPageCnt]);
			new Insertion.Bottom($("message_list"), s);
		}
		$("hilited_holder").show();
	
		
		// fetch more if invalid messages parzsed away
		//alert("uniqueMsgCnt=" + this.uniqueMsgCnt );
		
		if (this.uniqueMsgCnt < this.msgAmount){
			this.fetchMore();
		} else {
			this.uniqueMsgCnt = 0;
			this.lastMsgContent = "";
		}

	
	},
	drawMessage : function (insertAtTop, nick, avatar, title, link, description, status_id, published, id){
		//alert("drawMessage=" + arguments);
	
		
		this.firstRender = true;
		title = this.cutBanner(title);
		
		//2007-08-03 10:33:55
		var date = published.split(" ");
		var first = date[0].split("-");
		var after = date[1].split(":");
		
		var day = first[2];
		if (day.substr(0,1) == 0){
			day = day.substr(1);
		}
		var month = first[1];
		if (month.substr(0,1) == 0){
			month= month.substr(1);
		}
		var dateStr = day + "." + month + "." + first[0] + " " + after[0] + ":" + after[1];
		
		var data = [nick, avatar, nick, title, description, link, status_id, status_names[status_id], dateStr, id, (status_names[status_id])];
		var s = this.main.getInclude("message", data);
		
		if (status_id > 0){
			if (title.substring(0,1) == " "){
				title = title.substring(1);
			}
			this.main.topFlash.showBubbles([nick, title, avatar, status_id	]);			
		}
		//window.setTimeout("fnHide2(" + oToHide.id + ")", 3000);		
		//this.main.topFlash.showBubbles([" + nick + "," + title + "," + avatar + "," + status_id + "]);", 2000);
		
		
		if (!insertAtTop){
			new Insertion.Bottom($("message_list"), s);
		} else {
			new Insertion.Top($("message_list"), s);
		}
		
		if (id == null){
			// own message
		}
	},
	
	cutBanner : function(s){
		s = Try.these(
			function() {
				for (var i=1; i<status_names.length; i++){
					pos = s.indexOf(status_names[i]);
					if (pos != -1){
						s = s.substr(pos+status_names[i].length+2, s.length);
						return s;
						break;
					}
				}
				return s;
			},
			function() {return s;}
		);
		return s;
	},
	
	fetchMore : function(){
		this.msgOffset += this.msgAmount;
		this.getMessages(this.msgType, true, this.fetchArg);
		this.msgPageCnt++;
	},
	
	clearMessages : function(){
		//alert("clear");
		this.msgOffset = 0;
		this.msgPageCnt = 0;

		msgHolder = $("message_list");
		msgHolder.innerHTML = "";
		
		this.main.topFlash.reset();
	},
	
	msgFieldE : function(){
		var f = $("msg");
		var infoF = $("msgCnt");
		
		if (f.value.length > this.msgMaxLimit) {
			f.value = f.value.substring(0, this.msgMaxLimit);
		} else {
		}
	},
	
	reportMsg : function(id, sender, msg, status_name){
		this.reportMsgID = id;
		this.reportMsgStatus = status_name;
		this.reportMsgTxt = msg;
		this.reportMsgSender = sender;
		
		
		var objLink = document.createElement('a');
		var url = "rookinurkka_report_msg.php?msg=" + this.reportMsgTxt + "&status=" + this.reportMsgStatus + "&sender=" + this.reportMsgSender;

		objLink.setAttribute('href',url);
		
		this.main.lightBoxWin = new lightbox(objLink);
		this.main.lightBoxWin.activate();
	},
	sendReportMsg : function(mode){
		this.main.closePopup();
		
		if (this.reportMsgID != -1){
			var str = "id=" + this.reportMsgID + "&status_name=" + escape(this.reportMsgStatus) + "&sender_name=" + escape(this.main.getNick());
			new Ajax.Request('app/report_msg.php?' + str, {
				method:'post', 

				onSuccess: function(transport){
					var response = transport.responseText || "no response text";
					if (response == "err"){
					} else {
					}
				}.bind(this),
					onFailure: function(){ 
					}
				}
			);
		}
	}

}




