(function($){
	
	var weather_flag=false;
	
	function print_weather_error() {
		var output;
		output = '<div id="weather-info">';
		output += '<table id="weather-table"><tr>';
		output += '<td id="w_unknow_left"><img src="themes/fyru/snippets/weather/icons/fyru/unknow.jpg"/></td>';
		output += '<td id="w_unknow_right">нет данных</td>';
		output += '</tr></table>';
		output += '<div id="gismeteo-copyrigth">';
		output += '<a href="http://gismeteo.ru">gismeteo.ru</a></div></div>';
		$('#weather').html(output);
		$('#weather-select').html('Выберите город');
	}
	
	function print_weather(siti_id) {
		
		var output;
		try {
			var pars = {
				tpl: '@FILE:themes/fyru/snippets/weather/weather.tpl',
				themes: 'fyru',
				error: '@FILE:themes/fyru/snippets/weather/error.tpl',
				icons: 'fyru',
				siti_id: siti_id
			};
			weather_flag=true;
			$('#weather').html('<img src="themes/fyru/snippets/weather/icons/ajax-loader.gif" id="w-loader"/>');
			$('#weather-td').css('cursor','wait');
			var options = {
					url: 'index.php?id=493',
					data: pars,
					dataType: 'json',
					timeout: 30000,
					async: true,
					success: function(data) {
							if (!data.error) {
								$('#weather').html(data.template);
								$('#weather-select').html(data.name);
							} else print_weather_error();
							$('#weather-td').css('cursor','auto');
							weather_flag=false;
						},
					error: function(data) {
						print_weather_error();
						$('#weather-td').css('cursor','auto');
						weather_flag=false;
					}
			}
			$.ajax(options);
		} catch(e) {
		}
	}
	
	$(function(){

		var $weather_siti = $('#weather-siti');
		var cookie_wth = $.readCookie('wth');
		var siti_id;
		
		if (cookie_wth) siti_id = cookie_wth;
		else siti_id = 2;
		
		print_weather(siti_id);
		
		$('#weather-select').bind('click',function(event) {
			if (weather_flag) return;
			$weather_siti.show(100);
		});
						
		$weather_siti.bind('click',function(event) {
			var name;
			var $target = $(event.target);
			if ($target.hasClass('siti')) {
				var siti_id = $target.attr('siti_id');
				$('#weather-select').html('Загрузка');
				$(this).hide(100);
				print_weather(siti_id);
				$.setCookie("wth", siti_id, {duration: 365});
			} else {
				if ($target.hasClass('w-close'))
					$(this).hide(100);
			}
		});	
		
	});
		
})(jQuery);