/*!
 * jQuery Meteorologica Plugin
 * Author: Ernest Lombardi
 *
 * Required files:
 * jquery.meteorologica.js
 * /css/meteorologica.css
 *
 * Copyright (c) 2010 E.Lombardi: http://www.ernestlombardi.com/
 * Version: 1.0 (30-JAN-2010)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 * Requires: jQuery v1.3.x or later
 */

(function($) {

	$.fn.meteorologica = function(options){
	    
	    config = $.extend({}, $.fn.meteorologica.defaults, options);
	    
	    var feed = new google.feeds.Feed(config.feed + config.zip);    
	    
	    feed.load(function(result) {
			    
		if (!result.error) {
		
			var header = result.feed.entries[0].title;
			
			var content = result.feed.entries[0].content;
			
			if(header.indexOf("City not found") < 0){
				
				$.fn.meteorologica.format(header, content);
			    
			}else{
				
			    alert("City not found. Please try another zip code.");
			    
			}
		    
		}
		
	    });
	    
	};  
	
	$.fn.meteorologica.format = function(header, content){
	    var location = header.indexOf(" for ") + 5;
	    location = header.substr(location, header.indexOf(" at ") - location);
	    $(".forecastLocation").html(location);
	    
	    var forecastTime = header.indexOf(" at ") + 4;
	    forecastTime = header.substr(forecastTime, header.length);
	    $(".forecastTime").html(forecastTime);
	    
	    var forecastImage = content.indexOf("<img ");
	    forecastImage = content.substr(forecastImage, (content.indexOf(".gif") + 6) - forecastImage);
	    $(".forecastImage").html(forecastImage);    
	    
	    var currentConditions = content.indexOf("</b>") + 4;
	    currentConditions = content.substr(currentConditions, content.lastIndexOf("<b>") - currentConditions);
	    $(".currentConditions").html(currentConditions.replace(/<br>/g,""));      
	    
	    var todaysForecast = content.indexOf("-") + 1;
	    todaysForecast  = content.substr(todaysForecast , content.lastIndexOf("-") - (todaysForecast + 9));
	    $(".todaysForecast").html(todaysForecast .replace(/<br>/g,""));    
	    
	    var tomorrowsForecast = content.lastIndexOf("-") + 1;
	    tomorrowsForecast  = content.substr(tomorrowsForecast , content.indexOf("<a") - (tomorrowsForecast + 1));
	    $(".tomorrowsForecast").html(tomorrowsForecast .replace(/<br>/g,""));     
	    
	    var fullForecast = content.indexOf("<a");
	    fullForecast  = content.substr(fullForecast, content.length - fullForecast);
	    fullForecast  = fullForecast.replace(/<br>/g,"");     
	    $(".fullForecast").html(fullForecast.replace("</a>","</a><br/>"));
	};
	
	$.fn.meteorologica.update = function(newZip){

		$.fn.meteorologica({
				
			zip: newZip.value
			
		});
		
	};
	
	$.fn.meteorologica.defaults = {
		
		zip: "04101",
		feed: "http://weather.yahooapis.com/forecastrss?p="
		
	};

})(jQuery);
