//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;
            var 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;
	}

        // Add to user autocompleter
        var user = YAHOO.util.Selector.query(".qspan a", this.quip_html)[0]; // Assuming user is the first link
                                                                             // in the qspans
        fluther_disc.completer.addName(user.childNodes[0].data);

	//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	
	}
	
}


nameAutoCompleter = function(input_field, container, indicator) {
        
        
	//new YAHOO.widget.LogReader('ask');
	var ds = new YAHOO.util.LocalDataSource([]); 
	this.datasource = ds;
	this.indicator_id = indicator;
	this.tag_ac = new YAHOO.widget.AutoComplete(input_field, container, this.datasource, {
		highlightClassName: "selected",
		delimChar: [" ", "\n", "-"]
	});
	this.tag_ac.dataRequestEvent.subscribe(Bind(function(){ YD.setStyle(this.indicator_id,'display','');}, this));
	this.tag_ac.dataReturnEvent.subscribe(Bind(function(){ YD.setStyle(this.indicator_id, 'display', 'none');}, this));
	this.tag_ac.queryDelay = 0;

    this.addName = function(name) {
        var data = this.datasource.liveData;
        formatted_name = '@' + name;

        // See if the name is already in the array, if so, remove it.
        for (var i in data) {
            if (data[i] == formatted_name) {
                data.splice(i, 1);
                break;
            }
        }

        data.unshift(formatted_name);
    };
	
	this.nameexists = function(name) {
        var data = this.datasource.liveData;
		for (var i in data) {
			if (data[i] == name) {
				return true;
			}
		}
		return false;
	};
	
};

var fluther_disc = {
	//TODO: do this first, and better (over-ridden in disc.html)
	//discussion_id:0,
	//since: 0,
	//asker: null,
	//user: null,
	//listen_delay: [15000], //milliseconds 
    completer: new nameAutoCompleter('answerarea', 'name-autocomplete', 'talk_ajax_loader'),
	facebook_broadcast: false,
	facebook_actionlinks: null,
	facebook_attachment: null,
	
	//methods
	init: function() {
		fluther_disc.listener = new Updater(fluther_disc.listen_delay, fluther_disc.listen);

		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]);
		}
		
		var preview = new PreviewHandler('answerarea', 'chat-preview', {
			indicator:'talk_ajax_loader',
			callback: fluther_disc.openPreview
		});

            //    preview.sanitize_params = '&discussion=' + fluther_disc.discussion_id;
			preview.sanitize_params = fluther_disc.get_name_link;
         
        /* 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]);
        }
		
		if (fluther_disc.facebook_broadcast) {
			FB.ensureInit(function() {
				var actionLinks = fluther_disc.facebook_actionlinks;
				var attachment = fluther_disc.facebook_attachment;
				FB.Connect.streamPublish(attachment['name'], attachment, actionLinks, '', '', null, false);
			});	
			//FB.Connect.streamPublish('', null, null, '', '', null, false);
		}
		
	},

	openPreview: function() {
		if ($('quip-slider').style.display == "none") {
			
			// Reset the timer sinxe we're starting to type
			fluther_disc.listener.resetUpdaterAndFire();
			
			var re = new RegExp("^\\W*$");
			if ($('answerarea').value.match(re)) {
				return;
			}
			//$('quip-slider').style.display = '';
			
			//var h = YD.getStyle('quip-preview', "scrollHeight");
			
			YD.setStyle("quip-slider", "height", "133px"); 
			var eff = new YAHOO.widget.Effects.BlindDown('quip-slider'); 
			eff.onEffectComplete.subscribe(function() {
				YD.setStyle("quip-slider", "height", "auto");
			});
			
		}	
	},
	
	get_name_link: function(name) {
		if (fluther_disc.completer.nameexists(name)) {
			return '#';
		}
		return null;
	},
	
	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
		
		// only submit if we have text to submit: bug #241
		if ($('quip-slider').style.display == "none") {
			// Test for non-whitespace is in open preview
			return;
		}
		

		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);
