/*
 * jQuery Twitter/Identica plugin 0.1.1
 * Requires jQuery 1.3.2
 *
 * Copyright 2011, Ronnie van den Crommenacker
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 */
 
/*
 * functions parseDate and parseResults are copied and modified from twidenash
 * See the copyrights for those functions below
* 
* 
* Copyright (c) 2010 Stuart Langridge
* 
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* 
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* 
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* Website: http://code.google.com/p/twidenash/
*/


(function ($) {
    $.fn.extend({   
        twidenash: function (options) {
            var defaults = {
                use_id: true,               // If true, the id="" of the element will be used
                hashtag: null,              // The hashtag to search (if use_id = false)
                amount: 5,                  // Aount of items to get
                update_interval: 30000,     // How often to refresh
                sources: [                  // The sources to search the hashtag
                    'http://locoteams.status.net/api/',
                    'http://identi.ca/api/',
                    'http://search.twitter.com/'
                ]
            };
            options =  $.extend(defaults, options);
            
            function parseDate(created_at) {
                var date = new Date(),
                    delta = parseInt((date.getTime() - created_at) / 1000, 10),
                    pluralize = function (singular, n) {
                        return n + ' ' + singular + (n === 1 ? '' : 's');
                    },
                    date_msg = null;
                if (delta < 60) {
                    date_msg = 'less than a minute ago ';
                } else if (delta < (45 * 60)) {
                    date_msg = 'about ' + pluralize("minute", parseInt(delta / 60, 10)) + ' ago ';
                } else if (delta < (24 * 60 * 60)) {
                    date_msg = 'about ' + pluralize("hour", parseInt(delta / 3600, 10)) + ' ago ';
                } else {
                    date_msg = 'about ' + pluralize("day", parseInt(delta / 86400, 10)) + ' ago ';
                }
                return date_msg;
            }
            
            function parseResults(element, data) {
                var exp = /(\b(https?|ftp|file):\/\/[\-A-Z0-9+&@#\/%?=~_|!:,.;]*[\-A-Z0-9+&@#\/%=~_|])/gi,
                    items = [],
                    result,
                    item,
                    r;
                for (r in data.results) {
                    if (data.results.hasOwnProperty(r)) {
                        result = data.results[r];
                        items.push({ text: result.text, 
                            id: result.id,
                            img: result.profile_image_url, 
                            dt: Date.parse(result.created_at),
                            user: result.from_user });
                    }
                }
                items.sort(function (a, b) { return b.dt - a.dt; });
                for (r in items) {
                    if (items.hasOwnProperty(r)) {
                        item = items[r];
                        // TODO: check for other sources datetime
                        if (element.children().length < options.amount) {
                            $(element).append($('<li><img width="48" src="' + item.img + '"><span class="nick" id="' + item.id + '">' + item.user + '</span><span class="time"> ' + parseDate(item.dt) + ' </span><span class="comment">' + item.text.replace(exp, "<a href='$1' target='_blank'>$1</a>") + '</span></li>').hide().fadeIn('slow'));
                        }
                    }
                }
            }
            
            function fetch(element, url, hashtag, amount) {
                $.getJSON(url + 'search.json?callback=?', {q: '#' + hashtag, rpp: amount}, function (data) {
                    parseResults(element, data);
                });
            }
            
            return $(this).each(function (i, html_element) {

                function update(html_element, options) {
                    var html_element = html_element;
                    var options = options;
                    return function() {
                        $(html_element).empty();
                        var sources = options.sources,
                            element = $('<ul>').appendTo(html_element),
                            hashtag,
                            s;
                        for (s in sources) {
                            if (sources.hasOwnProperty(s)) {
                                hashtag = options.use_id ? $(html_element).attr('id') : options.hashtag;
                                if (hashtag) {
                                    fetch(element, sources[s], hashtag, options.amount);
                                }
                            }
                        }
                    }
                }
                update(html_element, options)();
                window.setInterval(update(html_element, options), options.update_interval);
            });
        }
    });
}(jQuery));

