/*
    Title:	Live Twitter Search
    Date: 24th July 2009
    Author: Andrew Mason 
    Contact: a.w.mason at gmail.com
    
    URL: http://analoguesignal.com/

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
    
*/

// Wait till the DOM is ready then run the app
$('windows').ready(function() {
    livesearch.init();
});

var livesearch = {
    search_url: 'http://search.twitter.com/search.json',
    refresh_url: '',
    updating: false,
    target_id: '#results',
    tweets: new Array(),
    img_cache: new Array(),
    max: 4,
    show_delay: 1, // In seconds
    paused: false,
    delay: 20, // In seconds
    
    
    
    fetch: function(term) {       
        // Build the default URL
        var url = this.search_url + '?q=' + encodeURIComponent(term) + "&callback=?";
        
        // if updating use a different URL
        if (this.updating) {
            url = this.search_url + livesearch.refresh_url + "&callback=?";
        }
        
        // Get the first set of tweets
        $.getJSON(url,
        function(data){
            // Clear image cache
            $('#cached_images').empty();
            
            // Set the update refresh URL
            livesearch.refresh_url = data.refresh_url;

            // Do these actions on first fetch
            if (!livesearch.updating) {
                // Clear the target and array
                $(livesearch.target_id).empty();
                livesearch.tweets = new Array();   
            }
            
            // Add the results to tweet array
            livesearch.tweets = jQuery.merge(livesearch.tweets, jQuery.makeArray(data.results));
            
            // if there where no results, display an error message
            if (!livesearch.updating && livesearch.tweets <= 0) {
                $(livesearch.target_id).html('<div id="no_tweet">Sorry, there&rsquo;s no results for that search</div>');
            }

            
            if (!livesearch.updating) {
                // Clear any setInterval that is running
                clearInterval(livesearch.output_interval);
                clearInterval(livesearch.refreshInterval);
                
                // Start a new DOM writing interval
                livesearch.output_interval = setInterval(function() {
                    if (livesearch.tweets.length > 0) {
                        livesearch.display(livesearch.tweets.shift(), true);
                    };
                }, livesearch.show_delay*1000);
                
                // Start a new ajax call interval
                livesearch.refreshInterval = setInterval(function() {
                    livesearch.fetch();
                }, livesearch.delay*1000);
            }
            
            // pre-cache images
            $.each(data.results, function() {
                $('#cached_images').append('<img src="' + this.profile_image_url + '" />\n\r');
            });
            
            // Indicate that the next fetch will update exisiting tweets
            livesearch.updating = true;
        });
    },
    
    search: function(term) {
        // Clear update interval
        clearInterval(livesearch.output_interval);
        
        // Indicate it's a new search
        livesearch.updating = false;
        
        // Remove all tweets from DOM
        $(livesearch.target_id).html('<div id="loading">Loading...</div>');
        
        // Make the Ajax call
        this.fetch(term);        
    },

    
    display: function(tweet, slide) {
    
        /*
        if ($('.result').length >= this.max) {
            $('.result:last').slideUp('slow', function() {
                $(this).remove();
            });
        }
        */
        
        var result_container = $('<div class="result"></div>');
        result_container.append('<a class="tweet_photo" href="http://www.twitter.com/' + tweet.from_user + '"><img width="48" height="48" alt="tweet_photo" src="' + tweet.profile_image_url + '" /></a>\n\r');
        result_container.append('<p class="tweet_text">' + tweet.text + '</p>\n\r');
        result_container.append('<p class="tweet_meta">from <span class="tweet_user">' + tweet.from_user + '</span> on '+ tweet.created_at + '</p>\n\r');
        
        
        $('#results').prepend(result_container);
        
        if (slide) {
            result_container.hide();
            result_container.slideDown("slow");
        }
        
        result_container.bind('click', function() {
            livesearch.pause(this);
        });
  
    },
    
    pause: function(e) {
        
        $(livesearch.paused_tweet).stop;
        
        if (!this.paused) {
        
            livesearch.paused_tweet = e;
        
            //clearInterval(this.countdown);
            clearInterval(livesearch.output_interval);
            
            // Stop animate bar
            //$('#refresh_inner').stop();
            
            // Flag that the system is paused
            livesearch.paused = true;
            
            // Add paused message
            var pause_elm = $('<div id="paused">Paused</div>').hide();
            $(e).prepend(pause_elm);
            pause_elm.slideDown();
            
            $(e).toggleClass('paused');
            
            return;
        }
        
        
        
        if (livesearch.paused_tweet != e) {
            return false;
        }
        
        // Flag that the system is un-paused
        this.paused = false;
        
        // remove paused elmenet
        $('#paused').slideUp('slow', function(e) {
            $(this).remove();
        });
        
        $(e).toggleClass('paused');
        
        
        // Unpausing
        livesearch.output_interval = setInterval(function() {
            if (livesearch.tweets.length > 0) {
                livesearch.display(livesearch.tweets.shift(), true);
            };
        }, livesearch.show_delay*1000);
 
   
    },
    
    init: function() {
        // this.search('twitter');
        $('#submit').bind('click', function() {
            if ($('#search_term').attr('value') == '') {
                alert('Please enter a search term');
                return;
            }
            livesearch.search($('#search_term').attr('value'));
        });
        
        
        $('#search_term').bind('keypress', function(e) {
            if (e.which == 13) {
                if ($(this).attr('value') == '') {
                    alert('Please enter a search term');
                    return;
                } else {
                    livesearch.search($('#search_term').attr('value'));
                }
            }
        });
        
        // Hidden cached image container
        $('body').append('<div id="cached_images" style="display: none;"></div>');
        
         
        // Get latest trends
        $.getJSON('http://search.twitter.com/trends/current.json?&callback=?',
        function(data){
            $('#inner_trends').empty();
            $.each(data.trends, function() {
                $.each(this, function() {
                    var link = $("<a href='#' title='" + this.query+ "'>" + this.name + '</a>').bind('click', function() {
                        $('#search_term').attr('value', this.title);
                        livesearch.search(this.title);
                        return false;
                    });
                    
                    $('#inner_trends').append(link);
                });
            });
            
            
        });
    }
};