/*
JUITTER 1.0.0 - 22/07/2009 - http://juitter.com
BY RODRIGO FANTE - http://rodrigofante.com

** jQuery 1.2.* or higher required

Juitter is distributed under the MIT License
Read more about the MIT License --> http://www.opensource.org/licenses/mit-license.php

This script is just a beta test version, download and use it at your own risk.
The Juitter developer shall have no responsability for data loss or damage of any kind by using this script.
*/
(function($) {

    var counter = 1;
    var instances = {};

    function Juitter(opts) {
        this.id = counter++;
        instances[this.id] = this;
        this.start(opts);
    }
    // create object contructor
    Juitter.prototype = {
        numMSG: 5, // set the number of messages to be show
        contDiv: "juitterContainer", // //Set a place holder DIV which will receive the list of tweets example <div id="juitterContainer"></div>   
        loadMSG: "Loading messages...", // Loading message, if you want to show an image, fill it with "image/gif" and go to the next variable to set which image you want to use on 
        imgName: "loader.gif", // Loading image, to enable it, go to the loadMSG var above and change it to "image/gif"
        readMore: "", // read more message to be show after the tweet content
        showAvatar: true, // insert "image" to show avatar of "text" to show the name of the user that sent the tweet 
        updateInterval: 60, //optional, disabled by default, the number after "live-" indicates the time in seconds to wait before request the Twitter API for updates, I do not recommend to use less than 60 seconds.

        // some global vars
        aURL: "",
        msgNb: 1,
        mode: "",
        param: "",
        time: "",
        lang: "",
        gifName: "",
        ultID: "",
        filterWords: "",
        running: false,
        id: 0,
        // Twitter API Urls: constant members.
        apifMultipleUSER: "http://search.twitter.com/search.json?from%3A",
        apifUSER: "http://search.twitter.com/search.json?q=from%3A",
        apitMultipleUSER: "http://search.twitter.com/search.json?to%3A",
        apitUSER: "http://search.twitter.com/search.json?q=to%3A",
        apiSEARCH: "http://search.twitter.com/search.json?q=",

        // object functions.
        registerVar: function(opt) {
            this.searchType = opt.searchType;
            this.searchObject = opt.searchObject;
            this.lang = opt.lang || this.lang;
            this.contDiv = opt.placeHolder || this.contDiv;
            this.loadMSG = opt.loadMSG || this.loadMSG;
            this.imgName = opt.imgName || this.imgName;
            this.numMSG = opt.total || this.numMSG;
            this.readMore = opt.readMore || this.readMore;
            this.showAvatar = opt.showAvatar || this.showAvatar;
            this.filterWords = opt.filterWords;
            this.openExternalLinks = opt.openExternalLinks ? "target='_blank'" : "";

        },

        start: function(opt) {
            ultID = 0;
            this.registerVar(opt);
            if ($("#" + this.placeHolder)) {
                // show the load message
                this.loading();
                // create the URL  to be request at the Twitter API
                this.aURL = this.createURL();
                // query the twitter API and create the tweets list
                this.conectaTwitter(1);
                // if live mode is enabled, schedule the next twitter API query
                this.startUpdateTimer();
            }
        },

        loading: function() {
            if (this.loadMSG == "image/gif") {
                $("<img></img>")
					.attr('src', this.gifName)
					.appendTo("#" + this.contDiv);
            } else $("#" + this.contDiv).html(this.loadMSG);
        },

        createURL: function() {
            var url = "";
            //debugger;
            var jlg = this.lang.length > 0 ? "&lang=" + this.lang : "";
            var seachMult = this.searchObject.search(/,/);
            if (seachMult > 0) this.searchObject = "&ors=" + this.searchObject.replace(/,/g, "+");
            if (this.searchType == "fromUser" && seachMult <= 0) url = this.apifUSER + this.searchObject;
            else if (this.searchType == "fromUser" && seachMult >= 0) url = this.apifMultipleUSER + this.searchObject;
            else if (this.searchType == "toUser" && seachMult <= 0) url = this.apitUSER + this.searchObject;
            else if (this.searchType == "toUser" && seachMult >= 0) url = this.apitMultipleUSER + this.searchObject;
            else if (this.searchType == "searchWord") url = this.apiSEARCH + this.searchObject + jlg;
            url += "&rpp=" + this.numMSG;
            return url;
        },

        conectaTwitter: function(e) {
            // query the twitter api and create the tweets list
            var self = this;
            var container = $("#" + self.contDiv);
            $.ajax({
                url: this.aURL,
                type: 'GET',
                dataType: 'jsonp',
                timeout: 1000,
                error: function() { $("#" + self.contDiv).html("fail#"); },
                success: function(json) {

                    if (json.results.length == 0)
                        return;

                    $("#" + self.contDiv).html("");

                    var $ul = $("<ul></ul>");
                    $ul.attr('id', 'twittList' + self.id)
						.attr('class', 'twittList')
						.prependTo(container);

                    $.each(json.results, function(i, item) {

                        if (item.text != "undefined") {
                            var link = "http://twitter.com/" + item.from_user + "/status/" + item.id;
                            var tweet = self.filter(item.text);
                            var mHTML;
                            if (self.showAvatar == true) {// build html and store in array, by comma separating each element. 
                                //when u join the array at then end it generates one long string...code looks neater. 
                                mHTML = [
                                        "<div style='float:left' id='liPlaceholder'>",
                                            "<div id='divTwitterImage' style='float:left;width:24px;'>",
                                                "<a href='http://www.twitter.com/", item.from_user, "' ", self.openExternalLinks, ">",
                                                    "<img src='", item.profile_image_url, "' alt='", item.from_user, "' class='juitterAvatar' />",
                                                "</a>",
                                             "</div>",
                                             "<div style='float:left' id='blurb'>", self.textFormat(tweet.substring(0, 120)),
                                                "<a href='", link, "' class='JRM' ", self.openExternalLinks, ">", self.readMore,
                                                "</a>",
                                              "</div>",
                                         "</div>"
                                     ].join("");
                            }
                            else {
                                mHTML = [
                                        "<a href='http://www.twitter.com/", item.from_user, "' ", self.openExternalLinks, ">@", item.from_user, ":",
                                        "</a> ",
                                        "<span id='blurb'>", self.textFormat(tweet.substring(0, 120)),
                                            "<a href='", link, "' ", self.openExternalLinks, ">", self.readMore,
                                            "</a>",
                                         "</span>"
                                    ].join("");
                            }
                            $("<li></li>")
									.html(mHTML)
									.attr('id', 'twittLI' + self.msgNb)
									.attr('class', 'twittLI')
									.css('background-image', 'none')
									.appendTo($ul);


                            // remove old entries                               
                            self.msgNb++;
                        }

                    });
                    // hide twitterPlaceHolder if juitterAPI returns no match.
                    if (json.results.length == 0) {
                        $(container).hide();
                    }
                    else {
                        $(container).show();
                    }

                }
            });
        },

        filter: function(s) {
            if (this.filterWords) {
                var searchWords = this.filterWords.split(",");
                var cleanHTML = s;
                if (searchWords.length > 0) {
                    $.each(searchWords, function(i, item) {
                        var sW = item.split("->").length > 0 ? item.split("->")[0] : item;
                        var rW = item.split("->").length > 0 ? item.split("->")[1] : "";
                        var regExp = eval('/' + sW + '/gi');
                        cleanHTML = cleanHTML.replace(regExp, rW);
                    });
                }
                return cleanHTML;
            } else return s;
        },

        textFormat: function(texto) {
            //make links
            var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
            texto = texto.replace(exp, "<a href='$1' class='extLink' " + this.openExternalLinks + ">$1</a>");
            exp = /[\@]+([A-Za-z0-9-_]+)/ig;
            texto = texto.replace(exp, "<a href='http://twitter.com/$1' class='profileLink' target='_blank'>@$1</a>");
            exp = /[\#]+([A-Za-z0-9-_]+)/ig;
            texto = texto.replace(exp, "<a href='http://juitter.com/#$1' target='_blank' onclick='$.Juitter.start({searchType:\"searchWord\",searchObject:\"$1\"});return false;' class='hashLink'>#$1</a>");
            // make it bold
            if (this.searchType == "searchWord") {
                var tempParam = this.param.replace(/&ors=/, "");
                var arrParam = tempParam.split("+");
                $.each(arrParam, function(i, item) {
                    var regExp = eval('/' + item + '/gi');
                    var newString = (' <b>' + item + '</b> ');
                    texto = texto.replace(regExp, newString);
                });
            }
            return texto;
        },

        startUpdateTimer: function() {
            // live mode timer
            //debugger;
            this.timer = setInterval("jQuery.Juitter.update(" + this.id + ")", this.updateInterval * 1000);
        }
    };

    /*Useage: $.Juitter(options)*/
    $.Juitter = function(opts) { return new Juitter(opts); };

    $.Juitter.update = function(instanceId) {
        // console.log("test" + instanceId);
        instances[instanceId].conectaTwitter(2);
    };

})(jQuery);
