﻿(function (ix2, $, undefined) {

    // Add twitterClient to the ix2 namespace (our own library)
    // we could also add private functions/properties here that 
    // can be shared amungst all "modules" in the IX2 library
    ix2.twitterClient = function (opts) {
        // private to twitterClient
        var defaults = {
            twitterSearchUrl: 'http://search.twitter.com/search.json',
            template: '',
            element: '',
            childClass: '',
            rpp: 25
        };

        // Merge our defaults with the parameters passed in
        // Using jQuery to help us.
        var options = $.extend({}, defaults, opts);

        // public - returned from twitterClient
        var pub = {};

        //private functions to twitterClient
        function getTweets(query, rpp, callback) {
            if (query === undefined) {
                throw "You must enter a twitter query";
            }

            // use jquery ajax to get the data
            var urlToCall = options.twitterSearchUrl + '?rpp=' + rpp + '&q=' + escape(query);
            $.ajax({
                url: urlToCall,
                dataType: 'jsonp',
                success: function (data, status, xhr) {
                    if (callback) { callback(data.results); }
                },
                error: function (xhr, status, error) {
                    console.log(status + ": " + error);
                }
            });
        }

        function displayTweets(data, templateId, elementId, childClass) {
            $(templateId).tmpl(data).appendTo($(elementId));
            if ($().timeago) {
                $(childClass + ' .relative').timeago();
            }
        }

        // public functions
        pub.getStream = function (query) {
            getTweets(query, options.rpp, function (data) {
                displayTweets(data, options.template, options.element, options.childClass);
            });
        };

        return pub;
    };

} (window.ix2 = window.ix2 || {}, jQuery));
