﻿// this script is reliant on jquery.cookie.js and jquery.tweet.js

jQuery.fn.twitterCache = function (options) {

    var opt = $.extend({
        username: "ledgardjepson",
        avatar_size: 0,
        count: 1,
        cookie_name: "twitter_store",
        cookie_expire_minutes: 10,
        debug_cache_status: false,
        no_tweets_message: "No tweets to display"
    }, options);

    var val = $.cookie(opt.cookie_name);
    var target_div = $(this);

    //we have a cache - use it
    if (val !== null) {

        var output = val;
        if (opt.debug_cache_status) { output = "<p>CACHED:</p>" + val; }
        target_div.html(output);

    } else {

        //get fresh data

        target_div.tweet({
            username: opt.username,
            count: opt.count,
            avatar_size: opt.avatar_size
        });

        setTimeout(function () {

            var latest_tweet = target_div.html();
            if (latest_tweet == "") {
                latest_tweet = "<p>" + opt.no_tweets_message + "</p>";
            }
            $.cookie(opt.cookie_name, latest_tweet, { expires: opt.cookie_expire_minutes });

        }, 500);
    }

};
