(function($) {
    $.fn.extend({

        jdigiclock: function(options) {

            var defaults = {
                weatherImagesPath: 'images/weather/',
                lang: 'en',
                am_pm: false,
                weatherLocationCode: 'NAM|US|IL|FAIRBURY',
                weatherMetric: 'F',
                weatherUpdate: 0,
                proxyType: 'php'
                
            };

            var options = $.extend(defaults, options);

            return this.each(function() {
                
                var $this = $(this);
                var o = options;
                $this.weatherImagesPath = o.weatherImagesPath;
                $this.weatherLocationCode = o.weatherLocationCode;
                $this.weatherMetric = o.weatherMetric == 'C' ? 1 : 0;
                $this.weatherUpdate = o.weatherUpdate;
                $this.proxyType = o.proxyType;

                var html = '<div id="digital_container">';
                html    += '<div id="weather"></div>';
                html    += '</div>';

                $this.html(html);

                $this.displayWeather($this);               

            });
        }
    });
   
    $.fn.displayWeather = function(el) {
        $.fn.getWeather(el);
        if (el.weatherUpdate > 0) {
            setTimeout(function() {$.fn.displayWeather(el)}, (el.weatherUpdate * 60 * 1000));
        }
    }

    $.fn.getWeather = function(el) {

        el.find('#weather').html('<p class="loading">Update Weather ...</p>');
        var metric = el.weatherMetric == 1 ? 'C' : 'F';
        var proxy = '';

        switch (el.proxyType) {
            case 'php':
                proxy = 'php/proxy.php';
            break;
            case 'asp':
                proxy = 'asp/WeatherProxy.aspx';
            break;
        }

        $.getJSON('lib/proxy/' + proxy + '?location=' + el.weatherLocationCode + '&metric=' + el.weatherMetric, function(data) {

            el.find('#weather .loading').hide();

            var curr_temp = '<p class="temp">' + data.curr_temp + '&deg;<span class="metric">' + metric + '</span></p>';

            el.find('#weather').css('background','url(' + el.weatherImagesPath + data.curr_icon + '.png) 60% 50% no-repeat');
            var weather = '<div id="local"><p class="city">' + data.city + '</p><p class="tempname">' + data.curr_text + '</p></div>';
			weather += '<div id="temp">' + curr_temp + '</div>';
            el.find('#weather').html(weather);
        });
    }

})(jQuery);
