(function($){
    $.fn.jWeather = function(options) {
        var defaults = {
            url: "http://www.elon.edu/e-net/GetXML.aspx?getUrl=http://www.weather.gov/data/current_obs/KBUY.xml",
            showImage: true,
            showLocationString: true,
            locationString: "Elon, NC",
            minutesBetweenRefresh: 30
        };
        var options = $.extend(defaults, options);
        
        return this.each(function() {
            obj = $(this);
            
            obj.ready(function(){
                getWeather(obj, options);
            });
            
            try
            {
                var seconds = 60 * options.minutesBetweenRefresh;
                obj.everyTime(seconds + "s",function(i) { // refresh the weather every 30 minutes
                    getWeather(obj, options);
                });
            } catch(exception)
            {
                // a reference to http://www.elon.edu/e-net/Scripts/menu/jquery.timers.min.js is not defined by the page
            }
            
        });
    };

    function getWeather($obj, options)
    {
        obj.html("<img src=\"http://www.elon.edu/e-net/images/indicator.gif\" alt=\"loading...\" />");
                
        $.ajax({
            type: "GET",
            url: options.url,
            dataType: "xml",
            success: function(xml) {
                $(xml).find('current_observation').each(function(){
                    obj.html("");
                    var temp = $(this).find('temp_f').text().split(".")[0] + "&deg;<span id=\"jWeatherF\">F</span>";
                    var img_src = $(this).find('icon_url_base').text() + $(this).find('icon_url_name').text();
                    var wrapper = $("<div id=\"jWeatherTemp\"></div>").html(temp);
                    if (options.showLocationString)
                    {
                        obj.prepend("<div id=\"jWeatherLocation\">" + options.locationString + "</div>");
                    }
                    obj.append(wrapper);
                    if (options.showImage)
                    {
                        obj.append("<img id=\"jWeatherIcon\" src=\"" + img_src + "\" alt=\"" + $(this).find('weather').text() + "\" title=\"" + $(this).find('weather').text() + "\"/>");
                    }
                });
            },
            error: function(xhr, message, ex) {
                //alert("Weather Ajax Error: " + message);
            }
        });
    }

})(jQuery);
