﻿/**
 * Plugin: jquery.zWeatherFeed
 * 
 * Version: 1.0.2
 * (c) Copyright 2010, Zazar Ltd
 * 
 * Description: jQuery plugin for display of Yahoo! Weather feeds
 * 
 * History:
 * 1.0.2 - Correction to options / link
 * 1.0.1 - Added hourly caching to YQL to avoid rate limits
 *         Uses Weather Channel location ID and not Yahoo WOEID
 *         Displays day or night background images
 *
 **/

(function($){

	var row = 'odd';

	$.fn.weatherfeed = function(locations, options) {	
	
		// Set pluign defaults
		var defaults = {
			unit: 'c',
			image: true,
			highlow: true,
			wind: true,
			link: true,
			showerror: true
		};  
		var options = $.extend(defaults, options); 
		
		// Functions
		return this.each(function(i, e) {
			var $e = $(e);
			
			// Add feed class to user div
			if (!$e.hasClass('weatherFeed')) $e.addClass('weatherFeed');

			// Check and append locations
			if (!$.isArray(locations)) return false;
			var count = locations.length;
			if (count > 10) count = 10;
			var locationid = '';
			for (var i=0; i<count; i++) {
				if (locationid != '') locationid += ',';
				locationid += "'"+ locations[i] + "'";
			}

			// Cache results for an hour to prevent overuse
			now = new Date()
					
			// Create Yahoo Weather feed API address
			var query = "select * from weather.forecast where location in ("+ locationid +") and u='"+ options.unit +"'";
			var api = 'http://query.yahooapis.com/v1/public/yql?q='+ encodeURIComponent(query) +'&rnd='+ now.getFullYear() + now.getMonth() + now.getDay() + now.getHours() +'&format=json&callback=?';

			// Send request
			//$.getJSON(api, function(data) {
			$.ajax({
				type: 'GET',
				url: api,
				dataType: 'json',
				success: function(data) {

					if (data.query) {
			
						if (data.query.results.channel.length > 0 ) {
							
							// Multiple locations
							var result = data.query.results.channel.length;
							for (var i=0; i<result; i++) {
							
								// Create weather feed item
								_callback(e, data.query.results.channel[i], options);
							}
						} else {

							// Single location only
							_callback(e, data.query.results.channel, options);
						}
					} else {
						if (options.showerror) $e.html('<p>Weather information unavailable</p>');
					}
				},
				error: function(data) {
					if (options.showerror)  $e.html('<p>Weather request failed</p>');
				}
			});

		});
	};

	// Function to each feed item
	var _callback = function(e, feed, options) {
		var $e = $(e);

		// Format feed items
		var wd = feed.wind.direction;
		if (wd>=348.75&&wd<=360){wd="É"};if(wd>=0&&wd<11.25){wd="É"};if(wd>=11.25&&wd<33.75){wd="É-ÉK"};if(wd>=33.75&&wd<56.25){wd="ÉK"};if(wd>=56.25&&wd<78.75){wd="K-ÉK"};if(wd>=78.75&&wd<101.25){wd="K"};if(wd>=101.25&&wd<123.75){wd="K-DK"};if(wd>=123.75&&wd<146.25){wd="DK"};if(wd>=146.25&&wd<168.75){wd="D-DK"};if(wd>=168.75&&wd<191.25){wd="D"};if(wd>=191.25 && wd<213.75){wd="D-DNY"};if(wd>=213.75&&wd<236.25){wd="DNY"};if(wd>=236.25&&wd<258.75){wd="NY-DNY"};if(wd>=258.75 && wd<281.25){wd="NY"};if(wd>=281.25&&wd<303.75){wd="NY-ÉNY"};if(wd>=303.75&&wd<326.25){wd="ÉNY"};if(wd>=326.25&&wd<348.75){wd="É-ÉNY"};
		var wf = feed.item.forecast[0];
		
		// Determine day or night image
		wpd = feed.item.pubDate;
		n = wpd.indexOf(":");
		tpb = _getTimeAsDate(wpd.substr(n-2,8));
		tsr = _getTimeAsDate(feed.astronomy.sunrise);
		tss = _getTimeAsDate(feed.astronomy.sunset);

		if (tpb>tsr && tpb<tss) { daynight = 'd'; } else { daynight = 'n'; }

		// Add item container
		var html = '<div class="weatherItem '+ row +'"';
		if (options.image) html += ' style="background-image: url(http://l.yimg.com/a/i/us/nws/weather/gr/'+ feed.item.condition.code + daynight +'.png); background-repeat: no-repeat;"';
		html += '>';
		var ido = new Array();
    ido = {
      'tornado' : 'Tornádó',
      'tropical storm' : 'Trópusi vihar',
      'hurricane' : 'Hurrikán',
      'severe thunderstorms' : 'Zivatarok',
      'thunderstorms' : 'Zivatarok',
      'mixed rain and snow' : 'Havas eső',
      'mixed rain and sleet' : 'Eső és Ónos eső',
      'mixed snow and sleet' : 'Hó és Ónos eső',
	  'mist':'Köd',
	  'cloudy/windy':'Felhős/Szeles',
	  'light snow/windy': 'Enyhe Hó/Szeles',
	  'snow shower/windy': 'Hózápor/Szeles',
	  'light rain/windy': 'Enyhe Eső/Szeles',
      'freezing drizzle' : 'Ónos szitálás',
	  'light drizzle' : 'Gyenge Szitálás',
	  'light freezing drizzle/fog':'Ónos szitálás/Köd',
      'drizzle' : 'Szitálás',
	  'light freezing drizzle': 'Enyhe Ónos Szitálás' ,
      'freezing rain' : 'Ónos eső',
	  'showers in the vicinity': 'Záporok a közelben',
      'showers' : 'Zápor',
'rain and snow' : 'Havaseső',
'snow/windy' : 'Hó / Szeles',
	  'rain': 'Eső',
	  'light snow': 'Hószállingózás',
	  'showers': 'Zápor',
	  'light rain': 'Szemerkélő eső',
	  'rain shower': 'Zápor Eső',
	  'light rain showers': 'Gyenge Záporeső',
	  'light rain shower': 'Gyenge Záporeső',
      'snow flurries' : 'Hózáporok',
      'light snow showers' : 'Hószállingózás',
	  'light snow shower' : 'Hószállingózás',
      'blowing snow' : 'Hófúvás',
'light snow/fog' : 'Hó/Ködös' ,
      'drifting snow': 'Hófúvás',
      'snow' : 'Hóesés',
	  'snow/fog' : 'Hó/Ködös',
	  'light snow grains': 'Enyhe hószitálás',
	  'light snow grains/fog':'Enyhe Hószitálás/Köd',
      'hail' : 'Jégeső',
      'sleet' : 'Ónoseső',
	  'light rain/freezing rain': 'Gyenge eső/Ónoseső',
      'dust' : 'Poros',
	  'ice crystals': 'Fagyos',
'snow grains' : 'Dara',
      'foggy' : 'Ködös',
	  'snow shower' : 'Hózápor' ,
	  'light freezing rain': 'Enyhe Ónoseső',
	  'fog': 'Ködös',
      'haze' : 'Ködös',
      'smoky' : 'Szmogos',
      'blustery' : 'Viharos zivatar',
      'windy' : 'Szeles',
      'cold' : 'Hideg',
      'cloudy' : 'Felhős',
      'mostly cloudy' : 'Többnyire felhős',
      'partly cloudy' : 'Részben felhős',
	  'partly cloudy/windy': 'Részben felhős/Szeles',
      'clear': 'Tiszta',
	  'mostly sunny/wind': 'Többnyire Napos/Szeles',
      'sunny' : 'Napos',
      'fair' : 'Bárányfelhős',
	  'fair/windy': 'Felhős/Szeles',
      'fair' : 'Bárányfelhős',
      'mixed rain and hail' : 'Eső és jégeső',
      'hot' : 'Hőség',
      'isolated thunderstorms' : 'Zivatarok',
      'scattered thunderstorms' : 'Elszórtan zivatarok',
      'scattered showers' : 'Elszórtan záporok',
      'heavy snow' : 'Hózápor',
      'scattered snow showers' : 'Elszórtan havazás',
      'heavy snow' : 'Hózápor',
      'partly cloudy' : 'Részben felhős',
      'thundershowers' : 'Felhőszakadás',
	  'thunderstorm': 'Zivatar',
      'snow showers' : 'Havazás',
	  'light rain with thunder': 'Gyenge Eső Dörgéssel',
	  'thunder in the vicinity': 'Vihar a közelben',
	  'thunderstorm/windy': 'Zivatar/Szeles',
	  'mostly cloudy/windy':'Többnyire Felhős/Szeles',
	  'heavy thunderstorm': 'Heves Zivatar',
	  'scattered thunderstorm': 'Elszórtan Zivatar',
	  'thunder': 'Viharos',
      'isolated thundershowers' : 'Felhőszakadás',
      'not available' : 'nem elérhető' 
	  };
	  
	  var varos = new Array();
	  varos = {
		  'GYOR': 'GYŐR',
		  'SZOLNOK': 'SZOLNOK',
		  'SIOFOK': 'SIÓFOK',
		  'PECS/POGANY': 'PÉCS',
		  'DEBRECEN': 'DEBRECEN',
		  'KESZTHELY': 'KESZTHELY',
		  'MISKOLC': 'MISKOLC',
		  'BUDAPEST': 'BUDAPEST',
		  'SZEGED': 'SZEGED',
		  'KECEL': 'PAKS',
	  };
	  

		// Add item data
		html += '<div class="weatherCity">'+ varos[feed.location.city.toUpperCase()] +'</div>';
		html += '<div class="weatherTemp">'+ feed.item.condition.temp +'&deg;</div>';
		html += '<div class="weatherDesc">'+ ido[feed.item.condition.text.toLowerCase()] +'</div>';
		if (options.highlow) html += '<div class="weatherRange">Max: '+ wf.high +'&deg; Min: '+ wf.low +'&deg;</div>';
		if (options.wind) html += '<div class="weatherWind">Szél: '+ wd +' '+ feed.wind.speed + feed.units.speed +'</div>';
		if (options.link) html += '<div class="weatherLink"><a href="'+ feed.item.link +'">Teljes előrejelzés</a></div>';
		
		html += '</div>';

		// Alternate row classes
		if (row == 'odd') { row = 'even'; } else { row = 'odd';	}
		
		$e.append(html);
	};

	// Get time string as date
	var _getTimeAsDate = function(t) {
		
		d = new Date();
		r = new Date(d.toDateString() +' '+ t);

		return r;
	};
})(jQuery);

