//The alternative constructor is Quip(HTMLElement) (for prerender quips)
function Quip(quipcontent, quipid, quipclass) {
	if (arguments.length == 1) { //rendered in Django
		this.quip_html = arguments[0];
		this.quipid = arguments[0].id.slice(4); //because the word "quip" precedes the id
	} else { // create the wrapper for the quip
		this.quipid = quipid;
		dom = YD.create('div',{'id':"quip"+ this.quipid, 'class': quipclass});
		dom.innerHTML = quipcontent;
        
        //open in new tab        
        links = YAHOO.util.Selector.query(".message a", dom)
        for(var i in links) {
            LinksNewTab(links[i]);
        } 
		
        $('quiplist').appendChild(dom);
		this.quip_html = dom;
	}


	//Setup all the events
	if(fluther_disc.user && this.quip_html.className.length <  15) { //second argument ensures it's not been censored by crude check for "censored" being appended.
		var link = $$('great-answer','span',this.quip_html)[0].childNodes[0];	//seleting <a> as firstChild of span... careful
		YE.on(link, 'click', function(e, linkid){
			YE.stopEvent(e);
			YC.asyncRequest('POST', HOST_NAME + '/usefulquip/', {
				success: Bind(function(o){
					var response = eval('(' + o.responseText + ')');
					// update the link and the data
					
					var scoreNode = YD.getElementsByClassName('score', 'span', this.parentNode)[0];
					scoreNode.replaceChild(document.createTextNode(response.quipscore), scoreNode.firstChild);
					this.parentNode.replaceChild(document.createTextNode("Great Answer!"), this);
				},this),
				timeout: 6000
				},
				"id="+linkid
			);
		}, this.quipid); //we pass the linkid to the function as linkid	
	}
	
}


var fluther_disc = {
	//variables
	//discussion_id:0,
	//since: 0,
	//asker: null,
	//user: null,
	//listen_delay: [15000], //milliseconds
	
	//methods
	init: function() {
		fluther_disc.listener = new Updater(fluther_disc.listen_delay, fluther_disc.listen);
		//Tests for updater
		//s = function(a,b){alert(a + " " + b);}
		//p = new Updater(3000, s, "a2","b2");

		YE.on($('answerform'), 'submit', fluther_disc.talk_post);
		
		//Turn on ajax-links only if user is auth... still needb better error msgs
		if (fluther_disc.user){
			YE.on($('followdisc'), 'click', function(e){
				YE.stopEvent(e);
				YC.asyncRequest('POST', HOST_NAME + '/togglebookmark/', {
					success: function(o){
						var response = eval('(' + o.responseText + ')');
						if (response['deletedbookmark_id']){
							$('followdisc').innerHTML = 'Follow this question';
						} else {
							$('followdisc').innerHTML = 'Stop following';
						}
					},
					timeout: 6000
					},
					"id="+fluther_disc.discussion_id
				);
			});
			var link = $('greatlink');
			YE.on(link, 'click', function(e, linkid){
			YE.stopEvent(e);
			YC.asyncRequest('POST', HOST_NAME + '/usefuldisc/', {
				success: function(o){
					var response = eval('(' + o.responseText + ')');
					rp = response;
					$('greatlink').parentNode.innerHTML = "Great Question! (<span class='score'>"+response.discscore+"</span><img width='8' height='8' alt=' points' src='"+MEDIA_URL+"images/v2/star.png' class='trans-png star'/>)";
				},
				timeout: 6000
				},
				"id="+fluther_disc.discussion_id
				);
			}); 
		}
				
		var quiplist = $$("quip", "div", "quiplist");
		for (var i in quiplist) {
			new Quip(quiplist[i]);
		}
		
		//new PreviewHandler('answerarea', 'chat-preview', {
		//	indicator:'talk_ajax_loader',
		//	callback: fluther_disc.openPreview
		//});
        
        /* Make quip links open in new tab */
        //TODO give this a root to make it faster.
        links  = YAHOO.util.Selector.query(".message a");
        for(var i in links) {
            LinksNewTab(links[i]);
        }
        links = YAHOO.util.Selector.query("#description a");
        for(var i in links) {
            LinksNewTab(links[i]);
        } 
	},

	listen: function() {
		var url = HOST_NAME + '/listen/?id='+fluther_disc.discussion_id+"&since="+fluther_disc.since+"&time="+new Date().getTime(); //time is to remove IE get caching
		
		//if composing add another param
		if($('answerarea') && $('answerarea').value != "") {
			url += "&composing=true";
		}
		
		if (!(fluther_disc.curr_listen_req && YC.isCallInProgress(fluther_disc.curr_listen_req)) ) {
			fluther_disc.curr_listen_req = YC.asyncRequest('GET', url, {
				success: fluther_disc.handle_listen,
				timeout: 6000
			});
		}
	},
	talk_post: function(e) {
		YE.stopEvent(e); //hijack submit
		
		fluther_disc.listener.stopUpdater(); //stop listener
		//abort current listens
		if (fluther_disc.curr_listen_req && YC.isCallInProgress(fluther_disc.curr_listen_req)) {
			try {YC.abort(fluther_disc.curr_listen_req);}
			catch(e) {} //Do anything here?
		}
		
		var quip_message = $('answerarea').value;
		
		YD.setStyle("talk_ajax_error","display", "none");
		YD.setStyle("talk_ajax_loader", "display", "");
		$('answer_submit').disabled = true;
		
		//send out talk
		var url = HOST_NAME + '/talk/?ajax';
		YC.asyncRequest('POST', url, {
			success: fluther_disc.handle_talk,
			failure: fluther_disc.handle_talk_failure},
		  	"id="+fluther_disc.discussion_id+
			"&message="+ encodeURIComponent(quip_message) + 
			"&since=" + fluther_disc.since
			);
		
		
	},
	
	handle_talk: function(transport) {
		$('answerarea').value = "";

		var response = fluther_disc.handle_listen(transport);
		
		if ("followed" in response) {
			$('followdisc').innerHTML = 'Stop following';
		}
		
		YD.setStyle("talk_ajax_loader", "display", "none");
		$('answer_submit').disabled = false;
			
		//restart listener
		fluther_disc.listener.startUpdater();		
	},
	
	handle_talk_failure: function(transport) {
		YD.setStyle("talk_ajax_loader", "display", "none");
		$('answer_submit').blur();
		$('answer_submit').disabled = false;
		
		YD.setStyle("talk_ajax_error","display", "");
		
		//restart listener
		fluther_disc.listener.startUpdater();		
	},
	
	handle_listen: function(transport) {
		var response = eval('(' + transport.responseText + ')');
		var quips = response.quips;
		
        if ("quips" in response) {
			fluther_disc.since = response.lastid;
		
			// zebra striping
			var quiplist = YD.getElementsByClassName("quip", "div", "quiplist"); //select only the divs
			if (quiplist.length > 0 && quiplist[quiplist.length-1].className == "quip quip1"){
				 var zebra_classes = ["quip quip2", "quip quip1"];	
			} else {
				 var zebra_classes = ["quip quip1", "quip quip2"];	
			}
			
			//do the building
			for (var i = 0; i < quips.length; i++){
				
				new Quip(quips[i].html, quips[i].id, zebra_classes[i%2]);
		
			}
		}
		
		//build the compose template
		$('composelist').innerHTML = response.compose_html;
		
		//do the status
		$('listeners').innerHTML = response.num_listeners;
		$('composers').innerHTML = response.num_composers;
	
		if (response.num_composers) {
			fluther_disc.listener.resetUpdater();
		}
		
	return response;
	}
};

YE.onDOMReady(fluther_disc.init);
