
function fontSize() {
  var width = 256;
  var fontSize = 24;
  var bodyWidth = $('html').width();
  var multiplier = bodyWidth / width;
  if ($('html').width() >= width) fontSize = Math.floor(fontSize * multiplier);
  $('body').css({fontSize: fontSize+'px'});
}

function setFactBlockHeight() {
	var hCity = ($('.city').is(':hidden')?0:$('.city').height());
	var h = Math.round(($('body').height() - hCity) / ($('.forecast').is(':hidden')?1:($('.forecast .img').is(':hidden')?1.5:2)));
	$('.fact table:first').css({'height':h+ 'px'});
	h = $('.forecast .img').is(':hidden')?h+Math.round(h*0.25):h;	
	return h;
}	

	var frcst = {
		citiesUrl: 'http://1eb4755a.services.gismeteo.ru/inform-service/40e7e07825d543ebb5d07cf4f2ee6d04/cities/',
		forecastUrl: 'http://1eb4755a.services.gismeteo.ru/inform-service/40e7e07825d543ebb5d07cf4f2ee6d04/forecast/',
		dict: null,
		delay: null,
		params: {
			lang: 'en', 
			deg: 'F', 
			press: 'mmHg', 
			hum: null, 
			wind: 'm',
			tpl: 'v2',
			weather: 'fact',
			icon: 'photorealistic'					 
		},
		currentCity: {
			id: null,
			name: null,
			fact: [],
			forecast: []
		},
		updatetime: 900000,
		utc: {timer: null, delay: 30000, time: null},
		tpl: null,
		isRenderFrc: true,
		version: '2_2',
		init: function(callback) {	
			$.each(listTepmplates.tpls, function(key, val) {
				$(val).remove();
			});				
			this.params = this.getConfig('params') || this.getDefaultSettings();
			this.setDictFromLang(this.params.lang);			
			var city = this.getConfig('city');	
			
			if (city) {
				this.currentCity = city;
				if (callback) callback();	
			}
			else this.setDefaultCityWithHtml5(callback)
			
			try {	
				var title = ($('html').height()<=64?frcst.currentCity.name[frcst.params.lang]:'Gismeteo');
				var url = 'http://www.gismeteo.'+this.dict.domain+'/city/hourly/'+city.id+'/?from=speeddial';
				
			}catch(e) {}	
		},
		
		doGeoCoding: function(latitude,longitude, callback){
			var request = new XMLHttpRequest();
			var that = this;
			
			var data = {language: "en", latlng: latitude+","+longitude, sensor: 'true'};
			$.ajax({
				url: 'http://maps.googleapis.com/maps/api/geocode/json',
				dataType: "json",
				data: data,
				context: {obj:this},
				success: $.proxy(function(data){
					var address = data.results[0];
					for(var i in address.address_components) {
						var type = address.address_components[i].types[0];
						if( type == "locality" || type == "political" ) {
							this.getGismeteoCityInfo(address.address_components[i].short_name, callback);
							break;
						}
					}
				}, this),
				error: $.proxy(function() {
					this.setDefaultCity(callback);
				}, this)
			});
		},
		
		getCity: function() {
			var city = {};
			city['v'] = '';
			if (this.params.tpl == 'v2') {
				city['prefix'] = '';
				city['name'] = this.currentCity.name[this.params.lang];
			}
			if (this.params.tpl == 'v1') {
				city['prefix'] = this.dict.currentCity_prefix[this.params.weather];
				if (this.params.weather == 'forecast') {
					var time = this.currentCity.forecast[0].valid.split('T')[1].split(':');
					city['prefix'] += ' '+ time[0]+':'+time[1];
				}
				city['name'] = this.currentCity.name2[this.params.lang];
				city['v'] ='_v1';		
			}
			return city;			
		},
		getImg: function(data) {
			var cl = data.cl;
			var pt = data.pt;
			var pr = data.pr;
			var st = data.st;
			var tod = 'n';
			var icon = data.icon;
			tod = icon;
			if (cl=="") cl = 0;
			if (cl == 0) {pt = 0; pr = 0, st = 0;}
			if (cl == 3) tod = '';
			if (pr == 3) pr = 2;
			if (pt == 0) pr = 0;
			if (pt == 0) pt = '';
			if (pr == 0 ) pr = '';
			if (pt == 0 && st != 0) pt = '0';
			if (pr == 0 && st != 0) pr = '0';
			if (st == 0) st = '';
			return tod+cl+pt+pr+st;
		},
		
		getGismeteoCityInfo: function(cityName, callback) {
			var data = {startsWith: cityName, lang: "en", where: 'all'};
			
			$.ajax({
				url: 'http://1eb4755a.services.gismeteo.ru/inform-service/40e7e07825d543ebb5d07cf4f2ee6d04/cities/',
				dataType: "xml",
				data: data,
				context: {obj:this},
				success: $.proxy(function(data){
					var obj = $($(data).find('item')[0]);
					this.currentCity.id= obj.attr('id');
					this.currentCity.name = obj.attr('n');
					callback();
				}, this),
				error: $.proxy(function() {
					this.setDefaultCity(callback);
				}, this)
			});
		},
		
		setDefaultCityWithHtml5: function(callback) {
			var that = this;
			
			chrome.extension.sendRequest({ command : "get-location",}, 
				function(obj) {
					if( obj.err > 0 ) {
						that.setDefaultCity(callback);
					}
					else {
						that.doGeoCoding(obj.lat, obj.lng, callback);
					}
				}
			);
		},
		
		getConfig: function (key) {
			var value = localStorage[key];
			try {
				if (value) return $.evalJSON(value);
				else return null;
			}
			catch (err) {return null}
		},		
		setConfig: function(key, val) {
			localStorage.removeItem(key);
			localStorage.setItem(key, $.toJSON(val));
		},
		getDefaultSettings: function() {
			var params = {};
			$.extend(params, this.params);
			params.lang = localStorage['GismeteoLang'] || chrome.i18n.getMessage("lang") || 'en';
			params.deg = localStorage['GismeteoTemper'] || 'F';
			params.press = localStorage['GismeteoPress'] || 'mmHg';
			params.wind = localStorage['GismeteoWind'] || 'm';
			return params;
		},
		setDictFromLang: function(lang) {
			this.dict	 = dict[lang] || dict['en'];
		},
		setDefaultCity: function(callback) {
			$('body').addClass('preloader');
			this.currentCity.id = 4368;
			data = {mode: 'ip', nocache: '1'};
			$.ajax({
				type: "GET",
				url: this.citiesUrl,
				data: data,
				dataType: "xml",
				success: $.proxy(function(data, status, xhr) {
					var f = $(data).find('item');
					if (f.length>0) {
						this.currentCity.id= $(f[0]).attr('id');
						this.currentCity.name = $(f[0]).attr('n');
					}
				}, this),
				error: $.proxy(function() {
					this.currentCity.id = this.dict.default_city_id;				
				}, this), 
				complete: $.proxy(function() {
					if (callback) callback();					
				}, this)
			});
		},
		render: function(isRenderFrc) {
			if (isRenderFrc) this.isRenderFrc = isRenderFrc;
			this.getFrc(function() {
				frcst.utc.time = frcst.getUtcTime();
				if (frcst.isRenderFrc) frcst.renderFrc();
				else frcst.renderDateTime();
				frcst.isRenderFrc = false;
				$(window).trigger('resize');
			  $('body').removeClass('preloader');	
				clearTimeout(frcst.delay);
				frcst.delay = null;
				frcst.delay = setTimeout(function() {frcst.render()}, frcst.utc.delay);
			});
		},
		getFrc: function (callback) {
			if (typeof(this.currentCity.fact) == 'undefined' || this.currentCity.fact.length == 0 ||
					typeof(this.currentCity.forecast) == 'undefined' || this.currentCity.forecast == 0 ||
					!this.currentCity.tzone || !this.currentCity.cur_time ||
					new Date().getTime() - new Date(this.currentCity.cur_time).getTime()<0 ||
					this.updatetime<=new Date().getTime() - new Date(this.currentCity.cur_time).getTime()) {
				$('.content').remove();
				
				$('body').addClass('preloader'); 							
				$.ajax({
					type: "GET",
					url: this.forecastUrl,
					data: {lang: this.params.lang, city: this.currentCity.id, all_langs: 1, ver: this.version},
					dataType: "xml",
					success: $.proxy(function(data, status, xhr) {
						var f = $(data).find('location');
						this.currentCity.fact = this.parseData($(f[0]), 'fact');
						this.currentCity.forecast = this.parseData($(f[0]), 'forecast');
						this.currentCity.cur_time = 	new Date();
						this.currentCity.tzone = $(f[0]).attr('tzone')*60000;
						this.currentCity.name = {};
						this.currentCity.name2 = {};						
						$.each(langs, $.proxy(function(index) {
							this.currentCity.name[langs[index]] = f.attr('name_'+langs[index]);
							this.currentCity.name2[langs[index]] = f.attr('name_'+langs[index]+'_r');					
						}, this));
						this.setConfig('city', this.currentCity);	
						this.isRenderFrc = true;												
						if (callback) callback();
						$(window).trigger('resize');
					}, this),
					error: $.proxy(function() {
						clearTimeout(this.delay);
						this.delay = null;
						this.delay = setTimeout(function(){frcst.render()}, 10000);
					}, this)
				});
			}
			else if (callback) callback();		
		},
		renderFrc: function() {	
			$.extend(listTepmplates.data, this.getCurrentTime(frcst.currentCity.tzone));
			listTepmplates.data.currentDateTime = frcst.dict.weekdays['w'+listTepmplates.data.day]+', '+listTepmplates.data.date+' '+frcst.dict.monthes['m'+listTepmplates.data.month]+', '+listTepmplates.data.hour+':'+listTepmplates.data.minutes;				
			this.setTemplateDate(frcst.currentCity.fact[0], 'fact');		
			if (frcst.params.tpl == 'v1' && frcst.params.weather == 'forecast') {
				this.setTemplateDate(frcst.currentCity.forecast[0], 'fact');	
			}
			$.each(frcst.currentCity.forecast, $.proxy(function(key, val) {
				this.setTemplateDate(val, 'forecast'+key);		
			}, this));
			$('.content').remove();			
			var content = $('<div class="content">');
			$(content)
				.append(listTepmplates.loadTpl(listTepmplates.tpls['city'].html(), frcst.getCity()))
				.append(listTepmplates.loadTpl(listTepmplates.tpls[frcst.params.tpl].html(), listTepmplates.data))
				.insertAfter('.loader');
			$('.fact .img').children('div').hide();
		 	$('.vectIcon').removeClass('c3');
			var t = frcst.params.deg == 'C'?frcst.currentCity.fact[0].t:Math.round(frcst.currentCity.fact[0].t*1.8+32);
			$('.fact .temper').removeClass('padding0'); 
			if (Math.abs(t)>99) $('.fact .temper').addClass('padding0');			  	
			if (frcst.params.icon == 'photorealistic') $('.fact .img').children('div:first').show();
			else {
				$('.fact .vectIcon').addClass('c'+frcst.currentCity.fact[0].cl);
				$('.fact .img').children('div:last').show();
			}		
			$.each(frcst.currentCity.forecast, function(key, val) {
				t = frcst.params.deg == 'C'?val.t:Math.round(val.t*1.8+32);
				$('.forecast .tod:eq('+key+') .temper').removeClass('t'+Math.abs(t)).addClass('t'+Math.abs(t));			
				if(Math.abs(t)>99) $('.forecast .tod:eq('+key+') .temper').removeClass('t100').addClass('t100');
			});
			if (frcst.currentCity.fact[0].pt == 0 || frcst.currentCity.fact[0].pt == '')
				$('.forecast').css({'margin-top': '-4%'});	
			else $('.forecast').css({'margin-top': '-2%'});			
		},
		setTemplateDate: function(data, ident) {
			ident = '_' + ident;
			listTepmplates.data['t'+ident] = frcst.params.deg == 'C'?data.t:Math.round(data.t*1.8+32);
			listTepmplates.data['plus'+ident] = listTepmplates.data['t'+ident]>=0?(listTepmplates.data['t'+ident]!=0?'+':''):'&minus;';
			listTepmplates.data['t'+ident] = Math.abs(listTepmplates.data['t'+ident]);
			listTepmplates.data['sign'+ident] = frcst.dict.params[frcst.params.deg];
			listTepmplates.data['photorealistic'+ident] = frcst.getImg(data);
			listTepmplates.data['press'+ident] = frcst.params.press=='mmHg'?data.p:Math.round(data.p/0.75);
			listTepmplates.data['press_descript'+ident] = frcst.dict.params[frcst.params.press];
			listTepmplates.data['ws'+ident] = data.ws>0?(frcst.params.wind=='m'?data.ws:Math.round(data.ws*3.6)):frcst.dict.wDirs[0];
			listTepmplates.data['ws_descript'+ident] = data.ws>0?frcst.dict.params[frcst.params.wind]:'';
			listTepmplates.data['wd'+ident] = data.ws>0?data.wd:0;
			listTepmplates.data['wd_descript'+ident] = data.ws>0?', '+frcst.dict.wDirs[data.wd]:'';
			listTepmplates.data['hum'+ident] = data.hum;
			listTepmplates.data['hum_descript'+ident] = frcst.dict.hum;
			listTepmplates.data['description'+ident] = frcst.dict.phenomens['cl'+data.cl]+
																	((data.pr != 0 && data.pr != 2)||(data.pt==1 || data.pt==2)?', ':'')+
																	(data.pr != 0 && data.pr != 2?frcst.dict.phenomens['pr'+data.pr]:'')+
																	(data.pt==1 || data.pt==2?' '+frcst.dict.phenomens['pt'+data.pt]:'')+
																	(data.ts==1?', '+frcst.dict.phenomens['ts1']:'');
			var pictName = 'White';
			listTepmplates.data['url'] = 'images/icons/Sprite_Vector_'+pictName+'.svg';
			listTepmplates.data['cl'+ident] = 'c'+data.cl;
			listTepmplates.data['star'+ident] = data.icon=='n'?'n':'d';
			listTepmplates.data['pt'+ident] = (data.pt==1?'r':'s')+data.pt;
			listTepmplates.data['st'+ident] = 'st'+data.st;
			try {
				listTepmplates.data['tod'+ident] = frcst.dict.tods[data.tod];
			}
			catch(err) {} 
		},
		renderDateTime: function() {
			$.extend(listTepmplates.data, this.getCurrentTime(frcst.currentCity.tzone));
			listTepmplates.data.currentDateTime = frcst.dict.weekdays['w'+listTepmplates.data.day]+', '+listTepmplates.data.date+' '+frcst.dict.monthes['m'+listTepmplates.data.month]+', '+listTepmplates.data.hour+':'+listTepmplates.data.minutes;				
			$('.day-time').html(listTepmplates.data.currentDateTime);
		},
		parseData: function(data, item) {
			var d = [];
			$(data).find(item).each($.proxy(function(index, obj){
				var f=$(obj).find('values');
				this.data = {
					tod: $(obj).attr('tod'),
				  valid: $(obj).attr('valid'),
					t:f.attr('t'),																				
					hi:f.attr('hi'),
					p:f.attr('p'),
					cl:f.attr('cl'),
					pt:f.attr('pt'),
					pr:f.attr('pr'),
					st:f.attr('ts'),				
					wd:f.attr('wd') == 0?1:f.attr('wd'),
					ws:f.attr('ws'),
					hum:f.attr('hum'),
					icon:f.attr('icon').indexOf('sun')>-1?'d':'n',
				};
				d.push(this.data);
			}, this));
			return d;
		},
		getUtcTime: function(){
			var now = new Date();
			var now_utc = new Date(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(),  now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds());
			return now_utc.getTime(); 
	  },
		getCurrentTime: function(value) {
			var res = {};
			var now = new Date();
			now.setTime(this.utc.time + value);
			res.day = now.getDay();
			res.date = now.getDate();
			res.month = now.getMonth();
			res.hour = now.getHours();			
			res.minutes = now.getMinutes();
			if (res.minutes.toString().length == 1) res.minutes = '0' + res.minutes;
			return res;	
		},	  	
	};
	
	$(window).resize(function() {
		fontSize(); 
		var h = setFactBlockHeight();
		var r = Math.min($('.fact .img').width(), h); 
		$('.fact .vectIcon').css({'width':r+'px', 'height': r+'px', 'margin-left':Math.round(($('.fact .img').width()-r)/2)+'px'});	
		var n = $('.fact .temper .first span.t').text().length;
		var w = (n==1?$('.fact .temper .first').width():(n==2?$('.fact .temper .first').width()-$('.fact .temper .sign').width():$('.fact .temper .first').width()-$('.fact .temper .sing').width()-$('.fact .temper .first').width()*0.4));
		if ($('.fact .temper .first span.plus').width()-$('.fact .temper .first span.t').width()-$('.fact .temper .first span.sign').width() == 0) w = w + $('.fact .temper .first span.t').width();	
		$('.forecast td').css({'width':w+'px'});	
		w = w-w*0.1;
		$('.forecast .vectIcon').css({'width':w+'px', 'height': w+'px'});
		
		var title = null;
		var url = null;
		if ($('html').height()<=64)
			title = frcst.currentCity.name[frcst.params.lang] || 'Gismeteo';	  
		else 
			title ='Gismeteo';
		if (frcst.currentCity.id) url  = 'http://www.gismeteo.'+frcst.dict.domain+'/city/hourly/'+frcst.currentCity.id+'/?from=speeddial';
		else url  = 'http://www.gismeteo.'+frcst.dict.domain+'/?from=speeddial';
	});
	
	window.addEventListener('storage', function(){clearTimeout(frcst.delay); frcst.delay = null; frcst.delay = setTimeout(function(){frcst.init(function() {frcst.render(true)})}, 100)}, false);
	window.addEventListener('load', function(){	frcst.init(function(){frcst.render(); $(window).trigger('resize');});}, false);			
	
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-35888604-1']);
_gaq.push(['_trackPageview']);
		
var listTepmplates = {
	tpls: {v1: $('.v1'), v2: $('.v2'), city: $('.city_block')},
	loadTpl: function(template, data) {
	return template.replace(/\{([\w\.]*)\}/g, function (str, key) {
	var keys = key.split("."), value = data[keys.shift()];
	$.each(keys, function () { value = value[this]; });
	return (value === null || value === undefined) ? "" : ($.isArray(value) ? value.join('') : value);
  });
},
data: {}		
};