(function($) {
    jQuery.fn.tweet = function(o) {
        var s = {
            aacct: [""],
            qacct: [""],
            count: 3,
            loading_text: null,
            cats: [""],
            page: 1,
            phrase: "",
            threshold: "",
            category: ""
        };
        jQuery.fn.extend({
            cleanTags: function() {
                var returning = [];
                var regex_meme = /([\#]+([^0-9]\w*)(?=[ ]+([^\#]+)))/gi;
                var regex_tag = /([\@]+([A-Za-z0-9-_]+))|([\#]+(\w*))/gi;
                //remove explicit tags
                this.each(function() {
                    returning.push(this.replace(regex_meme, '$2').replace(regex_tag, ""));
                });
                return jQuery(returning);
            }
        });

        if (o) jQuery.extend(s, o);
        return this.each(function() {
            var returnText = '';
            var qa = "";
            if (jQuery("#questions-answers").length == 0) {
                qa = jQuery(this).append('<div id="questions-answers"></div>');
            } else {
                qa = jQuery("#questions-answers");
            }
            if (typeof(s.aacct) == "string") {
                s.aacct = [s.aacct];
            }
            if (typeof(s.qacct) == "string") {
                s.qacct = [s.qacct];
            }
            var query = 'q=from:' + s.aacct;
            jQuery.each(s.cats,
            function(i, item) {
                if (item != '') {
                    query += '%20%23' + item + (i < s.cats.length - 1 ? '%20OR': '');
                }
            });
            if (s.phrase != "") {
                query += '&phrase=' + s.phrase;
            }
            query += "&page=" + s.page;
            var url = 'http://search.twitter.com/search.json?&' + query + (s.threshold == "" ? '': '&since_id=' + s.threshold) + '&rpp=' + s.count + '&callback=?';
            jQuery.ajax({
					type:"GET",
					"url":url,
					dataType:"jsonp", 
					success:function(data){success1(data,s)}
				} 
			);
		});
    };
})(jQuery);

function success1(data,s){
	jQuery("#loading-animated").hide();
	jQuery("#loading-static").show();
    if (data.results.length < s.count && s.threshold == "") {
        jQuery("#more").hide();
		jQuery("#all").show();
    } else if (s.threshold==""){
        setTimeout('jQuery("#more").fadeIn("slow")', 2000);
    }
    if (data.results.length == 0) {
        if (s.phrase != "") {
            var out = '<div id="asked">';
            out += '<div id="response">No answers containing the search terms were found.</div>';
            out += '<div id="q-repeat">' + s.phrase + '</div>';
            out += '</div>';
            jQuery("#tweets").prepend(out);
            jQuery("#asked").fadeIn("slow");
        }
        document.jsAPI.microAnswers(0, "No_topic");
    } else {
        document.jsAPI.microAnswers(s.page, "No_topic");
        jQuery.each(data.results,
        function(i, item) {
            if (item.id > s.threshold) {
                var who = [item.to_user];
                var qid = item.text.match(/[\#]+([0-9]+)/gi);
                if (qid != null) {
                    qid = qid[0].substring(1);
                    var cat = item.text.match(/[\#]+([a-zA-Z]+)/gi);
                    if (cat != null) {
                        cat = cat[0].substring(1);
                    }

                    var timestamp = (new Date() - new Date(item.created_at)) / (1000 * 60);
                    var original_timestamp = item.created_at;
                    if (timestamp < 60) {
                        round = Math.round(timestamp);
                        timestamp = +round + ' minute' + (round > 1 ? 's': '') + ' ago';
                    } else if (timestamp < 1440) {
                        round = Math.round(timestamp / 60);
                        timestamp = round + ' hour' + (round > 1 ? 's': '') + ' ago';
                    } else if (timestamp < 10080) {
                        round = Math.round(timestamp / 1440);
                        timestamp = round + ' day' + (round > 1 ? 's': '') + ' ago';
                    } else if (timestamp < 70560) {
                        round = Math.round(timestamp / 10080);
                        timestamp = round + ' week' + (round > 1 ? 's': '') + ' ago';
                    } else {
                        round = Math.round(timestamp / 40320);
                        timestamp = Math.round(timestamp / 40320) + ' week' + (round > 1 ? 's': '') + ' ago';
                        timestamp = round + 'month' + (round > 1 ? 's': '') + ' ago';
                    }
                    var answer = jQuery([item.text]).cleanTags()[0];
                    var answerid = item.id;
                    var block = '';

                    //find question
                    var question = '';
                    var answerDate = new Date(item.created_at);
                    if (answerDate.getTime() + 86400000 > new Date().getTime()) {
                        until = "";
                    } else {
                        until = dateFormat(answerDate.getTime() + 86400000, "yyyy-mm-dd");
                    }
                    query = 'q=from:' + (item.to_user == null ? s.qacct: item.to_user) + ' to:' + s.aacct + (until == "" ? "": '&until=' + until);

                    url = 'http://search.twitter.com/search.json?&' + query + '&rpp=' + 40 + '&callback=?';
                        jQuery.getJSON(url,
                        function(data) {
                            jQuery.each(data.results,
                            function(i, item) {
                                if ((item.id + '').substring(10 - qid.length) == qid) {
                                    var ordinal = (jQuery('.qa').length % 2 == 0 ? 'odd': 'even');
                                    question = jQuery([item.text]).cleanTags()[0];
                                    block += '<div class="qa ' + (cat == null ? '': cat) + " " +ordinal + '" id="a_' + answerid + '">';
                                    block += '<div class="qa-content qa-content' + ordinal + '">';
                                    block += '<div class="timestamp">' + timestamp + (who != '' ? ' - Asked by <a href="'+(who!="EVQuestions" ? 'http://twitter.com/'+who :'#')+'" target="_blank"><span class="highlight">@' + who + '</span></a>': '') + '</div>';
                                    block += '<p class="question"><span class="highlight">Q:</span>' + question + '</p>';
                                    block += '<p class="answer"><span class="highlight">A:</span>' + answer + '</p>';
                                    block += '</div>';
                                    block += '<div class="qa-meta qa-meta' + ordinal + '">';
                                    block += '<ul>';
                                    block += '<li class="tag">' + (cat != null ? 'More about <a href="javascript:document.jsAPI.filterChanged(\''+cat+'\')"><span class="highlight">' + cat: '') + '</span></a></li>';
                                    block += '</ul>';
                                    block += '</div>';
                                    block += '</div>';
                                    if (jQuery('#a_' + answerid).length == 0) {
                                        if (s.threshold == "") {
                                            jQuery('#questions-answers').append(block);
                                        } else {
                                            jQuery('#questions-answers').prepend(block);
                                        }
                                        jQuery('#a_' + answerid).fadeIn("slow");
                                        
                                    }
                                    return false;
                                }
                            });
                        });
                }
            }
        });
    }
}

function tweetThis(q, cat) {
	if (q != "" && q!="Sending question, please wait..."){
    	jQuery('#question_text').addClass("sending");
	    var myurl = 'async/post.jsp';
	    jQuery.ajax({
	        url: myurl,
	        type: "POST",
	        data: "q=" + q + "&cat=" + cat,
	        success: function() {
	            jQuery("#asked").remove();
	            var out = '<div id="asked">';
	            out += '<div id="response">Thank you for submitting your question</div>';
	            out += '<div id="q-repeat">We read all submitted questions and post as many answers as we can. In the meantime, try searching answered questions - it\'s possible someone has made a similar query.</div>';
	            out += '</div>';
	            jQuery("#tweets").prepend(out);
	            jQuery("#question_text").val("");
	            jQuery("#question_text").removeClass("sending");
	            jQuery('#asked').fadeIn("slow");
	        }
	    });
		document.jsAPI.questionSubmitted();
	}
}