/*
 * Copyright (c) 2011 The Wonderfactory, http://www.thewonderfactory.com
 *
 * 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.
 */

/**
 * @fileOverview Loads tweets into the DOM.
 * @version 0.1
 * @author The Wonderfactory <technology@thewonderfactory.com> 
 */

/**
 * See (http://jquery.com/).
 * @name jQuery
 * @class 
 * See the jQuery Library  (http://jquery.com/) for full details.  This documents
 * the function and classes that are added to jQuery by this plug-in.
 */

/**
 * See (http://jquery.com/)
 * @name jQuery.fn
 * @class 
 * See the jQuery Library  (http://jquery.com/) for full details.  This documents
 * the function and classes that are added to jQuery by this plug-in.
 * @memberOf jQuery
 */

(function($) {
    var methods = {
        init: function(options) {
            options = $.extend({}, $.fn.tweets.defaults, options);
            
            return this.each(function() {
                var self = $(this);
                
                // Store variables so we can use later
                self.data('twitter', {
                    options: options,
                    contentDiv: self.find('.' + options.contentClass)
                });

                // Load the tweets into the DOM
                functions.loadTweets.call(self);
            });
        }
    };
      
    var functions = {
        loadTweets: function() {
            var self = $(this);
            var data = self.data('twitter');
            
            // Perform jsonp ajax call to retrieve tweets
            $.ajax({
                url: 'http://search.twitter.com/search.json',
                data: {
                    q: data.options.query,
                    rpp: data.options.numberOfTweets
                },
                dataType: 'jsonp',
                success: function(jsonData) {
                    // Create ul to hold the tweets
                    var ul = $('<ul>').addClass(data.options.ulClass).hide();
                    //console.log(jsonData)
                    // Loop through each tweet and add them to the ul
                    $.each(jsonData.results, function(i, tweetData) {
                        var username = tweetData.from_user;
						var avatar = '<img src="'+tweetData.profile_image_url+'" />';
                        var status = tweetData.text.replace(/((https?|s?ftp|ssh)\:\/\/[^"\s\<\>]*[^.,;'">\:\s\<\>\)\]\!])/g, function(url) {
                            return '<a target="'+ data.options.target +'" href="' + url + '">' + url + '</a>';
                        }).replace(/\B@([_a-z0-9]+)/ig, function(reply) {
                            return  reply.charAt(0) + '<a target="' + data.options.target + '" href="http://twitter.com/' + reply.substring(1) + '"><strong>' + reply.substring(1) + '</strong></a>';
                        });
                        
                        var li = $('<li><div>' + avatar + '</div><div class="last">' + status + ' <p class="age">' + functions.relativeTime(tweetData.created_at) + '</p></div></li>');
                        li.appendTo(ul);
                    });

                    ul.appendTo(data.contentDiv).fadeIn();

                    data.contentDiv.scarecrow();
                }
            });
        },
        
        relativeTime: function (timeValue) {
            var values = timeValue.split(' ');
            timeValue = values[2] + " " + values[1] + ", " + values[3] + " " + values[4];
            var parsed_date = Date.parse(timeValue);
            var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
            var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
            delta = delta + (relative_to.getTimezoneOffset() * 60);

            if (delta < 60) {
                return 'less than a minute ago';
            } else if(delta < 120) {
                return 'about a minute ago';
            } else if(delta < (60 * 60)) {
                return (parseInt(delta / 60)).toString() + ' minutes ago';
            } else if(delta < (120 * 60)) {
                return 'about an hour ago';
            } else if(delta < (24 * 60 * 60)) {
                return 'about ' + (parseInt(delta / 3600)).toString() + ' hours ago';
            } else if(delta < (48 * 60 * 60)) {
                return '1 day ago';
            } else {
                return (parseInt(delta / 86400)).toString() + ' days ago';
            }
        }
    };
    
    /**
     * <p>Loads tweets into the DOM.</p>
     *
     * @example $('.twitter').tweets({ username: 'google', numberOfTweets: 10 });
     *
     * @param options An optional options object.
     *
     */
    jQuery.fn.tweets = function(method) {
        // Method calling logic
        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || ! method) {
            return methods.init.apply(this, arguments);
        } else {
            $.error('Method ' +  method + ' does not exist');
        }
    };
    
    jQuery.fn.tweets.defaults = {
        contentClass: 'feed',
        ulClass: 'scarecrow-content',
        target:'_blank',
        
        query: null,
		numberOfTweets: 21
    };
})(jQuery);
