$('.version_trigger *').disableSelection();
var suggest = new GISCitySuggest();
suggest.url = 'http://1eb4755a.services.gismeteo.ru/inform-service/40e7e07825d543ebb5d07cf4f2ee6d04/cities/';
suggest.minLength = 2;
suggest.result_tpl = "<div class=\"city\">@city</div><div class=\"dc\">@district@country</div>";
suggest.loadingClass = 'o';
suggest.setCallback('select', $.proxy(function(event, ui){
	$('.location').val(ui.item.n);	
	settings.city =  {'id':ui.item.id, 'name': ui.item.n, 'name2':{}, 'fact': {}, 'forecast':{}};
	settings.setStorage('city', settings.city);
}, this));
suggest.init($('.location'), 'en');

var templates = {
	tpls: {v1: $('.v1'), v2: $('.v2')},
	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);
    });
  } 			
};				

var settings = {
	citiesUrl: 'http://1eb4755a.services.gismeteo.ru/inform-service/40e7e07825d543ebb5d07cf4f2ee6d04/cities/',
	dict: null,
	city: {},
	params: {
		lang: 'en', 
		deg: 'C', 
		press: 'mmHg', 
		hum: null, 
		wind: 'm',
		colorsheme: 'classic',
		tpl: 'v2',
		weather: 'fact',
		icon: 'photorealistic'		 
	},
	
	setSuggestUrl: function(lang, suggest) {
		suggest.init($('.location'), lang || 'ru');			
	},
	
	getStorage: function (key) {
		var value = localStorage[key];
		if (value) 
			return $.evalJSON(value);
		else return null;
	},
	setStorage: function(key, val) {
		if(typeof(widget)!='undefined' && widget.preferences)
			localStorage = widget.preferences;
		
		localStorage[key] = $.toJSON(val);
	},
	
	translateCity: function(callback) {
		settings.city = settings.getStorage('city');
		data = {lang: this.params.lang, id: this.city.id};
		$.ajax({
	    type: "GET",
			data: data,
			dataType: "xml",		   
	  	url: this.citiesUrl,
	    dataType: "xml",
	    success: $.proxy(function(xmlElement) { 
	    	try {
	    		var items = xmlElement.getElementsByTagName("item");  		
		    	this.city.name[lang] = items[0].getAttribute("n");
		    	if (callback) callback();     	
	    	}	catch(err) { return; }
	    }, this)
		});								
	}
};

$.each(templates.tpls, function(key, val) {
	$(val).remove();
});

document.addEventListener('DOMContentLoaded', function(){
	localize();
	
	var deg = localStorage['GismeteoTemper']|| 'F';
	var press = localStorage['GismeteoPress'] || 'mmHg';
	var wind = localStorage['GismeteoWind'] || 'm';
	
	var $radios = $('input:radio[name=GismeteoPress]');
    if($radios.is(':checked') === false) {
        $radios.filter('[value='+press+']').attr('checked', true);
    }
	
	var $radios = $('input:radio[name=GismeteoTemper]');
    if($radios.is(':checked') === false) {
        $radios.filter('[value='+deg+']').attr('checked', true);
    }
	
	var $radios = $('input:radio[name=GismeteoWind]');
    if($radios.is(':checked') === false) {
        $radios.filter('[value='+wind+']').attr('checked', true);
    }
	
	try {
		var value = localStorage.city;
		
		if (value) {
			var city = $.evalJSON(value);
			$(".location").val(city.name.en);
		}
	}catch(ex){
	}
	
});

function localize() {
	var translation = chrome.i18n.getMessage("settings_title");
	var divHeader = document.getElementById("header");
	divHeader.innerHTML=translation;
	
	var lexems = ["label_city", "label_press", "label_wind", "label_degrees"];
	for(var i in lexems) {
		var translation = chrome.i18n.getMessage(lexems[i]);
		var elm = document.getElementById(lexems[i]);
		elm.innerHTML=translation;
	}
	
	var translation = chrome.i18n.getMessage("placeholder_city");
	var elm = document.getElementById("location");
	elm.setAttribute("placeholder", translation);
}



$('body').delegate('input[type=\'radio\']', 'change', function(event) {
	var obj = event.currentTarget;
	localStorage[$(obj).attr('name')] = $(obj).filter(":checked").val();
});
