(function ($) {
    var twitterMsgNumber = 0;
    var lastItemId = -1;
    var apiSearchUrl = 'http://search.twitter.com/search.json?callback=?&q=';
    var apiUserTimelineUrl = 'http://api.twitter.com/1/statuses/user_timeline.json?callback=?&screen_name=';

    SearchTwitter = function (container, options) {
        var $url = options.url;
        if (lastItemId > -1) {
            $url = $url + '&since_id=' + lastItemId;
        }

        $.getJSON($url, function (data) {
            if (options.mode == 'timeline') {
                CreateWidget(data, options, container);
            }
            else {
                CreateWidget(data.results, options, container);
            }
        });
    };

    RemoveTweets = function (container, maxTweets) {
        if (twitterMsgNumber >= maxTweets) {
            container.children('.twitterblock').each(
				function (i, item) {
				    if (i >= maxTweets) {
				        $(this).hide();
				        $(this).remove();
				    };
				}
			);
        };
    };

    CreateWidget = function (items, options, container) {
        items = items.sort(function mycomparator(a, b) { return parseInt(a.id) - parseInt(b.id); });
        var setLastBlock = options.tweets > 1;

        if (items.length > 0) {
            container.parent().parent().show();
            $.each(items, function (i, item) {
                if (item.id != lastItemId) {
                    var $tweet = $('<div class="twitterblock"/>').attr('id', 'tweet' + item.id);

                    if (options.mode == 'timeline' && options.showRetweetTextOnly && item.retweeted_status != 'undefined') {
                        $tweet.html(FormatTweet($('<h2/>').html(item.retweeted_status.text)));
                    }
                    else {
                        $tweet.html(FormatTweet($('<h2/>').html(item.text)));
                    }

                    var $decoded = htmlDecode(item.source);
                    if (options.showDate) {
                        var $time = $('<span class="date serif"/>').html(new Date(item.created_at).format(options.dateFormat) + (options.showApp ? ' via ' + $decoded : ''));
                        $time.appendTo($tweet);
                    }

                    if (options.animate) {
                        $tweet.hide();
                    }

                    $tweet.prependTo(container);

                    if ($('.twitterblock').parents('.main_column').length == 0) 
                        Cufon.replace('#tweet' + item.id + ' h2');

                    if (options.animate) {
                        $tweet.slideDown('slow');
                    }

                    RemoveTweets(container, options.tweets);
                    if (setLastBlock) {
                        container.children('.twitterblock').last().addClass('twitterblock_last');
                    }
                    twitterMsgNumber++;

                    lastItemId = parseInt(item.id);
                }
            });
        }
    };

    CreateGuid = function () {
        var result, i, j;
        result = '';
        for (j = 0; j < 32; j++) {
            i = Math.floor(Math.random() * 16).toString(16);
            result = result + i;
        }
        return result
    };

    FormatTweet = function (tweet) {
        tweet.html(tweet.html().replace(/http:\/\/\S+/g, '<a href="$&" target="_blank">$&</a>'));
        tweet.html(tweet.html().replace(/\s?(@)(\w+)/g, ' @<a onclick="javascript:pageTracker._trackPageview(\'/outgoing/twitter.com/\');" href="http://twitter.com/$2" target="_blank">$2</a>'));
        tweet.html(tweet.html().replace(/\s?(#)(\w+)/g, ' <a onclick="javascript:pageTracker._trackPageview(\'/outgoing/search.twitter.com/search?q=%23\');" href="http://search.twitter.com/search?q=%23$2" target="_blank">#$2</a>'));
        return tweet;
    };

    $.fn.twitter = { version: "0.1" };
    $.fn.twitter = function (options) {
        var $settings = $.extend({}, $.fn.twitter.defaults, options);
        var id = 'twitter_' + CreateGuid();
        document.write('<div id="' + id + '"></div>');
        $this = $('#' + id);

        if ($settings.mode == 'timeline') {
            $settings.url = apiUserTimelineUrl + $.URLEncode($settings.query) + '&count=' + $settings.tweets + ($settings.showRetweets ? '&include_rts=true' : '&include_rts=false');
        }
        else {
            $settings.url = apiSearchUrl + $.URLEncode($settings.query) + '&rpp=' + $settings.tweets + '&result_type=' + ($settings.realTime ? 'recent' : 'mixed');
        }

        SearchTwitter($this, $settings);

        if ($settings.live) {
            //$(document).everyTime($settings.interval * 1000, SearchTwitter($this, $settings), 0);
            setInterval(function () { SearchTwitter($this, $settings) }, $settings.interval * 1000);
        };
    };

    $.fn.twitter.defaults = {
        tweets: 10,
        query: "from:achmea",
        interval: 60,
        live: true,
        animate: true,
        showDate: true,
        showRetweets: true,
        showRetweetTextOnly: false,
        showApp: true,
        realTime: true,
        dateFormat: 'HH:MM ddd mmm dd yyyy',
        mode: 'search',
        url: apiSearchUrl
    };
})(jQuery);

function htmlEncode(value) {
    return $('<div/>').text(value).html();
}

function htmlDecode(value) {
    return $('<div/>').html(value).text();
}

$.extend({ URLEncode: function (c) {
    var o = ''; var x = 0; c = c.toString(); var r = /(^[a-zA-Z0-9_.]*)/;
    while (x < c.length) {
        var m = r.exec(c.substr(x));
        if (m != null && m.length > 1 && m[1] != '') {
            o += m[1]; x += m[1].length;
        } else {
            if (c[x] == ' ') o += '+'; else {
                var d = c.charCodeAt(x); var h = d.toString(16);
                o += '%' + (h.length < 2 ? '0' : '') + h.toUpperCase();
            } x++;
        } 
    } return o;
},
    URLDecode: function (s) {
        var o = s; var binVal, t; var r = /(%[^%]{2})/;
        while ((m = r.exec(o)) != null && m.length > 1 && m[1] != '') {
            b = parseInt(m[1].substr(1), 16);
            t = String.fromCharCode(b); o = o.replace(m[1], t);
        } return o;
    }
});


/*
* Date Format 1.2.3
* (c) 2007-2009 Steven Levithan <stevenlevithan.com>
* MIT license
*
* Includes enhancements by Scott Trenda <scott.trenda.net>
* and Kris Kowal <cixar.com/~kris.kowal/>
*
* Accepts a date, a mask, or a date and a mask.
* Returns a formatted version of the given date.
* The date defaults to the current date/time.
* The mask defaults to dateFormat.masks.default.
*/

var dateFormat = function () {
    var token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
		timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
		timezoneClip = /[^-+\dA-Z]/g,
		pad = function (val, len) {
		    val = String(val);
		    len = len || 2;
		    while (val.length < len) val = "0" + val;
		    return val;
		};

    // Regexes and supporting functions are cached through closure
    return function (date, mask, utc) {
        var dF = dateFormat;

        // You can't provide utc if you skip other args (use the "UTC:" mask prefix)
        if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date)) {
            mask = date;
            date = undefined;
        }

        // Passing date through Date applies Date.parse, if necessary
        date = date ? new Date(date) : new Date;
        if (isNaN(date)) throw SyntaxError("invalid date");

        mask = String(dF.masks[mask] || mask || dF.masks["default"]);

        // Allow setting the utc argument via the mask
        if (mask.slice(0, 4) == "UTC:") {
            mask = mask.slice(4);
            utc = true;
        }

        var _ = utc ? "getUTC" : "get",
			d = date[_ + "Date"](),
			D = date[_ + "Day"](),
			m = date[_ + "Month"](),
			y = date[_ + "FullYear"](),
			H = date[_ + "Hours"](),
			M = date[_ + "Minutes"](),
			s = date[_ + "Seconds"](),
			L = date[_ + "Milliseconds"](),
			o = utc ? 0 : date.getTimezoneOffset(),
			flags = {
			    d: d,
			    dd: pad(d),
			    ddd: dF.i18n.dayNames[D],
			    dddd: dF.i18n.dayNames[D + 7],
			    m: m + 1,
			    mm: pad(m + 1),
			    mmm: dF.i18n.monthNames[m],
			    mmmm: dF.i18n.monthNames[m + 12],
			    yy: String(y).slice(2),
			    yyyy: y,
			    h: H % 12 || 12,
			    hh: pad(H % 12 || 12),
			    H: H,
			    HH: pad(H),
			    M: M,
			    MM: pad(M),
			    s: s,
			    ss: pad(s),
			    l: pad(L, 3),
			    L: pad(L > 99 ? Math.round(L / 10) : L),
			    t: H < 12 ? "a" : "p",
			    tt: H < 12 ? "am" : "pm",
			    T: H < 12 ? "A" : "P",
			    TT: H < 12 ? "AM" : "PM",
			    Z: utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
			    o: (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
			    S: ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
			};

        return mask.replace(token, function ($0) {
            return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
        });
    };
} ();

// Some common format strings
dateFormat.masks = {
    "default": "ddd mmm dd yyyy HH:MM:ss",
    shortDate: "m/d/yy",
    mediumDate: "mmm d, yyyy",
    longDate: "mmmm d, yyyy",
    fullDate: "dddd, mmmm d, yyyy",
    shortTime: "h:MM TT",
    mediumTime: "h:MM:ss TT",
    longTime: "h:MM:ss TT Z",
    isoDate: "yyyy-mm-dd",
    isoTime: "HH:MM:ss",
    isoDateTime: "yyyy-mm-dd'T'HH:MM:ss",
    isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
};

// Internationalization strings
dateFormat.i18n = {
    dayNames: [
		"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
		"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
	],
    monthNames: [
		"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
		"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
	]
};

// For convenience...
Date.prototype.format = function (mask, utc) {
    return dateFormat(this, mask, utc);
};

