/**
 * AjaxDiscussion: 
 * 
 * 	Example: 
 * 
 * 	var chat=new AjaxDiscussion(domContainer, {id:24,server:"discusionServer.php", editable:true, updateInterval:5000});
 * 	chat.getPosts("Append this post after retrieving any previous messages");
 * 
 */



var AjaxDiscussion=new Class({
	currentJob:{priority:0,job:null},
	count:0,
	options:
	{
		editable:false,
		id:0,
		server:"",
		updateInterval:10000, /*10 second update interval*/
		proactive:true, /*poll server on updateInterval*/
		template:null,
		windowTemplate:function(instance){return AjaxDiscussion.DefaultWindowTemplate(instance);},
		postTemplate:function(post, instance){return AjaxDiscussion.DefaultPostTemplate(post,instance);},
		showReply:true,
		invertPosts:false,
		serverOffset:0
	},
	initialize:function(el, options){
		var me=this;
		me.setOptions(options);
		el.appendChild(me.createWindow());
		if(me.options.showReply){el.appendChild(me.createPostbox());}
		if(me.options.last&&me.options.last!=""){
			me.time=me.options.last;
		}
		
		me.addJob(me.getPosts(),3);
			
	if(me.options.proactive)
		me.status=runLater(function(){
			if(!me.options.proactive)
				return true; //effectively cancels further execution.
			if(me.tryCancel(1))
				me.addJob(me.getPosts(),1);
			return false;
		},me.options.updateInterval);
	
	},
	beActive:function(){
		var me=this;
		me.options.proactive=true;
		if(!me.status.isRunning){
			me.status=runLater(function(){
				if(!me.options.proactive)
					return true; //effectively cancels further execution.
				if(me.tryCancel(1))
					me.addJob(me.getPosts(),1);
				return false;
			},me.options.updateInterval);
			
		}
	},
	bePassive:function(){
		var me=this;
		me.options.proactive=false;
	},
	createWindow:function()
	{
		var me=this;
		var container=me.options.windowTemplate(me);
		me.window=container.window;
		return container.root; 
	},
	createPostbox:function()
	{
		var me=this;
		me.post=new Element('div',{styles:{width:"400px",height:"100px"}, 'class':"mediaMap_Input"});

		if(BrowserDetect.browser=="Explorer")
		{
			var tbl=$(document.createElement('table'));
			var tr=$(tbl.insertRow());
			var lft=$(tr.insertCell());
			var rght=$(tr.insertCell());
			
		}else{
			var tbl=new Element('table');
			var tr=new Element('tr');
			var lft=new Element('td');
			var rght=new Element('td');
			tbl.appendChild(tr);
			tr.appendChild(lft);
			tr.appendChild(rght);
			
		}
		tbl.addClass("mediaMap_InputTable");
		lft.addClass("mediaMap_InputLeft");
		rght.addClass("mediaMap_InputRight");
		
		var txt=new Element('textarea',{rows:"4", cols:"38",'class':"mediaMap_InputText"});
		lft.appendChild(txt);
		me.post.appendChild(tbl);

		var messageBox=new TextAreaMessage(txt,{message:"click here to enter a new message.\nclick the comment bubble to send."});
		var img=new Element('div',{
			'class':"mediaMap_InputSubmit",
			title:"Submit :: click here to submit your message",
			styles:
			{
			cursor:"pointer"
			},
			events:{
				click:function(){
				var priority=2;
				if(messageBox.verify()&&me.tryCancel(priority)){
					
					me.addJob(me.getPosts(txt.value),priority);
					messageBox.el.value='';
					//messageBox.onBlur(messageBox);
				}
			}
			}
		});
		new mediaTips(img);
		rght.appendChild(img);
		return me.post;
	},
	addPost:function(item){
		var me=this;
		me.count++;
		var post=me.options.postTemplate(item, me);
		if(me.options.invertPosts){
			post.injectTop(me.window);
		}else{
			me.window.appendChild(post);
		}
			if(item.time){
			me.time=item.time;
			}
	},


	getPosts:function(text){
		var me=this;	
		var job=new DiscussionPostRequest(me,text);
		job.addEvent('onSuccess',function(response){
			$each(response.posts,function(post){
				me.addPost(post); //should automatically add to window using template
			});
			if(response.posts.length>0){me.fireEvent("onAddedPosts");}
		});
		mm_debug(["Geolive Discussion. Executing Post request",{me:me, serverQuery:job, reply:(text||false)}]);
		return job.execute();

	},
	addJob:function(job, priority){
		var me=this;
		me.currentJob.job=job;
		me.currentJob.priority=priority;
		job.addEvent('onComplete',function(){
			me.currentJob.job=null;
			me.currentJob.priority=0;
		});
	},
	tryCancel:function(priority)
	{
		var me=this;
		return (!me.currentJob.job||(me.currentJob.priority<priority&&me.cancelJob()));
	},
	cancelJob:function(){
		var me=this;
		var job=me.currentJob.job;
		if(job)
		{
			job.cancel();
			me.currentJob.job=null;
		}
		me.currentJob.priority=0;
		return true;
	}



});

AjaxDiscussion.implement(new Options(),new Events());

//default post and container, templates.
AjaxDiscussion.DefaultPostTemplate=function(item, discussion){
	var binary=discussion.window.childNodes.length%2==0?"even":"odd";
	var postEl=new Element('div',{'class':"mediaMapPost mediaMapPost_"+binary, styles:{opacity:"0"}});	
	
	if(BrowserDetect.browser=="Explorer")
	{
		var tbl=$(document.createElement('table'));
		var tr=$(tbl.insertRow());
		var left=$(tr.insertCell());
		var right=$(tr.insertCell());
	}else{
		var tbl=new Element('table');
		var tr=new Element('tr');
		var left=new Element('td');
		var right=new Element('td');
		tbl.appendChild(tr);
		tr.appendChild(left);
		tr.appendChild(right);
	}
	
	
	tbl.addClass("mediaMapPost_table");
	left.addClass("mediaMapPostLeft");
	left.addClass("mediaMapPostLeft_"+binary);
	right.addClass("mediaMapPostRight");
	right.addClass("mediaMapPostRight_"+binary);

	
	postEl.appendChild(tbl);
	var avatar='/administrator/components/com_mediamapserver/Viewer/images/hello.png';
	if(item.details&&item.details.avatar&&item.details.avatar!=""){
		avatar=item.details.avatar;
	}
	var profile=false;
	if(item.details&&item.details.profile&&item.details.profile!=""){
		profile=item.details.profile;
		var a=new Element('a', {href:profile, style:"display:block;"});
		a.appendChild(new Element('img',{'class':"mediaMapPostImage", src:avatar}));
		left.appendChild(a);
		
	}else{
	left.appendChild(new Element('img',{'class':"mediaMapPostImage", src:avatar}));
	}

	if(discussion.options.editable)
	{
		var edit=new Element('td',{'class':"mediaMapPost_Edit"});
		tbl.appendChild(edit);
	}
	var txt=new Element('div',{'class':"mediaMapPost_Text"});
	right.appendChild(txt);

	item.username=(item.details&&item.details.username?item.details.username:"guest");
	var user=new Element('div',{'class':"mediaMapPost_User"});
	user.innerHTML=item.username;
	user.addClass("mediaMapPost_User"+"_"+item.username);
	right.appendChild(user);

	if(item.rating)
	{
		//item.rating="";
		var rate=new Element('div',{'class':"mediaMapPost_Rate"});
		rate.innerHTML=item.rating;
		right.appendChild(rate);
	}
	if(item.time)
	{
		var time=new Element('div',{'class':"mediaMapPost_Time"});
		time.innerHTML=MapFactory.CalculateRelativeTime(item.time,discussion.options.serverOffset);
		right.appendChild(time);

	}
	if(discussion.options.editable)
	{
		var del=new Element('div',{'class':"mediaMapPost_Delete"});
		del.innerHTML='remove';
		right.appendChild(del);
		del.addEvent('click',function(){
			var deletePost=new DeletePostRequest(discussion, item.id);
			deletePost.addEvent('onSuccess',function(result){
				if(result.success==true){
				postEl.setStyle('display','none');
				}else{alert("Error:"+result.msg);}
			});
			deletePost.addEvent('onFailure',function(){
				alert("Error deleting post");
				
			});
			deletePost.execute();
			
		});

	}

	if(item.uid&&parseInt(item.uid)>0){
		var textSpan=new Element('span');
		textSpan.innerHTML=item.text;
		txt.appendChild(textSpan);
	}else{
	txt.appendChild(document.createTextNode(item.text));
	}
	
	if(parseInt(item.visible||1)==0){
		postEl.addClass('hidden');
		
	}
	new Fx.Style(postEl, 'opacity', {duration:250}).start(0,1);
	return postEl;
};
AjaxDiscussion.DefaultWindowTemplate=function(discussion){
	var window=new Element('div',{ 
		'class':"mediaMap_Wall"
			});
	window.setStyle('height','250px');
	window.setStyle('width','300px');
	return {root:window, 'window':window}; //return the root element and post window (same in this template)
	
	
};


