(function ($) {
    $.fn.addEvents = function (o) {

        $this = $(this);

        _url = createUrl('http://www.cambridgeshire.net/json_search.aspx?', o);

        function createUrl(url, o) {
            $.each(o, function (k, v) {
                url += "&" + k + "=" + v;
            });
            return url;
        }
        
        function addEvent(event, evens) {
            liClass = (evens) ? "even" : "";

            $("<li>").addClass(liClass)
                .append($("<a>").attr({ href: event.link }).text(event.title))
                .append($("<span>").addClass("date").text(" - " + event.startdate + ", " + event.location))
                .append($("<p>").addClass("description").text(event.description))
                .appendTo("#" + $this.attr("id") + " ul");
            }

            $.ajax({
                url: _url,
                type: 'GET',
                dataType: 'jsonp',
                timeout: 3000,
                error: function () {
                    ($this).text("There is a problem retrieving these events. Please try again later.");
                },
                success: function (data) {
                    if (data.rss.channel.item) {
                        $("<ul>").appendTo($this);
                        if (parseInt(data.rss.channel.totalResults) > 1) {
                            $.each(data.rss.channel.item, function (i, item) {
                                addEvent(item, i % 2 == 0);
                            });
                        }
                        else {
                            addEvent(data.rss.channel.item, false);
                        }
                    }
                    else
                        ($this).text("Sorry there are no results.");
                    }
            });
        
        }
})(jQuery);

