/*	
	Currency Converter 2.0.2 Author: Paolo Grifantini 27 Feb 2014
	Contact: paolo.grifantini@gmail.com
	
	Copyright Paolo Grifantini, 2005-2014
	
	Portuguese and Brazilian Portuguese Localizationz by Carlos Eduardo Souza Lopes
	Japanese Localization by Christopher Li
	German Localization by Andreas Köhler & Stephan Hoyer
	Swedish Localization by Jac Lundqvist & Conny Brunnkvist
	French localization by Pierre Godin
	Dutch localization by Johan van Balen Blanken
	Spanish localization by Richard Sypeck
	Greek localization by Nicholas Koumenides
	Russian localization by Mikhail Fedoseev
	Traditional Chinese localization by Patrick Lei
	Polish localization by Cezary Okupski
	Turkish localization by Selcuk Albut
    Serbian localization by Dusan Djordjevic
    Norwegian localization by Odd-Jarle Kristoffersen
	
	Distributed under a Creative Commons License
	Attribution-NonCommercial-NoDerivs 2.5
	
	You are free:
	*	to copy, distribute, display, and perform the work
	
	Under the following conditions:
	* Attribution. You must attribute the work in the manner specified by the author or licensor.
	* Noncommercial. You may not use this work for commercial purposes.
	* No Derivative Works. You may not alter, transform, or build upon this work.
	
	For any reuse or distribution, you must make clear to others the license terms of this work.
	Any of these conditions can be waived if you get permission from the copyright holder.
	
	Your fair use and other rights are in no way affected by the above.
*/

/* remaining bugs

*/

/* to do

*** code cleaning

*/

/* done

*/

var newShow = { show : function(element) { $(element).style.display = 'block'; return element; } }
Element.addMethods(newShow);

Array.prototype.remove = function(from, to) {
  var rest = this.slice((to || from) + 1 || this.length);
  this.length = from < 0 ? this.length + from : from;
  return this.push.apply(this, rest);
};

//**** we start here
window.onload = init;

var current_version = "2.0.2";

var currentURI = "";

var total_errors = 0;

var error_com = false;

var there_is_a_new_version = false;

var error_retrieving_ecb = false;
var error_retrieving_palple = false;
var retrieve_data_done = 0;

// is the flipper showing?
var flipShown = false;
var updateShown = false;

var modifing_an_alement = 0;

var currency_date = "Sat, 11 Jan 2014 01:15:02 GMT";

localizedStrings['author'] = 'Currency Converter v2.0.2<br />by Paolo Grifantini';

var sections = true;
var by_name = true;
var by_country = false; // for compatibility with older release we set it to false and separate from by_name

var label_byname = true;

var show_ad = true;

var defaultFromIndex = "EUR";
var defaultToIndex = "USD"; // ricordati di modificarli

var fetch_from_site = "http://finance.yahoo.com/d?s=searchStringMagic&f=sl1d1t1ba";

var widget_style = 0; // 0 convertitore standard, 1 tabella delle conversioni, 2 convertitore mini

var table_elements = [{currency: 'USD', country:'USD'},{currency: 'EUR', country:'EUR'},{currency: 'LIT', country:'ITA'}];
var last_selected_value = {position:'0',value:'1000'};

var conversion_precision = 2;
var conversion_taxes = 0; // nessuna tassa di default
var inputTaxesVisibility = false;

var decimal_separator = ".";
var thousand_separator = ",";

var mousedown_in_add_var = undefined;
var mousedown_in_remove_var = undefined;

var skins_popup_data = new Array();

var top_height = 22;
var bottom_height = 27;
var ads_height = 21;
var element_height = 32;
var body_width = 336;

var popup_text_decoration = "none";
var button_visibility = "visible";

var new_data_date = 0;

// valute europee legacy
var legacy_euroconversion = [
	{name:'BFR', 		value:'40.3399'},
	{name:'NLG', 		value:'2.20371'},
	{name:'ATS', 		value:'13.7603'},
	{name:'PTE', 		value:'200.482'},
	{name:'FIM', 		value:'5.94573'},
	{name:'DM', 		value:'1.95583'},
	{name:'ESP', 		value:'166.386'},
	{name:'FRF', 		value:'6.55957'},
	{name:'IEP', 		value:'0.787564'},
	{name:'GRD', 		value:'340.750'},
	{name:'LIT', 		value:'1936.27'},
	{name:'SIT',		value:'239.640'},
	{name:'CYP',		value:'0.585274'},
	{name:'MTL',		value:'0.4293'},
    {name:'SKK',		value:'30.1260'},
    {name:'EEK',		value:'15.6466'},
    {name:'LVL',		value:'0.702804'},
    {name:'ADP',		value:'166.39326240000003'}
];


var currency_used_associative = new Array; // altro array codice nazione e valuta, suriettiva e divisa per categorie; è da questo che creo le voci per il popup

currency_used1 = [{country:'AFG',currency:'AFN'},{country:'AKD',currency:'EUR',multiple:'true'},{country:'ALB',currency:'ALL'},{country:'ALD',currency:'GBP',multiple:'true'},{country:'ALG',currency:'DZD'},{country:'AND',currency:'EUR',multiple:'true'},{country:'ANG',currency:'AOA'},{country:'ANL',currency:'XCD'},{country:'ANT',currency:'XCD'},{country:'ARB',currency:'AWG'},{country:'ARG',currency:'ARS'},{country:'AMD',currency:'AMD'},{country:'ASC',currency:'SHP',multiple:'true'},{country:'AUD',currency:'AUD'},{country:'AUT',currency:'EUR',multiple:'true'},{country:'AZE',currency:'AZN'},{country:'BAH',currency:'BSD'},{country:'BAN',currency:'BDT'},{country:'BAR',currency:'BBD'},{country:'BEL',currency:'BYR'},{country:'BEN',currency:'XOF',multiple:'true'},{country:'BER',currency:'BMD'},{country:'BHR',currency:'BHD'},{country:'BHU',currency:'BTN'},{country:'BHU',currency:'INR',multiple:'true'},{country:'BIO',currency:'GBP',multiple:'true'},{country:'BIO',currency:'USD',multiple:'true'},{country:'BLG',currency:'EUR',multiple:'true'},{country:'BLZ',currency:'BZD'},{country:'BOL',currency:'BOB'},{country:'BOS',currency:'BAM'},{country:'BOT',currency:'BWP'},{country:'BRA',currency:'BRL'},{country:'BRD',currency:'BIF'},{country:'BND',currency:'BND'},{country:'SGD',currency:'SGD'},{country:'BUL',currency:'BGN'},{country:'BUR',currency:'XOF',multiple:'true'},{country:'BVI',currency:'USD',multiple:'true'},{country:'CAM',currency:'KHR'},{country:'CMR',currency:'XAF',multiple:'true'},{country:'CAN',currency:'CAD'},{country:'CAP',currency:'CVE'},{country:'CAY',currency:'KYD'},{country:'CAR',currency:'XAF',multiple:'true'},{country:'CHA',currency:'XAF',multiple:'true'},{country:'CHL',currency:'CLP'},{country:'CHI',currency:'CNY'},{country:'COC',currency:'AUD',multiple:'true'},{country:'COL',currency:'COP'},{country:'COM',currency:'KMF'},{country:'CON',currency:'CDF'},{country:'CRP',currency:'XAF',multiple:'true'},{country:'COK',currency:'NZD',multiple:'true'},{country:'CSR',currency:'CRC'},{country:'COT',currency:'XOF',multiple:'true'},{country:'CRO',currency:'HRK'},{country:'CUB',currency:'CUP'},{country:'CYP',currency:'EUR',multiple:'true'},{country:'CZE',currency:'CZK'},{country:'DKK',currency:'DKK'},{country:'DJI',currency:'DJF'},{country:'DOM',currency:'XCD'},{country:'DMR',currency:'DOP'},{country:'EST',currency:'USD',multiple:'true'},{country:'ECU',currency:'USD',multiple:'true'},{country:'EGY',currency:'EGP'},{country:'ELS',currency:'SVC'},{country:'ELS',currency:'USD',multiple:'true'},{country:'EQU',currency:'XAF',multiple:'true'},{country:'ERI',currency:'ERN'},{country:'ESN',currency:'EUR',multiple:'true'},{country:'ETH',currency:'ETB'},{country:'FAR',currency:'DKK'},{country:'FIJ',currency:'FJD'},{country:'FIN',currency:'EUR',multiple:'true'},{country:'FRA',currency:'EUR',multiple:'true'},{country:'FRE',currency:'XPF',multiple:'true'},{country:'GAB',currency:'XAF',multiple:'true'},{country:'GAM',currency:'GMD'},{country:'GEL',currency:'GEL'},{country:'GER',currency:'EUR',multiple:'true'},{country:'GHA',currency:'GHS',multiple:'true'},{country:'GIB',currency:'GIP'},{country:'GRE',currency:'EUR',multiple:'true'},{country:'GRN',currency:'XCD'},{country:'GUA',currency:'GTQ'},{country:'GUE',currency:'GBP',multiple:'true'},{country:'GUI',currency:'GNF'},{country:'GUB',currency:'XOF',multiple:'true'},{country:'GUY',currency:'GYD'},{country:'HAI',currency:'HTG'},{country:'HON',currency:'HNL'},{country:'HKG',currency:'HKD'},{country:'HUN',currency:'HUF'},{country:'ICE',currency:'ISK'},{country:'INR',currency:'INR'},{country:'IDN',currency:'IDR'},{country:'IRA',currency:'IRR'},{country:'IRQ',currency:'IQD'},{country:'IRE',currency:'EUR',multiple:'true'},{country:'ISM',currency:'GBP',multiple:'true'},{country:'ILS',currency:'ILS'},{country:'ITA',currency:'EUR',multiple:'true'},{country:'LAT',currency:'EUR',multiple:'true'},{country:'JAM',currency:'JMD'},{country:'JAP',currency:'JPY'},{country:'JER',currency:'GBP',multiple:'true'},{country:'JOD',currency:'JOD'},{country:'KAZ',currency:'KZT'},{country:'KEN',currency:'KES'},{country:'KIR',currency:'AUD',multiple:'true'},{country:'KOR',currency:'KPW'},{country:'KOS',currency:'KRW'},{country:'KSV',currency:'EUR',multiple:'true'},{country:'KSV',currency:'RSD',multiple:'true'},{country:'KUW',currency:'KWD'},{country:'KYR',currency:'KGS'},{country:'LAO',currency:'LAK'},{country:'LEB',currency:'LBP'},{country:'LES',currency:'LSL'},{country:'LES',currency:'ZAR',multiple:'true'},{country:'LIB',currency:'LRD'},{country:'LBY',currency:'LYD'},{country:'LIE',currency:'CHF',multiple:'true'},{country:'LUX',currency:'EUR',multiple:'true'}];
currency_used2 = [{country:'XCD',currency:'XCD'},{country:'XAF',currency:'XAF'},{country:'XPF',currency:'XPF'},{country:'XOF',currency:'XOF'},{country:'EUR',currency:'EUR'},{country:'MAC',currency:'MOP'},{country:'MRP',currency:'MKD'},{country:'MAD',currency:'MGA'},{country:'MAL',currency:'MWK'},{country:'MLY',currency:'MYR'},{country:'MLD',currency:'MVR'},{country:'MLI',currency:'XOF',multiple:'true'},{country:'MLT',currency:'EUR',multiple:'true'},{country:'MAR',currency:'USD',multiple:'true'},{country:'MAU',currency:'MRO'},{country:'MRT',currency:'MUR'},{country:'MEX',currency:'MXN'},{country:'MIC',currency:'USD',multiple:'true'},{country:'MOL',currency:'MDL'},{country:'MON',currency:'EUR',multiple:'true'},{country:'MNG',currency:'MNT'},{country:'MTR',currency:'EUR',multiple:'true'},{country:'MSR',currency:'XCD'},{country:'MOR',currency:'MAD'},{country:'MOZ',currency:'MZN'},{country:'MYA',currency:'MMK'},{country:'NAG',currency:'AMD'},{country:'NAM',currency:'NAD'},{country:'NAM',currency:'ZAR',multiple:'true'},{country:'NAU',currency:'AUD',multiple:'true'},{country:'NEP',currency:'NPR'},{country:'NET',currency:'EUR',multiple:'true'},{country:'NAN',currency:'ANG'},{country:'NCL',currency:'XPF',multiple:'true'},{country:'NZD',currency:'NZD'},{country:'NIC',currency:'NIO'},{country:'NIG',currency:'XOF',multiple:'true'},{country:'NGR',currency:'NGN'},{country:'NIU',currency:'NZD',multiple:'true'},{country:'NCP',currency:'TRY',multiple:'true'},{country:'NMI',currency:'USD',multiple:'true'},{country:'NOR',currency:'NOK'},{country:'OMA',currency:'OMR'},{country:'PAK',currency:'PKR'},{country:'PAL',currency:'USD',multiple:'true'},{country:'PLS',currency:'ILS',multiple:'true'},{country:'PLS',currency:'JOD',multiple:'true'},{country:'PAN',currency:'PAB'},{country:'PNG',currency:'PGK'},{country:'PAR',currency:'PYG'},{country:'PER',currency:'PEN'},{country:'PHI',currency:'PHP'},{country:'PIT',currency:'NZD',multiple:'true'},{country:'POL',currency:'PLN'},{country:'POR',currency:'EUR',multiple:'true'},{country:'QAT',currency:'QAR'},{country:'ROM',currency:'RON'},{country:'RUB',currency:'RUB'},{country:'RWA',currency:'RWF'},{country:'SHP',currency:'SHP'},{country:'SKN',currency:'XCD'},{country:'SLC',currency:'XCD'},{country:'SVG',currency:'XCD'},{country:'SAM',currency:'WST'},{country:'SMR',currency:'EUR',multiple:'true'},{country:'STP',currency:'STD'},{country:'SAR',currency:'SAR'},{country:'SEN',currency:'XOF',multiple:'true'},{country:'RSD',currency:'RSD'},{country:'SEY',currency:'SCR'},{country:'SLN',currency:'SLL'},{country:'SGD',currency:'BND',multiple:'true'},{country:'SLO',currency:'EUR',multiple:'true'},{country:'SLV',currency:'EUR',multiple:'true'},{country:'SOL',currency:'SBD'},{country:'SOM',currency:'SOS'},{country:'ZAR',currency:'ZAR'},{country:'SGS',currency:'GBP',multiple:'true'},{country:'SPA',currency:'EUR',multiple:'true'},{country:'SRI',currency:'LKR'},{country:'SUD',currency:'SDG'},{country:'SUR',currency:'SRD'},{country:'SWA',currency:'SZL'},{country:'SWE',currency:'SEK'},{country:'SWI',currency:'CHF'},{country:'SYR',currency:'SYP'},{country:'TAI',currency:'TWD'},{country:'TAJ',currency:'TJS'},{country:'TAN',currency:'TZS'},{country:'THA',currency:'THB'},{country:'TOG',currency:'XOF',multiple:'true'},{country:'TON',currency:'TOP'},{country:'TRI',currency:'TTD'},{country:'TRC',currency:'SHP',multiple:'true'},{country:'TUN',currency:'TND'},{country:'TRY',currency:'TRY'},{country:'TUR',currency:'TMT'},{country:'TCI',currency:'USD',multiple:'true'},{country:'TUV',currency:'AUD',multiple:'true'},{country:'UGA',currency:'UGX'},{country:'UKR',currency:'UAH'},{country:'UAE',currency:'AED'},{country:'GBP',currency:'GBP'},{country:'USD',currency:'USD'},{country:'URU',currency:'UYU'},{country:'UZB',currency:'UZS'},{country:'VAN',currency:'VUV'},{country:'VAT',currency:'EUR',multiple:'true'},{country:'VEN',currency:'VEF'},{country:'VIE',currency:'VND'},{country:'WAL',currency:'XPF',multiple:'true'},{country:'WES',currency:'MAD'},{country:'YEM',currency:'YER'},{country:'ZAM',currency:'ZMW'},{country:'ZIM',currency:'ZWD'},{country:'CLF',currency:'CLF'},{country:'SDR',currency:'SDR'},{country:'UDI',currency:'UDI'},{country:'LIT',currency:'LTL'}];

currency_used_associative = currency_used1.concat(currency_used2);

commodities_associative = [{country:'XAU',currency:'XAU'},{country:'XPD',currency:'XPD'},{country:'XAG',currency:'XAG'},{country:'XPT',currency:'XPT'}];

unrecognized_currencies_associative = [{country:'TRA',currency:'PRB'},{country:'GUE',currency:'GGP'},{country:'COK',currency:'CKD'},{country:'ISM',currency:'IMP'},{country:'JER',currency:'JEP'},{country:'TUV',currency:'TVD'},{country:'SML',currency:'SLSH'},{country:'KIR',currency:'KIR'},{country:'FAL',currency:'FKP'},{country:'FAR',currency:'FIK'},{country:'BVI',currency:'USD_BVI'},{country:'COC',currency:'AUD_COC'},{country:'MIC',currency:'USD_MCR'},{country:'NAG',currency:'AMD_NAG'},{country:'NAU',currency:'AUD_NAU'},{country:'NIU',currency:'NZD_NID'},{country:'NMI',currency:'USD_NMI'},{country:'PAL',currency:'USD_PAL'},{country:'SGS',currency:'GBP_SGS'},{country:'TRC',currency:'GBP_TRC'},{country:'ALD',currency:'GBP_ALD'}];

old_currencies_associative = [{country:'GHA',currency:'GHC'},{country:'ZAM',currency:'ZMK'},{country:'TUR',currency:'TMM'},{country:'VEN',currency:'VEB'},{country:'MAD',currency:'MGF'},{country:'AND',currency:'ADP'},{country:'SUR',currency:'SRG'},{country:'ZRN',currency:'ZRN'},{country:'BRA',currency:'BRC'},{country:'ECU',currency:'ECS'},{country:'SUD',currency:'SDD'}];

european_legacy_associative = [{country:'LAT',currency:'LVL'},{country:'CYP',currency:'CYP'},{country:'ESN',currency:'EEK'},{country:'AKD',currency:'CYP'},{country:'MLT',currency:'MTL'},{country:'BLG',currency:'BFR'},{country:'NET',currency:'NLG'},{country:'AUT',currency:'ATS'},{country:'POR',currency:'PTE'},{country:'FIN',currency:'FIM'},{country:'GER',currency:'DM'},{country:'SPA',currency:'ESP'},{country:'FRA',currency:'FRF'},{country:'IRE',currency:'IEP'},{country:'GRE',currency:'GRD'},{country:'ITA',currency:'LIT'},{country:'SLV',currency:'SIT'},{country:'SLO',currency:'SKK'}];

virtual_currencies_associative = [{country:'LND',currency:'LND'},{country:'DOGE',currency:'DOGE'},{country:'BTC',currency:'BTC'},{country:'BTCR',currency:'BTCR'},{country:'BTCB',currency:'BTCB'},{country:'DMS',currency:'DMS'},{country:'LTC',currency:'LTC'},{country:'PPC',currency:'PPC'},{country:'MSC',currency:'MSC'},{country:'NXT',currency:'NXT'},{country:'QRK',currency:'QRK'},{country:'MEC',currency:'MEC'},{country:'FTC',currency:'FTC'},{country:'NVC',currency:'NVC'},{country:'XRP',currency:'XRP'}];

all_currencies_associative = currency_used_associative.concat(commodities_associative,unrecognized_currencies_associative,old_currencies_associative,european_legacy_associative,virtual_currencies_associative);

var ecb_euroconversion_associative;

// array con i simboli delle valute!!!
var currency_sign = [{name:'EUR',sign:'€'},{name:'BFR',sign:'fr'},{name:'NLG',sign:'ƒ'},{name:'ATS',sign:'öS'},{name:'PTE',sign:'$'},{name:'FIM',sign:'mk'},{name:'DM',sign:'DM'},{name:'ESP',sign:'₧'},{name:'FRF',sign:'₣'},{name:'IEP',sign:'IR£'},{name:'GRD',sign:'₯'},{name:'LIT',sign:'₤'},{name:'ALL',sign:'L'},{name:'BYR',sign:'Br'},{name:'BGN',sign:'лв'},{name:'CYP',sign:'£'},{name:'HRK',sign:'kn'},{name:'DKK',sign:'kr'},{name:'EEK',sign:'KR'},{name:'GIP',sign:'£'},{name:'GBP',sign:'£'},{name:'ISK',sign:'Íkr'},{name:'LTL',sign:'Lt'},{name:'MTL',sign:'₤'},{name:'MDL',sign:'L'},{name:'NOK',sign:'kr'},{name:'PLN',sign:'zł'},{name:'CZK',sign:'Kč'},{name:'RON',sign:'L'},{name:'RSD',sign:'дин'},{name:'SKK',sign:'Sk'},{name:'SIT',sign:''},{name:'SEK',sign:'kr'},{name:'CHF',sign:'Fr'},{name:'TRY',sign:'₤'},{name:'UAH',sign:'₴'},{name:'HUF',sign:'Ft'},{name:'SAR',sign:'ر.س'},{name:'ARS',sign:'$'},{name:'AUD',sign:'$'},{name:'BRL',sign:'R$'},{name:'CLP',sign:'$'},{name:'CAD',sign:'C$'},{name:'USD',sign:'$'},{name:'AED',sign:'د.إ'},{name:'JPY',sign:'¥'},{name:'HKD',sign:'HK$'},{name:'INR',sign:'₨'},{name:'ILS',sign:'₪'},{name:'MXN',sign:'$'},{name:'NZD',sign:'$'},{name:'CNY',sign:'Ұ'},{name:'RUB',sign:'руб.'},{name:'SGD',sign:'S$'},{name:'ZAR',sign:'R'},{name:'KRW',sign:'₩'},{name:'TWD',sign:'$'},{name:'UYU',sign:'$'},{name:'VEB',sign:'Bs'},{name:'VEF',sign:'BsF'},{name:'AFN',sign:'؋'},{name:'DZD',sign:'د.ج'},{name:'BHD',sign:'ب.د'},{name:'BOB',sign:'Bs'},{name:'BND',sign:'$'},{name:'COP',sign:'$'},{name:'CRC',sign:'₡'},{name:'CUP',sign:'$'},{name:'DOP',sign:'$'},{name:'ECS',sign:'S/.'},{name:'EGP',sign:'LE'},{name:'SVC',sign:'₡'},{name:'FJD',sign:'$'},{name:'PHP',sign:'₱'},{name:'JMD',sign:'$'},{name:'JOD',sign:'د.ا'},{name:'GNF',sign:'Fr'},{name:'GYD',sign:'$'},{name:'HNL',sign:'L'},{name:'IDR',sign:'Rp'},{name:'IRR',sign:'﷼'},{name:'KES',sign:'Sh'},{name:'KWD',sign:'د.ك'},{name:'LBP',sign:'ل.ل'},{name:'LYD',sign:'ل.د'},{name:'MVR',sign:'ރ.'},{name:'MYR',sign:'RM'},{name:'MUR',sign:'₨'},{name:'MAD',sign:'د.م.'},{name:'MNT',sign:'₮'},{name:'NPR',sign:'₨'},{name:'NIO',sign:'C$'},{name:'NGN',sign:'₦'},{name:'OMR',sign:'ر.ع.'},{name:'PKR',sign:'₨'},{name:'PAB',sign:'B/'},{name:'PYG',sign:'₲'},{name:'PEN',sign:'S/.'},{name:'SBD',sign:'$'},{name:'SCR',sign:'₨'},{name:'SYP',sign:'ل.س'},{name:'LKR',sign:'ூ'},{name:'TZS',sign:'Sh'},{name:'THB',sign:'฿'},{name:'TND',sign:'د.ت'},{name:'YER',sign:'﷼'},{name:'ETB',sign:'Br'},{name:'GHC',sign:'₵'},{name:'GMD',sign:'D'},{name:'SDD',sign:'LSd'},{name:'VND',sign:'₫'},{name:'BSD',sign:'$'},{name:'BBD',sign:'$'},{name:'BZD',sign:'$'},{name:'BMD',sign:'$'},{name:'KYD',sign:'$'},{name:'NAD',sign:'$'},{name:'TTD',sign:'$'},{name:'ZWD',sign:'$'},{name:'BIF',sign:'Fr'},{name:'KMF',sign:'Fr'},{name:'XOF',sign:'CFA'},{name:'XPF',sign:'F'},{name:'MGF',sign:'Fr'},{name:'MWK',sign:'MK'},{name:'ZMK',sign:'ZK'},{name:'ZMW',sign:'ZK'},{name:'SZL',sign:'L'},{name:'LSL',sign:'L'},{name:'MZM',sign:'MTn'},{name:'BTN',sign:'Nu'},{name:'SDR',sign:''},{name:'UDI',sign:''},{name:'CLF',sign:''},{name:'XCD',sign:''},{name:'XAU',sign:''},{name:'XPD',sign:''},{name:'XAG',sign:''},{name:'XPT',sign:''},{name:'MRO',sign:'UM'},{name:'MOP',sign:'P'},{name:'TOP',sign:'T$'},{name:'GTQ',sign:'Q'},{name:'QAR',sign:'ر.ق'},{name:'UGX',sign:'Sh'},{name:'BDT',sign:'৳'},{name:'WST',sign:'T'},{name:'KZT',sign:'〒'},{name:'VUV',sign:'Vt'},{name:'HTG',sign:'G'},{name:'SRG',sign:'ƒ'},{name:'ANG',sign:'ƒ'},{name:'PGK',sign:'K'},{name:'SLL',sign:'Le'},{name:'LVL',sign:'Ls'},{name:'AOA',sign:'Kz'},{name:'BWP',sign:'P'},{name:'CVE',sign:'$'},{name:'DJF',sign:'Fr'},{name:'ERN',sign:'Nfk'},{name:'IQD',sign:'ع.د'},{name:'KHR',sign:'៛'},{name:'KPW',sign:'₩'},{name:'LRD',sign:'$'},{name:'MMK',sign:'K'},{name:'SHP',sign:'£'},{name:'SOS',sign:'Sh'},{name:'ZRN',sign:'Z'},{name:'YUM',sign:'дин'},{name:'TMM',sign:'m'},{name:'TMT',sign:'m'},{name:'TJS',sign:'ЅМ'},{name:'KGS',sign:'сом'},{name:'GEL',sign:'ლ'},{name:'CDF',sign:'Fr'},{name:'BRC',sign:'₢'},{name:'BAM',sign:''},{name:'AZN',sign:'ман'},{name:'AWG',sign:'ƒ'},{name:'AMD',sign:'դր.'},{name:'ADP',sign:'₧'},{name:'STD',sign:'Db'},{name:'CUC',sign:'CUC$'},{name:'XCD',sign:'EC$'},{name:'CSD',sign:'дин'},{name:'RWF',sign:'RF'},{name:'MGA',sign:''},{name:'LAK',sign:'₭'},{name:'XAF',sign:'Fr'},{name:'MKD',sign:'ден'},{name:'SRD',sign:'$'},{name:'UZS',sign:'so‘m'},{name:'LND',sign:'L$'},{name:'GHC',sign:'₵'},{name:'SDG',sign:'£'},{name:'PRB',sign:'p.'},{name:'GGP',sign:'£'},{name:'CKD',sign:'$'},{name:'FIK',sign:'kr'},{name:'IMP',sign:'£'},{name:'JEP',sign:'£'},{name:'TVD',sign:'$'},{name:'SLSH',sign:'Sh'},{name:'KIR',sign:'$'},{name:'FKP',sign:'£'},{name:'USD_BVI',sign:'$'},{name:'AUD_COC',sign:'$'},{name:'USD_MCR',sign:'$'},{name:'AMD_NAG',sign:'դր.'},{name:'AUD_NAU',sign:'$'},{name:'NZD_NID',sign:'$'},{name:'USD_NMI',sign:'$'},{name:'USD_PAL',sign:'$'},{name:'GBP_SGS',sign:'£'},{name:'GBP_TRC',sign:'£'},{name:'GBP_ALD',sign:'£'},{name:'BTC',sign:'฿'},{name:'BTCR',sign:'฿'},{name:'BTCB',sign:'฿'},{name:'DMS',sign:'dm'},{name:'LTC',sign:'Ł'},{name:'PPC',sign:'Ᵽ'},{name:'MSC',sign:'MSC'},{name:'NXT',sign:'NXT'},{name:'QRK',sign:'QRK'},{name:'MEC',sign:'MEC'},{name:'FTC',sign:'FTC'},{name:'NVC',sign:'NVC'},{name:'XRP',sign:'XRP'},{name:'DOGE',sign:'Ɖ'}];
for (i=0; i<currency_sign.length; i++){
	currency_sign[currency_sign[i].name] = currency_sign[i];
}

function setToDefault() {
	euroconversion = [{name:'ALL',value:'140.73390733907337'},{name:'DKK',value:'7.461391280579472'},{name:'NOK',value:'8.400574005740058'},{name:'SEK',value:'8.864425310919776'},{name:'EUR',value:'1'},{name:'HUF',value:'298.4283176165095'},{name:'CHF',value:'1.2335656689900232'},{name:'UAH',value:'11.322946562798961'},{name:'CZK',value:'27.389367227005604'},{name:'ISK',value:'2.225620596391964'},{name:'HRK',value:'7.641109744430778'},{name:'MDL',value:'17.82834495011617'},{name:'RON',value:'4.545305453054531'},{name:'BGN',value:'1.977859778597786'},{name:'LTL',value:'3.4571545715457153'},{name:'TRY',value:'2.957769577695777'},{name:'BYR',value:'13079.130791307913'},{name:'GBP',value:'0.8291649583162498'},{name:'GIP',value:'0.8290282902829028'},{name:'PLN',value:'4.149104824381577'}];
	
	extraeu_main_euroconversion = [{name:'SAR',value:'5.12573459067924'},{name:'VEF',value:'8.599289326226595'},{name:'USD',value:'1.3666803334700013'},{name:'AUD',value:'1.5193385267186004'},{name:'CAD',value:'1.4892715593822603'},{name:'HKD',value:'10.597785977859779'},{name:'SGD',value:'1.7276206095394286'},{name:'NZD',value:'1.6464397977313108'},{name:'AED',value:'5.019680196801968'},{name:'TWD',value:'40.990843241765745'},{name:'ARS',value:'9.059723930572638'},{name:'CLP',value:'723.8349050157168'},{name:'MXN',value:'17.716960502938363'},{name:'ZAR',value:'14.546808801421347'},{name:'LSL',value:'14.561978953122864'},{name:'BRL',value:'3.230832308323083'},{name:'RUB',value:'45.127647943146094'},{name:'INR',value:'83.99617329506628'},{name:'ILS',value:'4.761650949842832'},{name:'KRW',value:'1448.202815361487'},{name:'JPY',value:'142.31242312423123'},{name:'CNY',value:'8.271559382260488'}];
	
	extraeu_euroconversion = [{name:'PAB',value:'1.0'},{name:'ETB',value:'26.19857865245319'},{name:'BOB',value:'9.443761104277709'},{name:'GHC',value:'19628.6475'},{name:'GHS',value:'3.228782287822878'},{name:'CRC',value:'3.58522282163455'},{name:'SVC',value:'11.955036217028837'},{name:'NIO',value:'34.87084870848709'},{name:'GMD',value:'52.00218668853355'},{name:'DZD',value:'108.28208282082821'},{name:'BHD',value:'0.5152384857181905'},{name:'JOD',value:'0.964056307229739'},{name:'KWD',value:'0.38649719830531637'},{name:'SDG',value:'7.779827798277982'},{name:'TND',value:'2.2604892715593823'},{name:'MAD',value:'11.190515238485718'},{name:'BZD',value:'2.7196938636053027'},{name:'BND',value:'1.7277572775727756'},{name:'NAD',value:'14.541478748120815'},{name:'BSD',value:'1.3666803334700013'},{name:'BBD',value:'2.7333606669400026'},{name:'BMD',value:'1.3666803334700013'},{name:'FJD',value:'2.5674456744567444'},{name:'KYD',value:'1.120677873445401'},{name:'ZWD',value:'17270832498.5856'},{name:'TTD',value:'8.760420937542708'},{name:'JMD',value:'145.14145141451414'},{name:'VND',value:'28821.921552548858'},{name:'XOF',value:'658.3025830258302'},{name:'XAF',value:'655.8036080360803'},{name:'BIF',value:'2107.421074210742'},{name:'RWF',value:'926.609266092661'},{name:'GNF',value:'9607.76274429411'},{name:'KMF',value:'491.85267186005194'},{name:'HTG',value:'60.04892715593823'},{name:'PYG',value:'6307.2977996446625'},{name:'ANG',value:'2.4463577969113026'},{name:'PGK',value:'3.4437611042777094'},{name:'MWK',value:'594.5059450594506'},{name:'ZMW',value:'7.544075440754407'},{name:'HNL',value:'27.442941096077625'},{name:'SLL',value:'298.4622679199125'},{name:'SZL',value:'14.593412600792675'},{name:'MZN',value:'41.13024463577969'},{name:'NGN',value:'217.9171791717917'},{name:'BTN',value:'84.65901325679923'},{name:'MRO',value:'397.0206368730354'},{name:'TOP',value:'2.5462621292879595'},{name:'MOP',value:'10.915539155391555'},{name:'COP',value:'2631.2696460297934'},{name:'DOP',value:'58.28891622249556'},{name:'PHP',value:'60.91294246275796'},{name:'EGP',value:'9.518518518518517'},{name:'LBP',value:'2062.320623206232'},{name:'GTQ',value:'10.771491048243815'},{name:'QAR',value:'4.976356430230969'},{name:'OMR',value:'0.5261719283859505'},{name:'IRR',value:'33083.23083230832'},{name:'YER',value:'293.80210468771355'},{name:'MYR',value:'4.4669946699467'},{name:'MVR',value:'20.89654229875632'},{name:'MUR',value:'41.68375017083504'},{name:'NPR',value:'135.46535465354654'},{name:'SCR',value:'16.509498428317617'},{name:'LKR',value:'178.62511958452916'},{name:'IDR',value:'16618.832854995217'},{name:'PKR',value:'144.18477518108514'},{name:'UGX',value:'3434.4676780101136'},{name:'TZS',value:'2209.238759054257'},{name:'KES',value:'118.46385130517973'},{name:'PEN',value:'3.823971573049064'},{name:'BDT',value:'106.36873035397021'},{name:'WST',value:'3.180265135984693'},{name:'KZT',value:'211.36394697280306'},{name:'THB',value:'45.10045100451004'},{name:'MNT',value:'2326.773267732677'},{name:'VUV',value:'130.51797184638514'}];
	
	virtual_currencies = [{name:'LND',value:'317.3431734317343'},{name:'DOGE',value:'952.38'},{name:'DMS',value:'436.69536695366946'},{name:'BTC',value:'0.0014206803952986197'},{name:'BTCR',value:'0.0016078592158553907'},{name:'BTCB',value:'0.00150711357608'},{name:'LTC',value:'0.04924368787863879'},{name:'PPC',value:'0.19434752329643296'},{name:'MSC',value:'0.008991648071504715'},{name:'NXT',value:'28.521991473554735'},{name:'QRK',value:'14.905890203498702'},{name:'MEC',value:'1.5190056297116306'},{name:'FTC',value:'3.303907896036627'},{name:'NVC',value:'0.0775057498798688'},{name:'XRP',value:'0.034819881107557744'}];
	for (i=0; i<virtual_currencies.length; i++){
		virtual_currencies[virtual_currencies[i].name] = virtual_currencies[i];
	}
	
	unrecognized_currencies = [{name:'PRB',value:'15.170151701517014'},{name:'GGP',value:'11.4'},{name:'FIK',value:'11.4'},{name:'CKD',value:'11.4'},{name:'IMP',value:'11.4'},{name:'JEP',value:'0.8291705344880943'},{name:'TVD',value:'11.4'},{name:'SLSH',value:'11.4'},{name:'KIR',value:'11.4'},{name:'FKP',value:'0.8291705344880943'},{name:'USD_BVI',value:'11.4'},{name:'AUD_COC',value:'11.4'},{name:'USD_MCR',value:'11.4'},{name:'AMD_NAG',value:'11.4'},{name:'AUD_NAU',value:'11.4'},{name:'NZD_NID',value:'11.4'},{name:'USD_NMI',value:'11.4'},{name:'USD_PAL',value:'11.4'},{name:'GBP_SGS',value:'11.4'},{name:'GBP_TRC',value:'11.4'},{name:'GBP_ALD',value:'11.4'}];
	for (i=0; i<unrecognized_currencies.length; i++){
		unrecognized_currencies[unrecognized_currencies[i].name] = unrecognized_currencies[i];
	}
	
	old_currencies = [{name:'VEB',value:'12600'},{name:'MGF',value:'12600'},{name:'SRG',value:'3717.2790000000004'},{name:'ZRN',value:'11.4'},{name:'BRC',value:'11.4'},{name:'ECS',value:'33857.4922'},{name:'SDD',value:'317.4275'},{name:'ZMK',value:'4374.181'}];
	
	commodities_currencies = [{name:'XAU',value:'0.001094351069760831'},{name:'XAG',value:'0.06765409303840371'},{name:'XPD',value:'0.0018341009641929752'},{name:'XPT',value:'0.0009525896239428727'}];
	for (i=0; i<commodities_currencies.length; i++){
		commodities_currencies[commodities_currencies[i].name] = commodities_currencies[i];
	}
	
	// valute extraeu palple
	palple_eur = '0.7317';
	
	palple_extraeu = [{name:'SBD',value:'9.853765204318709'},{name:'AFN',value:'75.76875768757687'},{name:'UYU',value:'28.76862101954353'},{name:'XPF',value:'119.58452917862512'},{name:'MGA',value:'3097.580975809758'},{name:'LYD',value:'1.6979636463031296'},{name:'MKD',value:'61.68511685116851'},{name:'IQD',value:'1591.1439114391144'},{name:'RSD',value:'115.19816864835315'},{name:'STD',value:'24566.078994123272'},{name:'XCD',value:'3.690036900369004'},{name:'SRD',value:'4.49296159628263'},{name:'GYD',value:'280.78447451141176'},{name:'LRD',value:'115.48448817821512'},{name:'AMD',value:'553.437201038677'},{name:'AWG',value:'2.4464944649446494'},{name:'CDF',value:'1262.8126281262812'},{name:'DJF',value:'245.66078994123274'},{name:'LAK',value:'10981.0028700287'},{name:'AOA',value:'133.41670083367498'},{name:'MMK',value:'1348.9134891348913'},{name:'GEL',value:'2.3897772311056444'},{name:'TMM',value:'19491.8625'},{name:'AZN',value:'1.072024053573869'},{name:'BAM',value:'1.9600929342626758'},{name:'ERN',value:'20.59587262539292'},{name:'CUP',value:'1.3666803334700013'},{name:'SYP',value:'195.36695366953668'},{name:'BWP',value:'12.169878365450321'},{name:'KHR',value:'5468.77135438021'},{name:'SOS',value:'1532.0486538198716'},{name:'CVE',value:'110.0861008610086'},{name:'KGS',value:'67.44253109197759'},{name:'TJS',value:'6.524805248052481'},{name:'SHP',value:'0.8290282902829028'},{name:'UZS',value:'3009.703430367637'},{name:'KPW',value:'1230.0123001230013'},{name:'CLF',value:'0.03102364356976903'},{name:'SDR',value:'0.8873787667455967'},{name:'UDI',value:'5.990116077000001'}];
	
	// tassi di cambio della bce
	ecb_euroconversion = [{name:'ecb_AUD',value:'1.5265'},{name:'ecb_BRL',value:'3.2511'},{name:'ecb_BGN',value:'1.9558'},{name:'ecb_CAD',value:'1.4777'},{name:'ecb_CNY',value:'8.2230'},{name:'ecb_KRW',value:'1443.48'},{name:'ecb_HRK',value:'7.6290'},{name:'ecb_DKK',value:'7.4621'},{name:'ecb_PHP',value:'60.746'},{name:'ecb_JPY',value:'142.67'},{name:'ecb_GBP',value:'0.82800'},{name:'ecb_HKD',value:'10.5367'},{name:'ecb_IDR',value:'16325.80'},{name:'ecb_LVL',value:'0.7087'},{name:'ecb_LTL',value:'3.4528'},{name:'ecb_MYR',value:'4.4423'},{name:'ecb_MXN',value:'17.7718'},{name:'ecb_NOK',value:'8.4025'},{name:'ecb_NZD',value:'1.6527'},{name:'ecb_PLN',value:'4.1749'},{name:'ecb_CZK',value:'27.392'},{name:'ecb_RON',value:'4.5450'},{name:'ecb_RUB',value:'45.1468'},{name:'ecb_SGD',value:'1.7255'},{name:'ecb_USD',value:'1.3587'},{name:'ecb_ZAR',value:'14.6297'},{name:'ecb_SEK',value:'8.8820'},{name:'ecb_CHF',value:'1.2342'},{name:'ecb_THB',value:'44.929'},{name:'ecb_TRY',value:'2.9585'},{name:'ecb_HUF',value:'299.24'}];
	
	// ci sono dei tassi che vengono fissati all'euro: è bene tenere qui il valore per maggiore precisione; se fossero fissati ad altre valute non andrebbe bene
	fixed_rates = [{name:'ZMK',value:'getValue(the_array,"ZMW")*1000'},{name:'TMT',value:'getValue(the_array,"TMM")/5000'},{name:'VEB',value:'getValue(the_array,"USD")*1000*6.3'},{name:'VEF',value:'getValue(the_array,"USD")*6.3'},{name:'XPF',value:'119.331742'},{name:'GHC',value:'getValue(the_array,"GHS")*10000'},{name:'XAF',value:'655.957'},{name:'XOF',value:'655.957'},{name:'NPR',value:'getValue(the_array,"INR")*1.6'},{name:'BTN',value:'getValue(the_array,"INR")'},{name:'SRG',value:'getValue(the_array,"SRD")*1000'},{name:'LSL',value:'getValue(the_array,"ZAR")'},{name:'XCD',value:'getValue(the_array,"USD")*2.7'},{name:'MGF',value:'getValue(the_array,"MGA")*5'},{name:'ECS',value:'getValue(the_array,"USD")*25000'},{name:'CUC',value:'getValue(the_array,"USD")*1.08'},{name:'ADP',value:'getValue(the_array,"ESP")'},{name:'GGP',value:'getValue(the_array,"GBP")'},{name:'GIP',value:'getValue(the_array,"GBP")'},{name:'CKD',value:'getValue(the_array,"NZD")'},{name:'FIK',value:'getValue(the_array,"DKK")'},{name:'IMP',value:'getValue(the_array,"GBP")'},{name:'JEP',value:'getValue(the_array,"GBP")'},{name:'TVD',value:'getValue(the_array,"AUD")'},{name:'SLSH',value:'getValue(the_array,"USD")*6000'},{name:'KIR',value:'getValue(the_array,"AUD")'},{name:'FKP',value:'getValue(the_array,"GBP")'},{name:'USD_BVI',value:'getValue(the_array,"USD")'},{name:'AUD_COC',value:'getValue(the_array,"AUD")'},{name:'USD_MCR',value:'getValue(the_array,"USD")'},{name:'AMD_NAG',value:'getValue(the_array,"AMD")'},{name:'AUD_NAU',value:'getValue(the_array,"AUD")'},{name:'NZD_NID',value:'getValue(the_array,"NZD")'},{name:'USD_NMI',value:'getValue(the_array,"USD")'},{name:'USD_PAL',value:'getValue(the_array,"USD")'},{name:'GBP_SGS',value:'getValue(the_array,"GBP")'},{name:'GBP_TRC',value:'getValue(the_array,"GBP")'},{name:'GBP_ALD',value:'getValue(the_array,"GBP")'},{name:'ZRN',value:'getValue(the_array,"CDF")*1000'},{name:'BRC',value:'getValue(the_array,"BRL")*2750'},{name:'CVE',value:'getValue(the_array,"EUR")*110.265'},{name:'BGN',value:'getValue(the_array,"EUR")*1.95583'},{name:'LTL',value:'getValue(the_array,"EUR")*3.4528'}];
	for (i=0; i<fixed_rates.length; i++){
		fixed_rates[fixed_rates[i].name] = fixed_rates[i];
	}
}

function cleaner()
{
	//widget.setPreferenceForKey("", "saved_last_selected_value");
	//widget.setPreferenceForKey("", "saved_last_selected_position");
	//widget.setPreferenceForKey("", "precision");
	//widget.setPreferenceForKey("", "taxes");
	widget.setPreferenceForKey("", "current_currency_version");
	widget.setPreferenceForKey("", "fetch_from_site");
	widget.setPreferenceForKey("", "currency_date");
	widget.setPreferenceForKey("", "euroconversion_current_currency_list");
	widget.setPreferenceForKey("", "extraeu_main_euroconversion_current_currency_list");
	widget.setPreferenceForKey("", "extraeu_euroconversion_current_currency_list");
	widget.setPreferenceForKey("", "ecb_euroconversion_current_currency_list");
	widget.setPreferenceForKey("", "palple_extraeu_current_currency_list");
	widget.setPreferenceForKey("", "palple_eur");
	widget.setPreferenceForKey("", "virtual_currencies");
	widget.setPreferenceForKey("", "commodities_currencies");
	widget.setPreferenceForKey("", "unrecognized_currencies");
    
    widget.setPreferenceForKey("true",createkey("showad"));
	widget.setPreferenceForKey("true","showad");
    //widget.setPreferenceForKey("", "showad");
	//widget.setPreferenceForKey("", createkey("showad"));
	//widget.setPreferenceForKey("['USD','EUR','LIT'];", createKey("saved_table_elements_data"));
}

function isNotInizialized(the_var)
{
	if (((the_var == undefined) || (the_var == "") || (the_var == "undefined") || (the_var == null)) && (the_var != "0")) return true;
	return false;
}

function isInArray(the_array, the_value, the_field)
{
	for (i=0;i<the_array.length;i++){ // devo esplicitare 'data' ma non va bene... devo far digerire the_field
		if (isNotInizialized(the_field)) {if (the_array[i] == the_value) return true;} else {if (the_array[i][the_field] == the_value) return true;}
	}
	
	return false;
}

function onhidden ()
{
	//saveConversionToPreferences();
}

if (window.widget)
{
	widget.onhide = onhidden;
}

if (window.widget) 
{
	widget.onshow = onshow;
}

function onshow()
{
	
}

function set_skin()
{
	var i, a;
	var link, stylesheetHref;
    
	for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
		if(((a.getAttribute("rel").indexOf("style") != -1) || (a.getAttribute("rel").indexOf("pippo") != -1)) && (a.getAttribute("id") != "common")) {			
			if(a.getAttribute("id") == "Active") link = a;
			if(a.getAttribute("id") == skin_prefs) {
				a.setAttribute("rel", "stylesheet");
			} else {
				a.setAttribute("rel", "pippo");
			}
		}
	}
	
	//link.setAttribute("href", stylesheetHref);
	
	var frontStyle = document.styleSheets[1].cssRules[0].style;
	body_width = frontStyle.width;
	body_width = body_width.replace("px","");
	body_width = parseInt(body_width);
	
	var topStyle = document.styleSheets[1].cssRules[1].style;
	top_height = topStyle.height;
	top_height = top_height.replace("px","");
	top_height = parseInt(top_height);
	
	var elementStyle = document.styleSheets[1].cssRules[3].style;
	element_height = elementStyle.height;
	element_height = element_height.replace("px","");
	element_height = parseInt(element_height);
	
	var bottomStyle = document.styleSheets[1].cssRules[4].style;
	bottom_height = bottomStyle.height;
	bottom_height = bottom_height.replace("px","");
	bottom_height = parseInt(bottom_height);
	
	var hackStyle = document.styleSheets[1].cssRules[5].style;
	popup_text_decoration = hackStyle.getPropertyValue('text-decoration');
	button_visibility = hackStyle.visibility;
    
    var adsStyle = document.styleSheets[1].cssRules[6].style;
	ads_height = adsStyle.height;
	ads_height = ads_height.replace("px","");
	ads_height = parseInt(ads_height);
    
    window.resizeTo (body_width, window.height);
}

function load_default_currencies_data()
{
	setToDefault();
	currency_date = "Sat, 11 Jan 2014 01:15:02 GMT"; // reset to default date
	
	// devo trasformare currency_date in data
	currency_date = new Date(currency_date);
	
	//currency_status.innerText = getLocalizedString('currency_status') + currency_date.toLocaleDateString("short") + " " + currency_date.toLocaleTimeString("short");
	status_text.innerText = getLocalizedString('currency_status');
	status_date.innerText = currency_date.toLocaleDateString("short") + " " + currency_date.toLocaleTimeString("short");
}

var error_retrieving = false;

function load_saved_currencies_data()
{ // legge i dati dalle preferenze
	fetch_from_site = widget.preferenceForKey ("fetch_from_site");
	
	if ((fetch_from_site == undefined) || (fetch_from_site == "")){
		fetch_from_site = "http://finance.yahoo.com/d?s=searchStringMagic&f=sl1d1t1ba";
		widget.setPreferenceForKey(fetch_from_site, "fetch_from_site");
	}
	
	currency_date_UTC = widget.preferenceForKey ("currency_date");
	
	if ((currency_date_UTC == undefined) || (currency_date_UTC == "")){
		widget.setPreferenceForKey(currency_date.toString(), "currency_date");
	}
	else {
		currency_date = new Date(currency_date_UTC);
	}
	
	error_retrieving = false;
	// provo a leggere i dati dalle preferenze
	if (window.widget)
	{
		try { // euroconversion list
			var euroconversion_current_currency_list = widget.preferenceForKey ("euroconversion_current_currency_list");
			var newAllData = new Array;
						
			euroconversion_current_currency_list = eval(euroconversion_current_currency_list);
			
			var c = euroconversion_current_currency_list.length;
			
			if (c == 0)
			{
				error_retrieving = true;
			}
			else
			{
				for (var i = 0; i < c; ++i)
				{
					var data = euroconversion_current_currency_list[i];
					
					if (data.name == "CSD") data.name = "RSD";
					newAllData[newAllData.length] = {name:data.name, value:data.value};
				}
				
				euroconversion = newAllData;
			}
		
		} catch(ex) // revert to default
		{
			error_retrieving = true;
		}
		
		try { // euroconversion list
			var extraeu_main_euroconversion_current_currency_list = widget.preferenceForKey ("extraeu_main_euroconversion_current_currency_list");
			var newAllData = new Array;
			
			extraeu_main_euroconversion_current_currency_list = eval(extraeu_main_euroconversion_current_currency_list);
			var c = extraeu_main_euroconversion_current_currency_list.length;
			
			if (c == 0)
			{
				error_retrieving = true;
			}
			else
			{
				for (var i = 0; i < c; ++i)
				{
					var data = extraeu_main_euroconversion_current_currency_list[i];

					newAllData[newAllData.length] = {name:data.name, value:data.value, site:data.site};
				}
				
				extraeu_main_euroconversion = newAllData;
			}
		
		} catch(ex) // revert to default
		{
			error_retrieving = true;
		}
		
		try { // euroconversion list
			var extraeu_euroconversion_current_currency_list = widget.preferenceForKey ("extraeu_euroconversion_current_currency_list");
			var newAllData = new Array;
			
			extraeu_euroconversion_current_currency_list = eval(extraeu_euroconversion_current_currency_list);
			var c = extraeu_euroconversion_current_currency_list.length;
			
			if (c == 0)
			{
				error_retrieving = true;
			}
			else
			{
				for (var i = 0; i < c; ++i)
				{
					var data = extraeu_euroconversion_current_currency_list[i];
                    
                    if ((data.name == 'ecb_SKK') || (data.name == 'ecb_SIT') || (data.name == 'ecb_MTL') || (data.name == 'ecb_ISK') || (data.name == 'ecb_CYP')){
                        continue;
                    }

					newAllData[newAllData.length] = {name:data.name, value:data.value, site:data.site};
				}
				
				extraeu_euroconversion = newAllData;
			}
		
		} catch(ex) // revert to default
		{
			error_retrieving = true;
		}
		
		try { // euroconversion list
			var ecb_euroconversion_current_currency_list = widget.preferenceForKey ("ecb_euroconversion_current_currency_list");
			var newAllData = new Array;
			
			ecb_euroconversion_current_currency_list = eval(ecb_euroconversion_current_currency_list);
			var c = ecb_euroconversion_current_currency_list.length;
			
			if (c == 0)
			{
				error_retrieving = true;
			}
			else
			{
				for (var i = 0; i < c; ++i)
				{
					var data = ecb_euroconversion_current_currency_list[i];
                    
                    if ((data.name == 'ECB_SKK') || (data.name == 'ECB_SIT') || (data.name == 'ECB_MTL') || (data.name == 'ECB_ISK') || (data.name == 'ECB_CYP')){
                        continue;
                    }

					newAllData[newAllData.length] = {name:data.name, value:data.value, site:data.site};
				}
				
				ecb_euroconversion = newAllData;
			}
		
		} catch(ex) // revert to default
		{
			error_retrieving = true;
		}
		
		try { // euroconversion list
			var palple_extraeu_current_currency_list = widget.preferenceForKey ("palple_extraeu_current_currency_list");
			var newAllData = new Array;
			
			palple_extraeu_current_currency_list = eval(palple_extraeu_current_currency_list);
			var c = palple_extraeu_current_currency_list.length;
			
			if (c == 0)
			{
				error_retrieving = true;
			}
			else
			{
				for (var i = 0; i < c; ++i)
				{
					var data = palple_extraeu_current_currency_list[i];

					newAllData[newAllData.length] = {name:data.name, value:data.value, site:data.site};
				}
				
				palple_extraeu = newAllData;
			}
		
		} catch(ex) // revert to default
		{
			error_retrieving = true;
		}
		
		palple_eur = widget.preferenceForKey ("palple_eur");
		if ((palple_eur == undefined) || (palple_eur == "")){
			error_retrieving = true;
		}
		
		try { // virtual_currencies list
			var virtual_currencies_list = widget.preferenceForKey ("virtual_currencies");
			var newAllData = new Array;
			
			virtual_currencies_list = eval(virtual_currencies_list);
			var c = virtual_currencies_list.length;
			
			if (c == 0)
			{
				error_retrieving = true;
			}
			else
			{
				for (var i = 0; i < c; ++i)
				{
					var data = virtual_currencies_list[i];

					newAllData[newAllData.length] = {name:data.name, value:data.value, site:data.site};
				}
				
				virtual_currencies = newAllData;
			}
		
		} catch(ex) // revert to default
		{
			error_retrieving = true;
		}
		
		for (i=0; i<virtual_currencies.length; i++){
			virtual_currencies[virtual_currencies[i].name] = virtual_currencies[i];
		}
		
		try { // commodities_currencies list
			var commodities_currencies_list = widget.preferenceForKey ("commodities_currencies");
			var newAllData = new Array;
			
			commodities_currencies_list = eval(commodities_currencies_list);
			var c = commodities_currencies_list.length;
			
			if (c == 0)
			{
				error_retrieving = true;
			}
			else
			{
				for (var i = 0; i < c; ++i)
				{
					var data = commodities_currencies_list[i];

					newAllData[newAllData.length] = {name:data.name, value:data.value, site:data.site};
				}
				
				commodities_currencies = newAllData;
			}
		
		} catch(ex) // revert to default
		{
			error_retrieving = true;
		}
		
		for (i=0; i<commodities_currencies.length; i++){
			commodities_currencies[commodities_currencies[i].name] = commodities_currencies[i];
		}
		
		try { // unrecognized_currencies list
			var unrecognized_currencies_list = widget.preferenceForKey ("unrecognized_currencies");
			var newAllData = new Array;
			
			unrecognized_currencies_list = eval(unrecognized_currencies_list);
			var c = unrecognized_currencies_list.length;
			
			if (c == 0)
			{
				error_retrieving = true;
			}
			else
			{
				for (var i = 0; i < c; ++i)
				{
					var data = unrecognized_currencies_list[i];

					newAllData[newAllData.length] = {name:data.name, value:data.value, site:data.site};
				}
				
				unrecognized_currencies = newAllData;
			}
		
		} catch(ex) // revert to default
		{
			error_retrieving = true;
		}
		
		for (i=0; i<unrecognized_currencies.length; i++){
			unrecognized_currencies[unrecognized_currencies[i].name] = unrecognized_currencies[i];
		}
	}
	
	if (error_retrieving == true){
		error_retrieving = false;
		load_default_currencies_data();
	}
	else
	{
		//currency_status.innerText = getLocalizedString('currency_status') + currency_date.toLocaleDateString("short") + " " + currency_date.toLocaleTimeString("short");
		status_text.innerText = getLocalizedString('currency_status');
		status_date.innerText = currency_date.toLocaleDateString("short") + " " + currency_date.toLocaleTimeString("short");
	}
}

function check_newest_currencies_data_available()
{
	if (currency_date_UTC != widget.preferenceForKey ("currency_date")){
		load_saved_currencies_data();
	}
}

function clean_for_new_version()
{
	try {
		saved_values_version = widget.preferenceForKey ("saved_values_version");
		
		if (current_version != saved_values_version){
			cleaner();
			widget.setPreferenceForKey(current_version, "saved_values_version");
		}
	}
	catch (ex){
		cleaner();
		widget.setPreferenceForKey(current_version, "saved_values_version");
	}
}

function init()
{
	//cleaner(); /* clean preferences for debug purposes */
	clean_for_new_version();
	
	content=document.getElementById('front'); // da modificare per i nuovi front
	
	content.addEventListener('mousemove',mousemove,false);
	content.addEventListener('mouseout',mouseexit,false);
	
	document.getElementById('flip').style.opacity = "0.0";
	
	document.getElementById('update_data').style.opacity = "0.0";
	
	update_data.setAttribute ("title", getLocalizedString('currency_status_tooltip'));
	update_data.setAttribute ("onmouseup", "javascript:update_currencies_data();");
	
	separators = RoundPlugin.getSeparators();
	thousand_separator = separators.charAt(0);
	decimal_separator = separators.charAt(1);
	
	load_default_currencies_data();
	
	load_saved_currencies_data(); // li legge dalle preferenze, se ci sono, se no prende quelli di default
	
	write_currencies_data();
	
	widget_style = widget.preferenceForKey(createkey("widget_style"));
	if (isNotInizialized(widget_style)) {widget_style = 0;}
	
	widget_style = 1;
	
	the_precision = widget.preferenceForKey(createkey("precision"));
	if (isNotInizialized(the_precision)) {
		the_precision = widget.preferenceForKey("precision");
		if (isNotInizialized(the_precision)) the_precision = 2;
	}
	conversion_precision = parseInt(the_precision);
	
	precision_popup.options[conversion_precision].selected = true;
	
	read_last_selected_from_prefs();
	read_table_elements_from_prefs();
	
	sections = widget.preferenceForKey(createkey("sections"));
	if (isNotInizialized(by_name)) {
		by_name = widget.preferenceForKey("sections");
		if (isNotInizialized(sections)) {sections = true;} else {sections = (sections == "true")?true:false}
	} else {sections = (sections == "true")?true:false}
	
	sections_radio_yes.checked = sections;
	sections_radio_no.checked = !sections;
	
	
	by_name = widget.preferenceForKey(createkey("by_name"));
	if (isNotInizialized(by_name)) {
		by_name = widget.preferenceForKey("by_name");
		if (isNotInizialized(by_name)) {by_name = false;} else {by_name = (by_name == "true")?true:false}
	} else {by_name = (by_name == "true")?true:false}
	
	by_country = widget.preferenceForKey(createkey("by_country"));
	if (isNotInizialized(by_country)) {
		by_country = widget.preferenceForKey("by_country");
		if (isNotInizialized(by_country)) {by_country = true;} else {by_country = (by_country == "true")?true:false}
	} else {by_country = (by_country == "true")?true:false}
	
	if (by_country){
		order_by_radio_states.checked = true;
	} else {
		order_by_radio_names.checked = by_name;
		order_by_radio_codes.checked = !by_name;
	}
	
	
	the_taxes = widget.preferenceForKey(createkey("taxes"));
	if (isNotInizialized(the_taxes)) {
		the_taxes = widget.preferenceForKey("taxes");
		if (isNotInizialized(the_taxes)) the_taxes = 0;
	}
	conversion_taxes = parseFloat(the_taxes);
	
	// costruisco il popup
	build_taxes_popup();
	
	//input_taxes_dialog.value = conversion_taxes;
	input_taxes_dialog.value = RoundPlugin.getFormattedValue(conversion_taxes.toString(),"false",6);
	
	
	skin_prefs = widget.preferenceForKey(createkey("skin_prefs"));
	if (isNotInizialized(skin_prefs)) {
		skin_prefs = widget.preferenceForKey("skin_prefs");
		if (isNotInizialized(skin_prefs)) skin_prefs = 'Default';
	}
	
	// costruisco il popup
	build_skin_popup();
	
	// seleziono il css
	set_skin();
	
	label_byname = widget.preferenceForKey(createkey("label_byname"));
	if (isNotInizialized(label_byname)) {
		label_byname = widget.preferenceForKey("label_byname");
		if (isNotInizialized(label_byname)) {label_byname = true;} else {label_byname = (label_byname == "true")?true:false}
	} else {label_byname = (label_byname == "true")?true:false}
	
	show_radio_names.checked = label_byname;
	show_radio_codes.checked = !label_byname;
    
    
    show_ad = widget.preferenceForKey(createkey("showad"));
	if (isNotInizialized(show_ad)) {
		show_ad = widget.preferenceForKey("showad");
		if (isNotInizialized(show_ad)) {show_ad = true;} else {show_ad = (show_ad == "true")?true:false}
	} else {show_ad = (show_ad == "true")?true:false}
    
    hide_ad_check.checked = !show_ad;
	
	populateArrays(); // prepara gli array
	sortArrays(); // ordina gli array
	
	setTimeout("update_currencies_data();", 10*1000); // il primo aggornamento dopo 10 secondi per non interferire con il primo calcolo, altrimenti lo sballa
	setInterval("update_currencies_data();",6*60*60*1000); // ogni 6h faccio il controllo
	
	setTimeout("version_check();", 20*1000);
	setInterval("version_check();",24*60*60*1000); // ogni 24h faccio il controllo
    
    setInterval("check_newest_currencies_data_available();",10*60*1000); // ogni 10 min faccio il controllo
    
	initFront();
	
	initBack();
}

function initBack()
{
	hide_ad_check_text.innerHTML = getLocalizedString('hide_ad');
    
    order_by_radio_names_text.innerHTML = getLocalizedString('order_by_radio_names_text');
	order_by_radio_codes_text.innerHTML = getLocalizedString('order_by_radio_codes_text');
	order_by_radio_states_text.innerHTML = getLocalizedString('order_by_radio_states_text');
	sections_radio_yes_text.innerHTML = getLocalizedString('sections_radio_yes_text');
	sections_radio_no_text.innerHTML = getLocalizedString('sections_radio_no_text');
	labels_radio_names_text.innerHTML = getLocalizedString('labels_radio_names_text');
	labels_radio_codes_text.innerHTML = getLocalizedString('labels_radio_codes_text');
	
	precisionLabel.innerHTML = getLocalizedString('precisionPrefs');
	taxesLabel.innerHTML = getLocalizedString('taxesPrefs');
	skinLabel.innerHTML = getLocalizedString('skinPrefs');
	
	label_taxes_dialog.innerHTML = getLocalizedString('label_taxes_dialog');
	taxes_dialog_undo.innerHTML = getLocalizedString('taxes_dialog_undo');
	taxes_dialog_ok.innerHTML = getLocalizedString('taxes_dialog_ok');
	
	author.innerHTML = getLocalizedString('author');

	var doneButton = document.getElementById('done');
	createGenericButton (doneButton, getLocalizedString('Done'), selectDone);
	
	var donateButton = document.getElementById('donate');
	createGenericButton (donateButton, getLocalizedString('Donate'), selectDonate);
	
	doneButton.childNodes[1].style.minWidth = '47px';
}

function initFront()
{
	if (widget_style == 0) { // standard
		return;
	}
	else if (widget_style == 1) { // table
		initFront_table();
        
        document.getElementById("ad_text").innerHTML = getLocalizedString("my_ad");
        ad_text.setAttribute ("onmouseup", "javascript:go_to_store();");
        
		document.getElementById("front").style.background = "none";
		document.getElementById("top").style.display = "block";
		document.getElementById("body_table").style.display = "block";
        if (show_ad) {document.getElementById("ads").style.display = "block";} else {document.getElementById("ads").style.display = "none";}
		document.getElementById("bottom").style.display = "block";
	}
	else if (widget_style == 2) { // compact
		return;
	}
}

function show_buttons (the_element,event)
{
	//event.stopPropagation();
	document.getElementById("add_button_" + the_element).style.visibility = "visible";
	document.getElementById("remove_button_" + the_element).style.visibility = "visible";
	
	document.getElementById("label_field_" + the_element).setAttribute("style","text-decoration: " + popup_text_decoration);
	//event.preventDefault();
}

function hide_buttons (the_element,event)
{
	//event.stopPropagation();
	
	document.getElementById("add_button_" + the_element).style.visibility = button_visibility;
	document.getElementById("remove_button_" + the_element).style.visibility = button_visibility;
	
	document.getElementById("label_field_" + the_element).setAttribute("style","text-decoration: none");
	//event.preventDefault();
}

function add_element(the_element)
{	
	if (mousedown_in_add_var != the_element) {mousedown_in_add_var = undefined; return;}
	mousedown_in_add_var = undefined;
	modifing_an_alement += 1;
	
	var new_table_elements = table_elements.splice(the_element, 0, table_elements[the_element]);
	
	if (the_element < last_selected_value.position) {++ last_selected_value.position;}
	
	//saveTableElements();
	save_options(); // al posto del solo saveTableElements, così ho tutti i dati globali settati bene
	
	// ricostruisci ora gli id della tabella
	var c = table_elements.length;
	
	var new_size = c*element_height + top_height + ads_height + bottom_height + 2;
	
	if (actual_size < new_size){
		front.style.height = c*element_height + top_height + ads_height + bottom_height + 2;
		window.resizeTo (body_width, c*element_height + top_height + ads_height + bottom_height + 2);
		
		actual_size = new_size;
	}
	
	// crea il nuovo elemento ed aggiungilo alla table html nella posizione giusta, con display = hidden
	var new_row = build_new_element(the_element + 1,document.getElementById("value_field_" + the_element).value);
	
	var previd = the_element;
	var prev_row = document.getElementById("body_table_element_" + previd);
	//devo inserire l'elemento nella tabella e dovrebbe essere hidden!!!
	insertAfter(new_row,prev_row);
	// rebuild table ids
	renumber_elements();
	
	// fornisco una lista degli elementi per il debug
	//print_elements_list();
	
	current_row = the_element + 1;
	
	new Effect.BlindDown("body_table_element_" + current_row,{ duration: 0.2 });
	modifing_an_alement -= 1;
	
	if (table_elements.length > 1){
		document.getElementById("remove_button_0").style.display = "block";
		document.getElementById("remove_button_disabled_0").style.display = "none";
	}
}

function insertAfter(newChild, refChild) { 
	refChild.parentNode.insertBefore(newChild,refChild.nextSibling); 
}

function build_new_element(i,the_value){
	var row_container = document.createElement('div');
	row_container.setAttribute ("class", "body_table_element");
	row_container.setAttribute ("id", "body_table_element_new_" + i);	
	new_top = i*element_height + top_height;
	//row_container.setAttribute ("style", "top:" + new_top + "px;");
	row_container.setAttribute ("style", "display: none;");
	row_container.setAttribute ("onmouseover", "javascript:show_buttons(" + i + ",event);");
	row_container.setAttribute ("onmouseout", "javascript:hide_buttons(" + i + ",event);");
	
	var label_field = document.createElement('div');
	label_field.setAttribute ("class", "label_field");
	label_field.setAttribute ("id", "label_field_new_" + i);
	//label_field.innerHTML = getLocalizedString(table_elements[i]);
	iso_code = table_elements[i].currency;
	if (iso_code.indexOf("ecb_") != -1){
		iso_code = iso_code.substring(4);
		
		if (label_byname) {label_field.innerHTML = "(" + getLocalizedString("bce") + ") " + getLocalizedString(iso_code);} else {label_field.innerHTML = iso_code;}
	} else {
		if (label_byname) {label_field.innerHTML = getLocalizedString(table_elements[i].currency);} else {label_field.innerHTML = table_elements[i].currency;}
	}
	
	//<select id='toUnit-popup' class='popup' onchange='toUnitChanged(this);'></select>
	var select_field = document.createElement('select');
	select_field.setAttribute ("class", "select_field");
	select_field.setAttribute ("id", "select_field_new_" + i);
	select_field.setAttribute ("onchange", "javascript:change_element(" + i + ");");

	//populatePopup(select_field,i);
	populatePopups(select_field,i);
	
	//<input type="text" id="valuta2" size = "8" value='' maxLength=13 onkeyup='convertAmount(this.value, "right");' />
	var value_field = document.createElement('input');
	value_field.setAttribute ("class", "value_field");
	value_field.setAttribute ("id", "value_field_new_" + i);
	value_field.setAttribute ("type", "text");
	value_field.setAttribute ("size", "8");
	value_field.setAttribute ("value", the_value);
	value_field.setAttribute ("maxLength", "23");
	value_field.setAttribute ("onkeyup", "javascript:convert_values(" + i + ",event);");
	value_field.setAttribute ("onkeypress", "javascript:return numeralsOnly(" + i + ",event);");
	value_field.setAttribute ("oninput", "javascript:convert_values(" + i + ",event);");
	
	var add_button = document.createElement('div');
	add_button.setAttribute ("class", "add_button");
	add_button.setAttribute ("id", "add_button_new_" + i);
	add_button.setAttribute ("onmousedown", "javascript:mousedown_in_add(" + i + ");");
	add_button.setAttribute ("onmouseup", "javascript:add_element(" + i + ");");
	
	var remove_button = document.createElement('div');
	remove_button.setAttribute ("class", "remove_button");
	remove_button.setAttribute ("id", "remove_button_new_" + i);
	remove_button.setAttribute ("onmousedown", "javascript:mousedown_in_remove(" + i + ");");
	remove_button.setAttribute ("onmouseup", "javascript:delete_element(" + i + ");");
	
	var remove_button_disabled = document.createElement('div');
	remove_button_disabled.setAttribute ("class", "remove_button_disabled");
	remove_button_disabled.setAttribute ("id", "remove_button_disabled_new_" + i);
	
	var currency_sign_field = document.createElement('div');
	currency_sign_field.setAttribute ("class", "currency_sign_field");
	currency_sign_field.setAttribute ("id", "currency_sign_field_new_" + i);
	
	the_element_code = table_elements[i].currency;
	if (the_element_code.indexOf("ecb_") != -1){
		iso_code = the_element_code.substring(4);
	} else {iso_code = the_element_code;}
	try {currency_sign_field.innerHTML = (currency_sign[iso_code].sign);} catch (exept) {currency_sign_field.innerHTML = ''}
	
	var country_flag = document.createElement('img');
	country_flag.setAttribute ("class", "country_flag");
	country_flag.setAttribute ("id", "country_flag_new_" + i);
	country_flag.setAttribute ("src", "Flags/" + table_elements[i].country + ".png");
	
	row_container.appendChild (label_field);
	row_container.appendChild (value_field);
	row_container.appendChild (select_field);
	row_container.appendChild (add_button);
	row_container.appendChild (remove_button);
	row_container.appendChild (remove_button_disabled);
	row_container.appendChild (currency_sign_field);
	row_container.appendChild (country_flag);
	
	return row_container;
}

Effect.MyBlindUp = function(element) {
  //RoundPlugin.logMessage("MyBlindUp: " + element.getAttribute("id"));
  element = $(element);
  element.makeClipping();
  return new Effect.Scale(element, 0,
    Object.extend({ scaleContent: false, 
      scaleX: false, 
      restoreAfterFinish: true,
      afterFinishInternal: function(effect) {
        effect.element.hide().undoClipping();
		effect.element.remove();
		finish_delete();
      } 
    }, arguments[1] || { })
  );
};

function finish_delete()
{	
	// resize the widget
	var c = table_elements.length;
	
	var new_size = c*element_height + top_height + ads_height + bottom_height + 2;
	
	if (actual_size < new_size){
		front.style.height = c*element_height + top_height + ads_height + bottom_height + 2;
		window.resizeTo (body_width, c*element_height + top_height + ads_height + bottom_height + 2);
		
		actual_size = new_size;
	}
	
	// se è l'ultimo disabilito il remove
	if (table_elements.length == 1){
		document.getElementById("remove_button_0").style.display = "none";
		document.getElementById("remove_button_disabled_0").style.display = "block";
	}
	
	modifing_an_alement -= 1;
}

function renumber_elements()
{
	//print_elements_list();
	
	var the_table = document.getElementById("body_table");
	var all_the_nodes = the_table.childNodes;
	
	// prima li resetto, per evitare conflitti
	for (var j=0;j<all_the_nodes.length;j++){
		if (all_the_nodes[j].getAttribute("id").indexOf("body_table_element_toberemoved_") >= 0) {continue;}
		
		all_the_nodes[j].setAttribute("id","body_table_element_reset_" + new_id);
		
		//RoundPlugin.logMessage("changing id of #:" + all_the_nodes[j].childNodes[0].getAttribute("id") + " to: label_field_");
		all_the_nodes[j].childNodes[0].setAttribute("id","label_field_reset_" + new_id);
		
		//RoundPlugin.logMessage("changing id of #:" + all_the_nodes[j].childNodes[2].getAttribute("id") + " to: select_field_");
		all_the_nodes[j].childNodes[2].setAttribute("id","select_field_reset_" + new_id);
		
		//RoundPlugin.logMessage("changing id of #:" + all_the_nodes[j].childNodes[1].getAttribute("id") + " to: value_field_");
		all_the_nodes[j].childNodes[1].setAttribute("id","value_field_reset_" + new_id);
		
		//RoundPlugin.logMessage("changing id of #:" + all_the_nodes[j].childNodes[3].getAttribute("id") + " to: add_button_");
		all_the_nodes[j].childNodes[3].setAttribute("id","add_button_reset_" + new_id);
		//RoundPlugin.logMessage("changing id of #:" + all_the_nodes[j].childNodes[4].getAttribute("id") + " to: remove_button_");
		all_the_nodes[j].childNodes[4].setAttribute("id","remove_button_reset_" + new_id);
		//RoundPlugin.logMessage("changing id of #:" + all_the_nodes[j].childNodes[5].getAttribute("id") + " to: remove_button_disabled_");
		all_the_nodes[j].childNodes[5].setAttribute("id","remove_button_disabled_reset_" + new_id);
		//RoundPlugin.logMessage("changing id of #:" + all_the_nodes[j].childNodes[6].getAttribute("id") + " to: currency_sign_field_");
		all_the_nodes[j].childNodes[6].setAttribute("id","currency_sign_field_reset_" + new_id);
		//RoundPlugin.logMessage("changing id of #:" + all_the_nodes[j].childNodes[7].getAttribute("id") + " to: country_flag_");
		all_the_nodes[j].childNodes[7].setAttribute("id","country_flag_reset_" + new_id);
		
		new_id++;
	}
	
	// poi li rinomino
	
	var new_id = 0;
	for (var j=0;j<all_the_nodes.length;j++){
		if (all_the_nodes[j].getAttribute("id").indexOf("body_table_element_toberemoved_") >= 0) {continue;}
		
		all_the_nodes[j].setAttribute("id","body_table_element_" + new_id);
		all_the_nodes[j].setAttribute("onmouseover","javascript:show_buttons(" + new_id + ",event);");
		all_the_nodes[j].setAttribute("onmouseout","javascript:hide_buttons(" + new_id + ",event);");
		
		//RoundPlugin.logMessage("changing id of #:" + all_the_nodes[j].childNodes[0].getAttribute("id") + " to: label_field_");
		all_the_nodes[j].childNodes[0].setAttribute("id","label_field_" + new_id);
		
		//RoundPlugin.logMessage("changing id of #:" + all_the_nodes[j].childNodes[2].getAttribute("id") + " to: select_field_");
		all_the_nodes[j].childNodes[2].setAttribute("onchange", "javascript:change_element(" + new_id + ");");
		all_the_nodes[j].childNodes[2].setAttribute("id","select_field_" + new_id);
		
		//RoundPlugin.logMessage("changing id of #:" + all_the_nodes[j].childNodes[1].getAttribute("id") + " to: value_field_");
		all_the_nodes[j].childNodes[1].setAttribute("onkeyup", "javascript:convert_values(" + new_id + ",event);");
		all_the_nodes[j].childNodes[1].setAttribute("onkeypress", "javascript:return numeralsOnly(" + new_id + ",event);");
		all_the_nodes[j].childNodes[1].setAttribute("oninput", "javascript:convert_values(" + new_id + ",event);");
		all_the_nodes[j].childNodes[1].setAttribute("id","value_field_" + new_id);
		
		//RoundPlugin.logMessage("changing id of #:" + all_the_nodes[j].childNodes[3].getAttribute("id") + " to: add_button_");
		all_the_nodes[j].childNodes[3].setAttribute("onmousedown", "javascript:mousedown_in_add(" + new_id + ");");
		all_the_nodes[j].childNodes[3].setAttribute("onmouseup", "javascript:add_element(" + new_id + ");");
		all_the_nodes[j].childNodes[3].setAttribute("id","add_button_" + new_id);
		//RoundPlugin.logMessage("changing id of #:" + all_the_nodes[j].childNodes[4].getAttribute("id") + " to: remove_button_");
		all_the_nodes[j].childNodes[4].setAttribute("onmousedown", "javascript:mousedown_in_remove(" + new_id + ");");
		all_the_nodes[j].childNodes[4].setAttribute("onmouseup", "javascript:delete_element(" + new_id + ");");
		all_the_nodes[j].childNodes[4].setAttribute("id","remove_button_" + new_id);
		//RoundPlugin.logMessage("changing id of #:" + all_the_nodes[j].childNodes[5].getAttribute("id") + " to: remove_button_disabled_");
		all_the_nodes[j].childNodes[5].setAttribute("id","remove_button_disabled_" + new_id);
		//RoundPlugin.logMessage("changing id of #:" + all_the_nodes[j].childNodes[6].getAttribute("id") + " to: currency_sign_field_");
		all_the_nodes[j].childNodes[6].setAttribute("id","currency_sign_field_" + new_id);
		//RoundPlugin.logMessage("changing id of #:" + all_the_nodes[j].childNodes[7].getAttribute("id") + " to: country_flag_");
		all_the_nodes[j].childNodes[7].setAttribute("id","country_flag_" + new_id);
		
		new_id++;
	}
	
	// se è l'ultimo disabilito il remove
	if (table_elements.length == 1){
		document.getElementById("remove_button_0").style.display = "none";
		document.getElementById("remove_button_disabled_0").style.display = "block";
	}
	
	// fornisco una lista degli elementi per il debug
	//print_elements_list();
}

function print_elements_list()
{
	var the_table = document.getElementById("body_table");
	var all_the_nodes = the_table.childNodes;
	for (var j=0;j<all_the_nodes.length;j++){
		RoundPlugin.logMessage("node #:" + j + "id #:" + all_the_nodes[j].getAttribute("id"));
	}
}

function delete_element(the_element)
{
	if (mousedown_in_remove_var != the_element) {mousedown_in_remove_var = undefined; return;}
	mousedown_in_remove_var = undefined;
	// per prima cosa, rinomina l'elemento da eliminare
	modifing_an_alement += 1;
	
	//RoundPlugin.logMessage("remove_element called on: #" + the_element);
	document.getElementById("body_table_element_" + the_element).setAttribute("id","body_table_element_toberemoved_" + the_element);
		
	if (table_elements.length == 1) return;
	
	if (the_element == last_selected_value.position){
		if (the_element != 0){
			last_selected_value.position --;
			last_selected_value.value = document.getElementById("value_field_" + last_selected_value.position).value;
		} else {
			var the_id = last_selected_value.position + 1;
			last_selected_value.value = document.getElementById("value_field_" + the_id).value;
		}
	} else if (the_element < last_selected_value.position){
		last_selected_value.position --;
	}
	
	//table_elements.splice(the_element,1);
	//table_elements.remove(the_element);
	table_elements.remove(the_element);
	//saveTableElements();
	save_options();
	
	renumber_elements(the_element);
	new Effect.MyBlindUp("body_table_element_toberemoved_" + the_element,{ duration: 0.2 });
}

function serialize_table_elements() //???????
{
	var to_return;
	
	for (var k=0;k<table_elements.length;k++){
		to_return += table_elements[k].currency + ";" + table_elements[k].country + "---";
	}
	
	return to_return;
}

function reset_mousedown()
{
	mousedown_in_add_var = undefined;
	mousedown_in_remove_var = undefined;
}

function mousedown_in_add(the_element)
{
	mousedown_in_add_var = the_element;
}

function mousedown_in_remove(the_element)
{
	mousedown_in_remove_var = the_element;
}

function change_element(the_element)
{
	var new_currency = document.getElementById("select_field_" + the_element).options[document.getElementById("select_field_" + the_element).selectedIndex].getAttribute("name");
	var new_country = document.getElementById("select_field_" + the_element).options[document.getElementById("select_field_" + the_element).selectedIndex].value;
	
	//RoundPlugin.logMessage("new country: " + new_country);
	var old_currency = table_elements[the_element].currency;
	var old_value = document.getElementById("value_field_" + the_element).value;
	
	table_elements.splice(the_element, 1, {currency:new_currency,country:new_country});
	
	saveTableElements();
	
	if (new_currency.indexOf("ecb_") != -1){
		iso_code = new_currency;
		iso_code = iso_code.substring(4);

		if (label_byname) {document.getElementById("label_field_" + the_element).innerHTML = "(" + getLocalizedString("bce") + ") " + getLocalizedString(iso_code);} else {document.getElementById("label_field_" + the_element).innerHTML = iso_code;}
		document.getElementById("currency_sign_field_" + the_element).innerHTML = (currency_sign[iso_code].sign);
	} else {
		if (label_byname) {document.getElementById("label_field_" + the_element).innerHTML = getLocalizedString(new_currency);} else {document.getElementById("label_field_" + the_element).innerHTML = new_currency;}
		document.getElementById("currency_sign_field_" + the_element).innerHTML = (currency_sign[new_currency].sign);
	}
	
	document.getElementById("country_flag_" + the_element).setAttribute ("src", "Flags/" + new_country + ".png");
	
	//RoundPlugin.logMessage("oldvalue= " + old_value);
	if(RoundPlugin){
    	var amount = RoundPlugin.getNumericValue(old_value);
    }
    //RoundPlugin.logMessage("amount= " + amount);
    var oldAmount = parseFloat(amount);
    
	if (isNaN(oldAmount)){
		// è vuoto o NaN --> devo prendere un altro riferimento come old_currency!!!
		// scansiono la tabella fino a trovare un elemento non vuoto		
		if (last_selected_value.position != the_element){
			convert_values(last_selected_value.position);
		} else {
			for (var k=0;k<table_elements.length;k++){
				oldAmount = document.getElementById("value_field_" + k).value;
				if (isNaN(oldAmount) == false){
					old_currency = table_elements[k].currency;
					last_selected_value.position = k;
					last_selected_value.value = oldAmount;
					
					convert_values(k);
					save_options();
					return;
				}
			}
		}
	} else {
		convert_value(old_currency,old_value,the_element);
	
		if (last_selected_value.position == the_element){last_selected_value.value = document.getElementById("value_field_" + the_element).value; save_options();}
	}
}

var actual_size = table_elements.length * element_height + top_height + ads_height + bottom_height + 2;

function initFront_table()
{	
	var c = table_elements.length;
		
	var new_size = c*element_height + top_height + ads_height + bottom_height + 2;
	
	if (actual_size < new_size){
		front.style.height = c*element_height + top_height + ads_height + bottom_height + 2;
		window.resizeTo (body_width, c*element_height + top_height + ads_height + bottom_height + 2);
		
		actual_size = new_size;
	}
	
	populatePopup(document.getElementById("default_select"),"EUR"); // ne popolo solo uno, poi lo copio negli altri, è ben più veloce
	
	removeAllChildren(body_table);
	
	for (var i=0; i<c; ++i){
		var row_container = document.createElement('div');
		row_container.setAttribute ("class", "body_table_element");
		row_container.setAttribute ("id", "body_table_element_" + i);
		row_container.setAttribute ("onmouseover", "javascript:show_buttons(" + i + ",event);");
		row_container.setAttribute ("onmouseout", "javascript:hide_buttons(" + i + ",event);");
		new_top = i*element_height + top_height;
		//row_container.setAttribute ("style", "top:" + new_top + "px;");
		
		var label_field = document.createElement('div');
		label_field.setAttribute ("class", "label_field");
		label_field.setAttribute ("id", "label_field_" + i);
		//label_field.innerHTML = getLocalizedString(table_elements[i]);
		iso_code = table_elements[i].currency;
		if (iso_code.indexOf("ecb_") != -1){
			iso_code = iso_code.substring(4);
			
			if (label_byname) {label_field.innerHTML = "(" + getLocalizedString("bce") + ") " + getLocalizedString(iso_code);} else {label_field.innerHTML = iso_code;}
		} else {
			if (label_byname) {label_field.innerHTML = getLocalizedString(table_elements[i].currency);} else {label_field.innerHTML = table_elements[i].currency;}
		}
		
		//<select id='toUnit-popup' class='popup' onchange='toUnitChanged(this);'></select>
		var select_field = document.createElement('select');
		select_field.setAttribute ("class", "select_field");
		select_field.setAttribute ("id", "select_field_" + i);
		select_field.setAttribute ("onchange", "javascript:change_element(" + i + ");");
		select_field.setAttribute ("onmousedown", "javascript:reset_mousedown();");

		//populatePopup(select_field,i);
		populatePopups(select_field,i);
		
		/*
		for (j=0; j< select_field.options.length; j++){
			if (select_field.options[j].name == table_elements[i]) {select_field.options[j].selected = true;break;}
		}*/
		
		//<input type="text" id="valuta2" size = "8" value='' maxLength=13 onkeyup='convertAmount(this.value, "right");' />
		var value_field = document.createElement('input');
		value_field.setAttribute ("class", "value_field");
		value_field.setAttribute ("id", "value_field_" + i);
		value_field.setAttribute ("type", "text");
		value_field.setAttribute ("size", "8");
		value_field.setAttribute ("maxLength", "23");
		value_field.setAttribute ("onkeyup", "javascript:convert_values(" + i + ",event);");
		value_field.setAttribute ("onkeypress", "javascript:return numeralsOnly(" + i + ",event);");
		value_field.setAttribute ("oninput", "javascript:convert_values(" + i + ",event);");
		value_field.setAttribute ("onmousedown", "javascript:reset_mousedown();");
		
		var add_button = document.createElement('div');
		add_button.setAttribute ("class", "add_button");
		add_button.setAttribute ("id", "add_button_" + i);
		add_button.setAttribute ("onmousedown", "javascript:mousedown_in_add(" + i + ");");
		add_button.setAttribute ("onmouseup", "javascript:add_element(" + i + ");");
		
		var remove_button = document.createElement('div');
		remove_button.setAttribute ("class", "remove_button");
		remove_button.setAttribute ("id", "remove_button_" + i);
		remove_button.setAttribute ("onmousedown", "javascript:mousedown_in_remove(" + i + ");");
		remove_button.setAttribute ("onmouseup", "javascript:delete_element(" + i + ");");
		
		var remove_button_disabled = document.createElement('div');
		remove_button_disabled.setAttribute ("class", "remove_button_disabled");
		remove_button_disabled.setAttribute ("id", "remove_button_disabled_" + i);
		
		var currency_sign_field = document.createElement('div');
		currency_sign_field.setAttribute ("class", "currency_sign_field");
		currency_sign_field.setAttribute ("id", "currency_sign_field_" + i);
		
		the_element_code = table_elements[i].currency;
		if (the_element_code.indexOf("ecb_") != -1){
			iso_code = the_element_code.substring(4);
		} else {iso_code = the_element_code;}
		try {currency_sign_field.innerHTML = (currency_sign[iso_code].sign);} catch (exept) {currency_sign_field.innerHTML = ''}
		
		var country_flag = document.createElement('img');
		country_flag.setAttribute ("class", "country_flag");
		country_flag.setAttribute ("id", "country_flag_" + i);
		country_flag.setAttribute ("src", "Flags/" + table_elements[i].country + ".png");
		
		row_container.appendChild (label_field);
		row_container.appendChild (value_field);
		row_container.appendChild (select_field);
		row_container.appendChild (add_button);
		row_container.appendChild (remove_button);
		row_container.appendChild (remove_button_disabled);
		row_container.appendChild (currency_sign_field);
		row_container.appendChild (country_flag);
		
		body_table.appendChild (row_container);
	}
	
	if (table_elements.length == 1){
		document.getElementById("remove_button_0").style.display = "none";
		document.getElementById("remove_button_disabled_0").style.display = "block";
	}
	
	if (actual_size >= new_size){
		front.style.height = c*element_height + top_height + ads_height + bottom_height + 2;
		window.resizeTo (body_width, c*element_height + top_height + ads_height + bottom_height + 2);
		
		actual_size = new_size;
	}
	
	document.getElementById("value_field_" + last_selected_value.position).value = last_selected_value.value;
	convert_values(last_selected_value.position);
	
	new_top = i*element_height + top_height;
	//document.getElementById("bottom").setAttribute ("style", "top:" + new_top + "px;");
	document.getElementById("bottom").style.display = "block";
}

function removeAllChildren (parent)
{
	while (parent.hasChildNodes())
		parent.removeChild(parent.firstChild);
}

function initFront_compact()
{
	// not implemented in this version
}

function compareData(a, b)
{
    try {
		var nameA = a.data;
		var nameB = b.data;
		if (nameA < nameB) {return -1}
		if (nameA > nameB) {return 1}
		return 0;
    } catch(ex) {return 0;}
}


function compareNames(a, b)
{
    try {
		var nameA = a.localized.toLowerCase( );
		var nameB = b.localized.toLowerCase( );
		if (nameA < nameB) {return -1}
		if (nameA > nameB) {return 1}
		return 0;
    } catch(ex) {return 0;}
}

function compareCodes(a, b)
{
    try {
		var nameA = a.name.toLowerCase( );
		var nameB = b.name.toLowerCase( );
		if (nameA < nameB) {return -1}
		if (nameA > nameB) {return 1}
		return 0;
    } catch(ex) {return 0;}
}

function compareCountries(a, b)
{
    //try{RoundPlugin.logMessage(a.country.toLowerCase());} catch (ex){RoundPlugin.logMessage("errore in: " + a.name);}
    try {
		var nameA = a.country.toLowerCase( );
		var nameB = b.country.toLowerCase( );
		if (nameA < nameB) {return -1}
		if (nameA > nameB) {return 1}
		return 0;
    } catch(ex) {return 0;}
}

function compareCountryNames(a, b)
{
    //try{RoundPlugin.logMessage(a.country.toLowerCase());} catch (ex){RoundPlugin.logMessage("errore in: " + a.name);}
    try {
		var nameA = a.country_name.toLowerCase( );
		var nameB = b.country_name.toLowerCase( );
		if (nameA < nameB) {return -1}
		if (nameA > nameB) {return 1}
		return 0;
    } catch(ex) {return 0;}
}

function goToDownloadPage()
{
	// vai al sito
	widget.openURL("http://www.palple.net/widgets/currencyconverter/CurrencyConverterPPC.zip");
}

var version_req_stop_timeout = false;
var version_req_timeout = false;

function loadVersionPage(url)
{
	if (window.XMLHttpRequest) {
		version_req = new XMLHttpRequest();
		version_req.overrideMimeType("text/xml");
		version_req.open("GET", url, true);
		version_req.setRequestHeader("Cache-Control", "no-cache");
		version_req.onreadystatechange = parseVersionPage;
		version_req.send(null);
		
		version_req_stop_timeout = false;
		version_req_timeout = false;
		setTimeout("version_req_send_timeout();",5000);
	}
}

function version_req_send_timeout()
{
	if (version_req_stop_timeout){return;}
	version_req_timeout = true;
}

function isGreaterVersion(release1, release2)
{
	// faccio uno split per il '.' e poi verifico valore per valore
	release1_numbers = release1.split('.');
	release2_numbers = release2.split('.');
	
	release1_value = 0;
	release2_value = 0;
	
	// risolvo matematicamente che è più elegante...
	
	for (i=0;i<release1_numbers.length;i++){
		release1_value += release1_numbers[i]*(Math.pow(10,-i*3));
	}
	
	for (i=0;i<release2_numbers.length;i++){
		release2_value += release2_numbers[i]*(Math.pow(10,-i*3));
	}
	
	if (release1_value > release2_value) return true;
	
	return false;
	
	/* wrong
	for (i=0;i<release1_numbers.length;i++){
		try {number_exists = release2_numbers[i];} catch (ex){return true;} // se non esiste il valore nella seconda...
		if (release1_numbers[i] > release2_numbers[i]) {return true;} else if (release1_numbers[i] < release2_numbers[i]) {return false;}
	}*/
}

function parseVersionPage()
{
	if (version_req_timeout) {version_req.abort(); version_req_timeout = false; version_req_stop_timeout = true; return;}
	
	if ((version_req.readyState == 4) && (version_req.status == 200)) {
		version_req_stop_timeout = true;
		version_req_timeout = false;
		
		latest_version = version_req.responseXML.getElementsByTagName("version");
		latest_version = latest_version[0].firstChild.data;
		
		// faccio una comparazione tra versioni
		if (isGreaterVersion(latest_version,current_version)){
			there_is_a_new_version = true;
		}
		
		/*
		if (latest_version != current_version){
			there_is_a_new_version = true;
		}*/
		//debug (latest_version);
		
		if (there_is_a_new_version) {
			new_version_badge.style.display = "block"
			new_version_tooltip_string = getLocalizedString('new_version_tooltip') + " " + latest_version + " (" + getLocalizedString('you_have') + " " + current_version + ")";
			new_version_badge.setAttribute ("title", new_version_tooltip_string);
		}
	}
}

function version_check()
{
	loadVersionPage('http://www.palple.net/widgets/currencyconverter/ppcversion.xml');
}


var throbber_visibile = 0;
var quote_req_stop_timeout = false;
var quote_req_timeout = false;

function update_currencies_data()
{
	// prima di tutto carico gli ultimi salvati
	check_newest_currencies_data_available();
	convert_values(last_selected_value.position);
	
	// se è passata meno di 1 ora non lo faccio
    currency_date_UTC = widget.preferenceForKey ("currency_date");
    currency_date = new Date(currency_date_UTC);
    currentDate = new Date();
    
    if ((currentDate.getTime() - currency_date.getTime()) < 60*60*1000) return;
    
    if (throbber_visibile > 0) return; // already updating
    
    // currency_status.innerText = getLocalizedString('updating');
	throbber_visibile += 2; // il numero di siti che devo visitare
    
	throb = new Throbber("retrieving");
	retrieving.setAttribute ("style", "display:block;");
	throb.start();
	
	// scarico i dati relativi alle valute
	fetchURIs = ["http://www.palple.net/iphone/currencyconverter/2/values.txt","http://www.quaerosoft.com/currencyconverter/values.txt"];
	
	var randomnumber = Math.floor(Math.random()*2);
	
	fetchURI = fetchURIs[randomnumber];
	
	currentURI = fetchURI;
	
	if (window.XMLHttpRequest) {
		req4 = new XMLHttpRequest();		
		req4.overrideMimeType("text/xml");
		req4.open("GET", currentURI, true);
		req4.setRequestHeader("Cache-Control", "no-cache");
		req4.onreadystatechange = function(e) {parseQuoteData_palple(e, req4);}
		req4.send(null);
	}
	
	ecbURI= "http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml";
	
	if (window.XMLHttpRequest) {
		req5 = new XMLHttpRequest();		
		req5.overrideMimeType("text/xml");
		req5.open("GET", ecbURI, true);
		req5.setRequestHeader("Cache-Control", "no-cache");
		req5.onreadystatechange = function(e) {parseQuoteData_ecb(e, req5);}
		req5.send(null);
	}
	
	total_errors = 0;
	
    quote_req_stop_timeout_palple = false; // se true, è stata fatta un abort quindi niente gestione del timeout
	quote_req_timeout_palple = false;
	quote_req_stop_timeout_ecb = false; // se true, è stata fatta un abort quindi niente gestione del timeout
	quote_req_timeout_ecb = false;
	setTimeout("quote_req_send_timeout_ecb();",18000);
    setTimeout("quote_req_send_timeout_palple();",18000);
}

function quote_req_send_timeout_ecb()
{
	if (quote_req_stop_timeout_ecb){return;}
	quote_req_timeout_ecb = true; // vado in ecb con il timeout
    
    parseQuoteData_ecb(null, req5);
}

function quote_req_send_timeout_palple()
{
	if (quote_req_stop_timeout_palple){return;}
	quote_req_timeout_palple = true; // vado in ecb con il timeout
    
    parseQuoteData_palple(null, req4);
}

function quote_req_send_timeout_palple_2()
{
	if (quote_req_stop_timeout_palple_2){return;}
	quote_req_timeout_palple = true; // vado in ecb con il timeout
    
    parseQuoteData_palple(null, reqN);
}


function parseQuoteData_ecb(e, request)
{
    if (quote_req_timeout_ecb) {
		try{
            request.abort();
        } catch (ex) {}
		//currency_status.innerText = getLocalizedString('error_updating');
		//status_text.innerText = getLocalizedString('error_updating');
		//status_date.innerText = "";
		//load_saved_currencies_data();
        quote_req_stop_timeout_ecb = true;
		
		if (throbber_visibile > 0){
			throbber_visibile -= 1;
			
			if (throbber_visibile == 0){throb.stop();retrieving.setAttribute ("style", "display:none;");}
		}
		
		return;
	}
    
	if (request.readyState == 4) {
		if (throbber_visibile > 0){
			throbber_visibile -= 1;
			
			if (throbber_visibile == 0){throb.stop();retrieving.setAttribute ("style", "display:none;");}
		}
		
		if (request.status == 200){
			var current_rate, cube_currency, cube_currency, array_code, current_code;
			
			cube_currency = request.responseXML.getElementsByTagName("Cube");
			
			for (var i = 0; i < ecb_euroconversion.length; i++) { // convert ecb_euroconversion to hash_table
    			ecb_euroconversion[ecb_euroconversion[i].name] = ecb_euroconversion[i];
			}

			try{
				for (j=0;j<cube_currency.length;j++){
					current_code = cube_currency[j].getAttribute("currency");
					if (!isNotInizialized(current_code)){
						current_rate = cube_currency[j].getAttribute("rate");
						
						if (!isNotInizialized(current_rate)){
							array_code = "ecb_" + current_code;
							
                            try{
                                ecb_euroconversion[array_code].value = current_rate;
                            } catch(ex) {
                                
                            }
						}
					}
				}
			} catch(ex) {RoundPlugin.logMessage("missing ecb currency on: " + array_code);}
            
            saveTheNewValues_ecb();
		}
		else
		{
			// error retrieving data
			error_retrieving_ecb = true;
            
            try{
                request.abort();
            } catch(ex) {}
		}
        
        quote_req_stop_timeout_ecb = true;
        		
		retrieve_data_done++;
	}
}

function handleDownloadError ()
{
    if (total_errors > 2){ // tutti errori, resettiamo e riproveremo in futuro
        total_errors = 0;
        return;
    }
    
    while (fetchURI == currentURI){ // switch to the other
        fetchURI = fetchURIs[Math.floor(Math.random()*2)];
    }
    
    currentURI = fetchURI;
    
    if (window.XMLHttpRequest) {
        reqN = new XMLHttpRequest();		
        reqN.overrideMimeType("text/xml");
        reqN.open("GET", fetchURI, true);
        reqN.setRequestHeader("Cache-Control", "no-cache");
        reqN.onreadystatechange = function(e) {parseQuoteData_palple(e, reqN);}
        reqN.send(null);
    }
    
    quote_req_stop_timeout_palple_2 = false;
    quote_req_timeout_palple = false;
    setTimeout("quote_req_send_timeout_palple_2();",18000);
}

function parseQuoteData_palple(e, request)
{
    if (quote_req_timeout_palple) {
		try{
            request.abort();
        } catch (ex) {}
        
        quote_req_stop_timeout_palple = true;
        quote_req_stop_timeout_palple_2 = true;
		//currency_status.innerText = getLocalizedString('error_updating');
		//status_text.innerText = getLocalizedString('error_updating');
		//status_date.innerText = "";
		load_saved_currencies_data();
		
		if (throbber_visibile > 0){
			throbber_visibile -= 1;
			
			if (throbber_visibile == 0){throb.stop();retrieving.setAttribute ("style", "display:none;");}
		}
		
		total_errors ++;
		
		handleDownloadError();
		
		return;
	}
	
	if (request.readyState == 4) {
		if (throbber_visibile > 0){
			throbber_visibile -= 1;
			
			if (throbber_visibile == 0){throb.stop();retrieving.setAttribute ("style", "display:none;");}
		}
		
		if (request.status == 200){ // we are ok
			
			//quote_req_stop_timeout = true;
			
			var the_data = request.responseText;
            
            // riempio tutti gli array con questi dati
            // anche la data di aggiornamento
            var quoteLines, quoteParts;
			var line;
            var the_data_array = [];
			
			quoteLines = the_data.split("\n");
            
            //var codes = "";
            			
			for (line = 0; line < quoteLines.length; line++)
			{
                if (line == 0){ // url
                
                } else if (line == 1){
                    // setta la last update date a partire da questo valore
                    var new_data_date_downloaded = parseInt(quoteLines[line]);
                    
                    // qui creo una data provvisioria per provare a vedere se abbiamo un'ora ok, altrimenti errore                    
                    var new_date = new Date();
                    new_date.setTime(new_data_date_downloaded*1000);
                    var seconds = new_date.getUTCSeconds();
                    
                    if (isNaN(seconds)){ // bad
                        total_errors ++;
                        
                        request.abort();
                        
                        handleDownloadError();
                        
                        return;
                    } else {// good
                        new_data_date = new_data_date_downloaded;
                        
                        currency_date = new_date.toUTCString();
                    }
                } else {
                    try{
                        quoteParts = quoteLines[line].split("=");
												
                        if (isNotInizialized(quoteParts[0])) {continue;} // in caso di dato mancante lascio quello di prima
                        if (isNotInizialized(quoteParts[1])) {continue;} // in caso di dato mancante lascio quello di prima
                        
                        var current_new_rate = parseFloat(quoteParts[1]);
                        
                        if (current_new_rate < 0) { current_new_rate = current_new_rate * -1 }
                        
                        the_data_array[quoteParts[0]] = current_new_rate; // array[code] = value
                        
                        //codes += '"' + quoteParts[0] + '",';
                        
                    } catch(ex) {}
                }
            }
            
            //RoundPlugin.logMessage(codes);
			
            // devo normalizzare per l'euro
            if (!isNaN(the_data_array["EUR"])) {palple_eur = the_data_array["EUR"];}
            
            //palple_eur = the_data_array["EUR"];
            
            for (i=0;i<palple_extraeu.length;i++){
                try{if (!isNaN(the_data_array[palple_extraeu[i].name])) { palple_extraeu[i].value = the_data_array[palple_extraeu[i].name]/palple_eur }} catch (ex) {}
            }
            
            for (i=0;i<euroconversion.length;i++){
                try{if (!isNaN(the_data_array[euroconversion[i].name])) { euroconversion[i].value = the_data_array[euroconversion[i].name]/palple_eur }} catch (ex) {}
            }
            
            for (i=0;i<extraeu_main_euroconversion.length;i++){
            	try{if (!isNaN(the_data_array[extraeu_main_euroconversion[i].name])) { extraeu_main_euroconversion[i].value = the_data_array[extraeu_main_euroconversion[i].name]/palple_eur }} catch (ex) {}
            }
            
            for (i=0;i<extraeu_euroconversion.length;i++){
                //if (extraeu_euroconversion[i].name == "SDG") {RoundPlugin.logMessage("SDG=" + the_data_array[extraeu_euroconversion[i].name]);}
                try{if (!isNaN(the_data_array[extraeu_euroconversion[i].name])) { extraeu_euroconversion[i].value = the_data_array[extraeu_euroconversion[i].name]/palple_eur }} catch (ex) {}
            }
            
            for (i=0;i<virtual_currencies.length;i++){
            	try{if (!isNaN(the_data_array[virtual_currencies[i].name])) { virtual_currencies[i].value = the_data_array[virtual_currencies[i].name]/palple_eur }} catch (ex) {}
            }
            
            for (i=0;i<commodities_currencies.length;i++){
            	try{if (!isNaN(the_data_array[commodities_currencies[i].name])) { commodities_currencies[i].value = the_data_array[commodities_currencies[i].name]/palple_eur }} catch (ex) {}
            }
            
            for (i=0;i<unrecognized_currencies.length;i++){
            	try{if (!isNaN(the_data_array[unrecognized_currencies[i].name])) { unrecognized_currencies[i].value = the_data_array[unrecognized_currencies[i].name]/palple_eur }} catch (ex) {}
            }
            
            for (i=0;i<old_currencies.length;i++){
            	try{if (!isNaN(the_data_array[old_currencies[i].name])) { old_currencies[i].value = the_data_array[old_currencies[i].name]/palple_eur }} catch (ex) {}
            }
            
            saveTheNewValues();
            
        }
		else
		{ // error
			// error retrieving data
            request.abort();
			//currency_status.innerText = getLocalizedString('error_updating');
			//status_text.innerText = getLocalizedString('error_updating');
			//status_date.innerText = "";
			load_saved_currencies_data();
			
			if (throbber_visibile > 0){
				throbber_visibile -= 1;
				
				if (throbber_visibile == 0){throb.stop();retrieving.setAttribute ("style", "display:none;");}
			}
			
			total_errors ++;
            
            try{
                request.abort();
            } catch(ex) {}
			
            quote_req_stop_timeout_palple = true;
            quote_req_stop_timeout_palple_2 = true;
            
			handleDownloadError();
            
            return;
		}
		
        quote_req_stop_timeout_palple = true;
        quote_req_stop_timeout_palple_2 = true;
        
		retrieve_data_done++;
	}
}

function saveTheNewValues_ecb()
{
	if (retrieve_data_done == 0) return;
	
	retrieve_data_done = 0;
	
	if (error_retrieving_ecb){ // al primo errore ristabilisco i vecchi dati dalle preferenze
		error_retrieving_ecb = false; // resetto
	}
	else // tutto ok nell'aggiornamento
	{
		write_currencies_data(); // salvo i nuovi dati nelle preferenze
		
		// forzo il ricalcolo con i nuovi cambi
		if (widget_style == 0){
			//convertAmount(document.getElementById('valuta1').value, "left");
		} else {
			document.getElementById("value_field_" + last_selected_value.position).value = last_selected_value.value;
			convert_values(last_selected_value.position);
		}
	}
}

function saveTheNewValues()
{
	if (retrieve_data_done == 0) return;
	
	retrieve_data_done = 0;
	
	if (error_retrieving_palple){ // al primo errore ristabilisco i vecchi dati dalle preferenze!
		//currency_status.innerText = getLocalizedString('error_updating');
		status_text.innerText = getLocalizedString('error_updating');
		status_date.innerText = "";
		load_saved_currencies_data(); // ristabilisco i vecchi dati
		
		error_retrieving_palple = false; // resetto
	}
	else // tutto ok nell'aggiornamento
	{
		write_currencies_data(); // salvo i nuovi dati nelle preferenze
		
        // creo una data a partire dalla stringa new_data_date letta nei dati
		// aggiorno la data di aggiornamento e la registro nelle preferenze
		current_date = new Date(); //ovviamente solo se l'ho effettivamente aggiornato ora
		current_date.setTime(new_data_date*1000);
        
		widget.setPreferenceForKey(current_date.toUTCString(), "currency_date");
        currency_date = current_date.toUTCString();
        
		var dateStr = current_date.toLocaleDateString("short");
		var timeStr = current_date.toLocaleTimeString("short");
		
		// scrivo la data di aggiornamento nel campo currency_status del widget
		//currency_status.innerText = getLocalizedString('currency_status') + dateStr + " " + timeStr;
		status_text.innerText = getLocalizedString('currency_status');
		status_date.innerText = dateStr + " " + timeStr;
		//currency_status.setAttribute ("title", getLocalizedString('currency_status_tooltip'));
		//currency_status.setAttribute ("onmouseup", "javascript:update_currencies_data();");
		
		// forzo il ricalcolo con i nuovi cambi
		if (widget_style == 0){
			//convertAmount(document.getElementById('valuta1').value, "left");
		} else {
			document.getElementById("value_field_" + last_selected_value.position).value = last_selected_value.value;
			convert_values(last_selected_value.position);
		}
	}
}

/*
function update_daily()
{
	currency_date_UTC = widget.preferenceForKey ("currency_date");
	
	if (currency_date_UTC == undefined){
		currency_date = new Date(currency_original_quote_date);
		currency_date_UTC = currency_date.toUTCString();
		widget.setPreferenceForKey(currency_date_UTC, "currency_date");
	}
	else {
		currency_date = new Date(currency_date_UTC);
	}
	
	// ora controllo se √® passato pi√π di un giorno
	var nowInMS = (new Date()).getTime();
	
	var lastUpdatedInMS = currency_date.getTime();
		
	if ((nowInMS - lastUpdatedInMS) > (24*60*60*1000)) {update_currencies_data(); version_check();} // 1 giorno di differenza
}*/


// scrive i dati nelle preferenze


function createDataJSString (theArray)
{
	var str = "[";
	var c = theArray.length;
	
	for (var i = 0; i < c; ++i)
	{
		var data = theArray[i];
		if (i != 0)
			str += ",";
		// make sure the name does not have any single quotes in it
		var name = data.name.replace(/\'/g, "\\'"); //"
		str += "{name:'" + data.name + "',value:'" + data.value + "'}";
	}
	
	str += "];";
	
	return str;
}

function write_currencies_data()
{
	pref = createDataJSString(euroconversion);
	widget.setPreferenceForKey (pref, "euroconversion_current_currency_list");
	//RoundPlugin.logMessage(pref);
	pref = createDataJSString(extraeu_main_euroconversion);
	widget.setPreferenceForKey (pref, "extraeu_main_euroconversion_current_currency_list");
	//RoundPlugin.logMessage(pref);
	pref = createDataJSString(extraeu_euroconversion);
	widget.setPreferenceForKey (pref, "extraeu_euroconversion_current_currency_list");
	//RoundPlugin.logMessage(pref);
	pref = createDataJSString(ecb_euroconversion);
	widget.setPreferenceForKey (pref, "ecb_euroconversion_current_currency_list");
	//RoundPlugin.logMessage(pref);
	pref = createDataJSString(palple_extraeu);
	widget.setPreferenceForKey (pref, "palple_extraeu_current_currency_list");
	//RoundPlugin.logMessage(pref);
	
	widget.setPreferenceForKey (palple_eur, "palple_eur");
	//RoundPlugin.logMessage(palple_eur);
	
	pref = createDataJSString(virtual_currencies);
	widget.setPreferenceForKey (pref, "virtual_currencies");
	//RoundPlugin.logMessage(pref);
	
	pref = createDataJSString(commodities_currencies);
	widget.setPreferenceForKey (pref, "commodities_currencies");
	//RoundPlugin.logMessage(pref);
	
	pref = createDataJSString(unrecognized_currencies);
	widget.setPreferenceForKey (pref, "unrecognized_currencies");
	//RoundPlugin.logMessage(pref);
	
	widget.setPreferenceForKey(fetch_from_site, "fetch_from_site");
	//widget.setPreferenceForKey(currency_date.toString(), "currency_date");
	//RoundPlugin.logMessage(currency_date.toString());
}

function linearForm(a,b)
{
	if ((a != null) && (b != null)) {
		return function(x) {return a*x + b;};
	} else if (a != null) {
		return function(x) {return a*x;};
	}
	alert("linearForm - bad args a = "+a+" b = "+b);
}

function invLinForm(a,b)
{
	if ((a != null) && (b != null)) {
		return function(y) {return (y-b)/a;};
	} else if (a != null) {
		return function(y) {return y/a;};
	} 
	alert("invLinForm - bad args a = "+a+" b = "+b);
}

function removeAllChildren (parent)
{
	while (parent.hasChildNodes())
		parent.removeChild(parent.firstChild);
}

function getCountryCodeFromIso(iso_code)
{
	// devo ottenere il country_code dall'iso_code, ovvero devo ottenere il country_code principale (esempio: eur per l'euro, usa per l'usd, etc.)		
	for (i=0;i<all_currencies_associative.length;i++){
		if (all_currencies_associative[i].currency == iso_code){
			try {
				is_multiple = all_currencies_associative[i].multiple;
				if (isNotInizialized(is_multiple)) return all_currencies_associative[i].country;
			} catch (ex){return all_currencies_associative[i].country;}
		}
	}
}

function getCountryNameFromIso(iso_code)
{
	// devo ottenere il country_code dall'iso_code, ovvero devo ottenere il country_cod principale (esempio: eur per l'euro, usa per l'usd, etc.)	
	//RoundPlugin.logMessage("iso to search: " + iso_code);
	country_code = getCountryCodeFromIso(iso_code);
	
	try {toReturn = country_names[country_code].name} catch (ex) {return "undefined";}
	//RoundPlugin.logMessage("country code found: " + country_code + "from iso: " + iso_code);
	return toReturn;
}

function getCountryName(country_code)
{
	try {toReturn = country_names[country_code].name} catch (ex) {return "undefined";}
	
	return toReturn;
	//return country_names[country_code].name;
}

function populateArrays()
{
	var unitArray = euroconversion;
	yahoo_unitArray = unitArray.concat(extraeu_main_euroconversion,extraeu_euroconversion,palple_extraeu);
	
	for (var i=0; i< yahoo_unitArray.length; i++){
		yahoo_unitArray[i].localized = getLocalizedString(yahoo_unitArray[i].name);
		yahoo_unitArray[i].country_name = getCountryNameFromIso(yahoo_unitArray[i].name);
		yahoo_unitArray[i].country = getCountryCodeFromIso(yahoo_unitArray[i].name);
	}
	
	for (var i=0; i< legacy_euroconversion.length; i++){
		legacy_euroconversion[i].localized = getLocalizedString(legacy_euroconversion[i].name);
		legacy_euroconversion[i].country_name = getCountryNameFromIso(legacy_euroconversion[i].name);
		legacy_euroconversion[i].country = getCountryCodeFromIso(legacy_euroconversion[i].name);
	}
	
	/*
	for (var i=0; i< palple_extraeu.length; i++){
		palple_extraeu[i].localized = getLocalizedString(palple_extraeu[i].name);
		palple_extraeu[i].country_name = getCountryNameFromIso(palple_extraeu[i].name);
		palple_extraeu[i].country = getCountryCodeFromIso(palple_extraeu[i].name);
	}*/
	
	for (var i=0; i< virtual_currencies.length; i++){
		virtual_currencies[i].localized = getLocalizedString(virtual_currencies[i].name);
		virtual_currencies[i].country_name = getCountryNameFromIso(virtual_currencies[i].name);
		virtual_currencies[i].country = getCountryCodeFromIso(virtual_currencies[i].name);
	}
	
	for (var i=0; i< commodities_currencies.length; i++){
		commodities_currencies[i].localized = getLocalizedString(commodities_currencies[i].name);
		commodities_currencies[i].country_name = getCountryNameFromIso(commodities_currencies[i].name);
		commodities_currencies[i].country = getCountryCodeFromIso(commodities_currencies[i].name);
	}
	
	for (var i=0; i< unrecognized_currencies.length; i++){
		unrecognized_currencies[i].localized = getLocalizedString(unrecognized_currencies[i].name);
		unrecognized_currencies[i].country_name = getCountryNameFromIso(unrecognized_currencies[i].name);
		unrecognized_currencies[i].country = getCountryCodeFromIso(unrecognized_currencies[i].name);
	}
	
	for (var i=0; i< old_currencies.length; i++){
		old_currencies[i].localized = getLocalizedString(old_currencies[i].name);
		old_currencies[i].country_name = getCountryNameFromIso(old_currencies[i].name);
		old_currencies[i].country = getCountryCodeFromIso(old_currencies[i].name);
	}
	
	ecb_euroconversion_associative = ecb_euroconversion;
	
	for (var i=0; i< ecb_euroconversion.length; i++){
		iso_code = ecb_euroconversion[i].name;
		iso_code = iso_code.substring(4);
		ecb_euroconversion_associative[i].localized = getLocalizedString(iso_code);
		ecb_euroconversion_associative[i].country_name = getCountryNameFromIso(iso_code);
		ecb_euroconversion_associative[i].country = getCountryCodeFromIso(iso_code);
		//RoundPlugin.logMessage(ecb_euroconversion[i].country);
	}
	
	all_active_unitArray = yahoo_unitArray.concat(unrecognized_currencies);
	allLegacyArray = legacy_euroconversion.concat(old_currencies);
	
	for (var i=0; i< currency_used_associative.length; i++){
		currency_used_associative[i].localized = getLocalizedString(currency_used_associative[i].currency);
		currency_used_associative[i].country_name = getCountryName(currency_used_associative[i].country);
	}
	
	for (var i=0; i< commodities_associative.length; i++){
		commodities_associative[i].localized = getLocalizedString(commodities_associative[i].currency);
		commodities_associative[i].country_name = getCountryName(commodities_associative[i].country);
	}
	
	for (var i=0; i< unrecognized_currencies_associative.length; i++){
		unrecognized_currencies_associative[i].localized = getLocalizedString(unrecognized_currencies_associative[i].currency);
		unrecognized_currencies_associative[i].country_name = getCountryName(unrecognized_currencies_associative[i].country);
	}
			
	for (var i=0; i< european_legacy_associative.length; i++){
		european_legacy_associative[i].localized = getLocalizedString(european_legacy_associative[i].currency);
		european_legacy_associative[i].country_name = getCountryName(european_legacy_associative[i].country);
	}
	
	for (var i=0; i< old_currencies_associative.length; i++){
		old_currencies_associative[i].localized = getLocalizedString(old_currencies_associative[i].currency);
		old_currencies_associative[i].country_name = getCountryName(old_currencies_associative[i].country);
	}
	
	for (var i=0; i< virtual_currencies_associative.length; i++){
		virtual_currencies_associative[i].localized = getLocalizedString(virtual_currencies_associative[i].currency);
		virtual_currencies_associative[i].country_name = getCountryName(virtual_currencies_associative[i].country);
	}
	
	all_active_unitArray_associative = currency_used_associative.concat(unrecognized_currencies_associative);
	allLegacyArray_associative = european_legacy_associative.concat(old_currencies_associative);
}

function sortArrays()
{
	if (sections && !by_country) { // plain list
		// ordino gli array
		if (by_name) {yahoo_unitArray.sort(compareNames);} else {yahoo_unitArray.sort(compareCodes);}
		if (by_name) {legacy_euroconversion.sort(compareNames);} else {legacy_euroconversion.sort(compareCodes);}
		//if (by_name) {palple_extraeu.sort(compareNames);} else {palple_extraeu.sort(compareCodes);}
		if (by_name) {virtual_currencies.sort(compareNames);} else {virtual_currencies.sort(compareCodes);}
		if (by_name) {unrecognized_currencies.sort(compareNames);} else {unrecognized_currencies.sort(compareCodes);}
		if (by_name) {old_currencies.sort(compareNames);} else {old_currencies.sort(compareCodes);}
		if (by_name) {ecb_euroconversion_associative.sort(compareNames);} else {ecb_euroconversion_associative.sort(compareCodes);}
		if (by_name) {commodities_currencies.sort(compareNames);} else {commodities_currencies.sort(compareCodes);}
	} else if (!sections && !by_country) { // unica lista per le active, escludo le legacy (che fondo insieme)
		if (by_name) {all_active_unitArray.sort(compareNames);} else {all_active_unitArray.sort(compareCodes);}
		if (by_name) {allLegacyArray.sort(compareNames);} else {allLegacyArray.sort(compareCodes);}
		if (by_name) {virtual_currencies.sort(compareNames);} else {virtual_currencies.sort(compareCodes);}
		if (by_name) {ecb_euroconversion_associative.sort(compareNames);} else {ecb_euroconversion_associative.sort(compareCodes);}
		if (by_name) {commodities_currencies.sort(compareNames);} else {commodities_currencies.sort(compareCodes);}
	} else if (!sections && by_country) { // unica lista per le active, escludo le legacy (che fondo insieme)
		all_active_unitArray_associative.sort(compareCountryNames);
		allLegacyArray_associative.sort(compareCountryNames);
		virtual_currencies_associative.sort(compareCountryNames);
		commodities_associative.sort(compareCountryNames);
		ecb_euroconversion_associative.sort(compareCountryNames);
	} else if (sections && by_country) {
		currency_used_associative.sort(compareCountryNames);
		unrecognized_currencies_associative.sort(compareCountryNames);
		european_legacy_associative.sort(compareCountryNames);
		old_currencies_associative.sort(compareCountryNames);
		virtual_currencies_associative.sort(compareCountryNames);
		ecb_euroconversion_associative.sort(compareCountryNames);
		commodities_associative.sort(compareCountryNames);
	}
}

function populatePopups(select, to_select)
{
	removeAllChildren(select);
	
	select.innerHTML = document.getElementById("default_select").innerHTML;
	
	// mi serve la lista delle options del popup
	var popupLength = select.options.length;
	
	for (var i=0;i<popupLength;i++){
		if (!by_country){
			if (select.options[i].getAttribute("name") == table_elements[to_select].currency) {select.options[i].setAttribute("selected",true);}
		} else {
			if ((select.options[i].getAttribute("name") == table_elements[to_select].currency) && (select.options[i].getAttribute("value") == table_elements[to_select].country)) {select.options[i].setAttribute("selected",true);}
		}
	}
}

function populatePopup(select, to_select) // to_select = elemento da selezionare da tabella
{
	removeAllChildren(select);
	
	if (sections && !by_country) { // plain list
		var currencies = yahoo_unitArray;
		var numCur = currencies.length;
		
		var opt_element = document.createElement("optgroup");
		opt_element.setAttribute("label",getLocalizedString("live_currencies"));
		
		for (var j = 0; j < numCur; j++)
		{
			var element = document.createElement("option");
			//element.innerText = getLocalizedString(currencies[j].name);
			if (by_country) {element.innerText = getCountryNameFromIso(currencies[j].name) + " - " + getLocalizedString(currencies[j].name) + " (" + currencies[j].name + ")";} else if (by_name) {element.innerText = getLocalizedString(currencies[j].name) + " (" + currencies[j].name + ")";} else {element.innerText = currencies[j].name + " - " + getLocalizedString(currencies[j].name);}
			element.setAttribute("name",currencies[j].name);
			element.setAttribute("value",currencies[j].country);
			//if (currencies[j].name == table_elements[to_select].currency) {element.setAttribute("selected",true);}
			opt_element.appendChild(element);
		}
		
		select.appendChild(opt_element);
		
		/*
		var currencies = palple_extraeu;
		var numCur = currencies.length;
		
		var opt_element = document.createElement("optgroup");
		opt_element.setAttribute("label",getLocalizedString("palple_extraeu"));
		
		for (var j = 0; j < numCur; j++)
		{
			var element = document.createElement("option");
			//element.innerText = getLocalizedString(currencies[j].name);
			if (by_country) {element.innerText = getCountryNameFromIso(currencies[j].name) + " - " + getLocalizedString(currencies[j].name) + " (" + currencies[j].name + ")";} else if (by_name) {element.innerText = getLocalizedString(currencies[j].name) + " (" + currencies[j].name + ")";} else {element.innerText = currencies[j].name + " - " + getLocalizedString(currencies[j].name);}
			element.setAttribute("name",currencies[j].name);
			element.setAttribute("value",currencies[j].country);
			//if (currencies[j].name == table_elements[to_select].currency) {element.setAttribute("selected",true);}
			opt_element.appendChild(element);
		}
		
		select.appendChild(opt_element);*/
		
		
		var currencies = ecb_euroconversion_associative;
		var numCur = currencies.length;
		
		var opt_element = document.createElement("optgroup");
		opt_element.setAttribute("label",getLocalizedString("ecb_euroconversion"));
		
		for (var j = 0; j < numCur; j++)
		{
			var element = document.createElement("option");
			iso_code = currencies[j].name;
			iso_code = iso_code.substring(4);
			
			//RoundPlugin.logMessage(getCountryNameFromIso(iso_code) + ";" + iso_code);
			if (by_country) {element.innerText = getCountryNameFromIso(iso_code) + " - " + getLocalizedString(iso_code) + " (" + iso_code + ")";} else if (by_name) {element.innerText = getLocalizedString(iso_code) + " (" + iso_code + ")";} else {element.innerText = iso_code + " - " + getLocalizedString(iso_code);}
			element.setAttribute("name",currencies[j].name);
			element.setAttribute("value",currencies[j].country);
			//if (currencies[j].name == table_elements[to_select].currency) {element.setAttribute("selected",true);}
			opt_element.appendChild(element);
		}
		
		select.appendChild(opt_element);
		
		// unrecognized currencies
		var currencies = unrecognized_currencies;
		var numCur = currencies.length;
				
		var opt_element = document.createElement("optgroup");
		opt_element.setAttribute("label",getLocalizedString("unrecognized_currencies"));
		
		for (var j = 0; j < numCur; j++)
		{
			var element = document.createElement("option");
			//element.innerText = getLocalizedString(currencies[j].name);
			iso_code = currencies[j].name;
			
			if (by_country) {element.innerText = getCountryNameFromIso(currencies[j].name) + " - " + getLocalizedString(currencies[j].name) + " (" + currencies[j].name + ")";} else if (by_name) {element.innerText = getLocalizedString(iso_code) + " (" + iso_code + ")";} else {element.innerText = iso_code + " - " + getLocalizedString(iso_code);}
			element.setAttribute("name",currencies[j].name);
			element.setAttribute("value",currencies[j].country);
			//if (currencies[j].name == table_elements[to_select].currency) {element.setAttribute("selected",true);}
			opt_element.appendChild(element);
		}
		
		select.appendChild(opt_element);
		
		
		// european old currencies
		var currencies = legacy_euroconversion;
		var numCur = currencies.length;
		
		var opt_element = document.createElement("optgroup");
		opt_element.setAttribute("label",getLocalizedString("euro_legacy"));
		
		for (var j = 0; j < numCur; j++)
		{
			var element = document.createElement("option");
			//element.innerText = getLocalizedString(currencies[j].name);
			if (by_country) {element.innerText = getCountryNameFromIso(currencies[j].name) + " - " + getLocalizedString(currencies[j].name) + " (" + currencies[j].name + ")";} else if (by_name) {element.innerText = getLocalizedString(currencies[j].name) + " (" + currencies[j].name + ")";} else {element.innerText = currencies[j].name + " - " + getLocalizedString(currencies[j].name);}
			element.setAttribute("name",currencies[j].name);
			element.setAttribute("value",currencies[j].country);
			
			//if (currencies[j].name == table_elements[to_select].currency) {element.setAttribute("selected",true);}
			opt_element.appendChild(element);
		}
		
		select.appendChild(opt_element);
		
		// old currencies
		var currencies = old_currencies;
		var numCur = currencies.length;
		
		var opt_element = document.createElement("optgroup");
		opt_element.setAttribute("label",getLocalizedString("old_currencies"));
		
		for (var j = 0; j < numCur; j++)
		{
			var element = document.createElement("option");
			//element.innerText = getLocalizedString(currencies[j].name);
			iso_code = currencies[j].name;
			
			if (by_country) {element.innerText = getCountryNameFromIso(currencies[j].name) + " - " + getLocalizedString(currencies[j].name) + " (" + currencies[j].name + ")";} else if (by_name) {element.innerText = getLocalizedString(iso_code) + " (" + iso_code + ")";} else {element.innerText = iso_code + " - " + getLocalizedString(iso_code);}
			element.setAttribute("name",currencies[j].name);
			element.setAttribute("value",currencies[j].country);
			//if (currencies[j].name == table_elements[to_select].currency) {element.setAttribute("selected",true);}
			opt_element.appendChild(element);
		}
		
		select.appendChild(opt_element);
		
		// virtual currencies
		var currencies = virtual_currencies;
		var numCur = currencies.length;
		
		var opt_element = document.createElement("optgroup");
		opt_element.setAttribute("label",getLocalizedString("virtual_currencies"));
		
		for (var j = 0; j < numCur; j++)
		{
			var element = document.createElement("option");
			//element.innerText = getLocalizedString(currencies[j].name);
			iso_code = currencies[j].name;
			
			if (by_country) {element.innerText = getCountryNameFromIso(currencies[j].name) + " - " + getLocalizedString(currencies[j].name) + " (" + currencies[j].name + ")";} else if (by_name) {element.innerText = getLocalizedString(iso_code) + " (" + iso_code + ")";} else {element.innerText = iso_code + " - " + getLocalizedString(iso_code);}
			element.setAttribute("name",currencies[j].name);
			element.setAttribute("value",currencies[j].country);
			//if (currencies[j].name == table_elements[to_select].currency) {element.setAttribute("selected",true);}
			opt_element.appendChild(element);
		}
		
		select.appendChild(opt_element);
		
		
		// commodities
		var currencies = commodities_currencies;
		var numCur = currencies.length;
		
		var opt_element = document.createElement("optgroup");
		opt_element.setAttribute("label",getLocalizedString("commodities_currencies"));
		
		for (var j = 0; j < numCur; j++)
		{
			var element = document.createElement("option");
			//element.innerText = getLocalizedString(currencies[j].name);
			iso_code = currencies[j].name;
			
			if (by_country) {element.innerText = getCountryNameFromIso(currencies[j].name) + " - " + getLocalizedString(currencies[j].name) + " (" + currencies[j].name + ")";} else if (by_name) {element.innerText = getLocalizedString(iso_code) + " (" + iso_code + ")";} else {element.innerText = iso_code + " - " + getLocalizedString(iso_code);}
			element.setAttribute("name",currencies[j].name);
			element.setAttribute("value",currencies[j].country);
			//if (currencies[j].name == table_elements[to_select].currency) {element.setAttribute("selected",true);}
			opt_element.appendChild(element);
		}
		
		select.appendChild(opt_element);
	} else  if (!sections && !by_country) { // unica lista per le active, escludo le legacy (che fondo insieme)
		var currencies = all_active_unitArray;
		var numCur = currencies.length;
		
		var opt_element = document.createElement("optgroup");
		opt_element.setAttribute("label",getLocalizedString("all_currencies"));
				
		for (var j = 0; j < numCur; j++)
		{
			var element = document.createElement("option");
			//element.innerText = getLocalizedString(currencies[j].name);
			if (by_country) {element.innerText = getCountryNameFromIso(currencies[j].name) + " - " + getLocalizedString(currencies[j].name) + " (" + currencies[j].name + ")";} else if (by_name) {element.innerText = getLocalizedString(currencies[j].name) + " (" + currencies[j].name + ")";} else {element.innerText = currencies[j].name + " - " + getLocalizedString(currencies[j].name);}
			element.setAttribute("name",currencies[j].name);
			element.setAttribute("value",currencies[j].country);
			//RoundPlugin.logMessage("country: " + element.getAttribute("value"));
			//if (currencies[j].name == table_elements[to_select].currency) {element.setAttribute("selected",true);}
			opt_element.appendChild(element);
		}
		
		select.appendChild(opt_element);
		
		
		var currencies = allLegacyArray;
		var numCur = currencies.length;
		
		var opt_element = document.createElement("optgroup");
		opt_element.setAttribute("label",getLocalizedString("all_legacy"));
		
		for (var j = 0; j < numCur; j++)
		{
			var element = document.createElement("option");
			//element.innerText = getLocalizedString(currencies[j].name);
			if (by_country) {element.innerText = getCountryNameFromIso(currencies[j].name) + " - " + getLocalizedString(currencies[j].name) + " (" + currencies[j].name + ")";} else if (by_name) {element.innerText = getLocalizedString(currencies[j].name) + " (" + currencies[j].name + ")";} else {element.innerText = currencies[j].name + " - " + getLocalizedString(currencies[j].name);}
			element.setAttribute("name",currencies[j].name);
			element.setAttribute("value",currencies[j].country);
			//if (currencies[j].name == table_elements[to_select].currency) {element.setAttribute("selected",true);}
			opt_element.appendChild(element);
		}
		
		select.appendChild(opt_element);
		
		
		var currencies = ecb_euroconversion_associative;
		var numCur = currencies.length;
		
		var opt_element = document.createElement("optgroup");
		opt_element.setAttribute("label",getLocalizedString("ecb_euroconversion"));
		
		for (var j = 0; j < numCur; j++)
		{
			var element = document.createElement("option");
			//element.innerText = getLocalizedString(currencies[j].name);
			iso_code = currencies[j].name;
			iso_code = iso_code.substring(4);
			
			if (by_country) {element.innerText = getCountryNameFromIso(iso_code) + " - " + getLocalizedString(iso_code) + " (" + iso_code + ")";} else if (by_name) {element.innerText = getLocalizedString(iso_code) + " (" + iso_code + ")";} else {element.innerText = iso_code + " - " + getLocalizedString(iso_code);}
			element.setAttribute("name",currencies[j].name);
			element.setAttribute("value",currencies[j].country);
			//if (currencies[j].name == table_elements[to_select].currency) {element.setAttribute("selected",true);}
			opt_element.appendChild(element);
		}
		
		select.appendChild(opt_element);
		
		
		// virtual currencies
		var currencies = virtual_currencies;
		var numCur = currencies.length;
		
		var opt_element = document.createElement("optgroup");
		opt_element.setAttribute("label",getLocalizedString("virtual_currencies"));
		
		for (var j = 0; j < numCur; j++)
		{
			var element = document.createElement("option");
			//element.innerText = getLocalizedString(currencies[j].name);
			iso_code = currencies[j].name;
			
			if (by_country) {element.innerText = getCountryNameFromIso(currencies[j].name) + " - " + getLocalizedString(currencies[j].name) + " (" + currencies[j].name + ")";} else if (by_name) {element.innerText = getLocalizedString(iso_code) + " (" + iso_code + ")";} else {element.innerText = iso_code + " - " + getLocalizedString(iso_code);}
			element.setAttribute("name",currencies[j].name);
			element.setAttribute("value",currencies[j].country);
			//if (currencies[j].name == table_elements[to_select].currency) {element.setAttribute("selected",true);}
			opt_element.appendChild(element);
		}
		
		select.appendChild(opt_element);
		
		
		// commodities
		var currencies = commodities_currencies;
		var numCur = currencies.length;
		
		var opt_element = document.createElement("optgroup");
		opt_element.setAttribute("label",getLocalizedString("commodities_currencies"));
		
		for (var j = 0; j < numCur; j++)
		{
			var element = document.createElement("option");
			//element.innerText = getLocalizedString(currencies[j].name);
			iso_code = currencies[j].name;
			
			if (by_country) {element.innerText = getCountryNameFromIso(currencies[j].name) + " - " + getLocalizedString(currencies[j].name) + " (" + currencies[j].name + ")";} else if (by_name) {element.innerText = getLocalizedString(iso_code) + " (" + iso_code + ")";} else {element.innerText = iso_code + " - " + getLocalizedString(iso_code);}
			element.setAttribute("name",currencies[j].name);
			element.setAttribute("value",currencies[j].country);
			//if (currencies[j].name == table_elements[to_select].currency) {element.setAttribute("selected",true);}
			opt_element.appendChild(element);
		}
		
		select.appendChild(opt_element);
	} else if (!sections && by_country) { // unica lista per le active, escludo le legacy (che fondo insieme)	
		var currencies = all_active_unitArray_associative;
		var numCur = currencies.length;
		
		var opt_element = document.createElement("optgroup");
		opt_element.setAttribute("label",getLocalizedString("all_currencies"));
		
		for (var j = 0; j < numCur; j++)
		{
			var element = document.createElement("option");
			//element.innerText = getLocalizedString(currencies[j].name);
			element.innerText = currencies[j].country_name + " - " + currencies[j].localized + " (" + currencies[j].currency + ")";
			element.setAttribute("name",currencies[j].currency);
			element.setAttribute("value",currencies[j].country);
			//if ((currencies[j].currency == table_elements[to_select].currency) && (currencies[j].country == table_elements[to_select].country)) {element.setAttribute("selected",true);}
			opt_element.appendChild(element);
		}
		
		select.appendChild(opt_element);
		
		
		var currencies = allLegacyArray_associative;
		var numCur = currencies.length;
		
		var opt_element = document.createElement("optgroup");
		opt_element.setAttribute("label",getLocalizedString("all_legacy"));
		
		for (var j = 0; j < numCur; j++)
		{
			var element = document.createElement("option");
			//element.innerText = getLocalizedString(currencies[j].name);
			element.innerText = currencies[j].country_name + " - " + currencies[j].localized + " (" + currencies[j].currency + ")";
			element.setAttribute("name",currencies[j].currency);
			element.setAttribute("value",currencies[j].country);
			//if ((currencies[j].currency == table_elements[to_select].currency) && (currencies[j].country == table_elements[to_select].country)) {element.setAttribute("selected",true);}
			opt_element.appendChild(element);
		}
		
		select.appendChild(opt_element);
		
		
		var currencies = ecb_euroconversion_associative;
		var numCur = currencies.length;
		
		var opt_element = document.createElement("optgroup");
		opt_element.setAttribute("label",getLocalizedString("ecb_euroconversion"));
		
		for (var j = 0; j < numCur; j++)
		{// non ho country_name nè localized, ecco perchè undefined!!!
			var element = document.createElement("option");
			//element.innerText = getLocalizedString(currencies[j].name);
			iso_code = currencies[j].name;
			iso_code = iso_code.substring(4);
			
			var index = currencies[j].name;
			
			//RoundPlugin.logMessage(currencies[index].country_name + ";" + currencies[index].localized + ";" + iso_code);
			//RoundPlugin.logMessage(currencies[j]);
			//RoundPlugin.logMessage(currencies[j].country_name + ";" + currencies[j].localized + ";" + iso_code);
			
			element.innerText = currencies[j].country_name + " - " + currencies[j].localized + " (" + iso_code + ")";
			element.setAttribute("name",currencies[j].name);
			element.setAttribute("value",currencies[j].country);
			//if (currencies[j].name == table_elements[to_select].currency) {element.setAttribute("selected",true);}
			opt_element.appendChild(element);
		}
		
		select.appendChild(opt_element);
		
		
		// virtual currencies
		var currencies = virtual_currencies_associative;
		var numCur = currencies.length;
		
		var opt_element = document.createElement("optgroup");
		opt_element.setAttribute("label",getLocalizedString("virtual_currencies"));
		
		for (var j = 0; j < numCur; j++)
		{
			var element = document.createElement("option");
			//element.innerText = getLocalizedString(currencies[j].name);
			element.innerText = currencies[j].country_name + " - " + currencies[j].localized + " (" + currencies[j].currency + ")";
			element.setAttribute("name",currencies[j].currency);
			element.setAttribute("value",currencies[j].country);
			//if ((currencies[j].currency == table_elements[to_select].currency) && (currencies[j].country == table_elements[to_select].country)) {element.setAttribute("selected",true);}
			opt_element.appendChild(element);
		}
		
		select.appendChild(opt_element);
		
		
		// commodities
		var currencies = commodities_associative;
		var numCur = currencies.length;
		
		var opt_element = document.createElement("optgroup");
		opt_element.setAttribute("label",getLocalizedString("commodities_currencies"));
		
		for (var j = 0; j < numCur; j++)
		{
			var element = document.createElement("option");
			//element.innerText = getLocalizedString(currencies[j].name);
			element.innerText = currencies[j].country_name + " - " + currencies[j].localized + " (" + currencies[j].currency + ")";
			element.setAttribute("name",currencies[j].currency);
			element.setAttribute("value",currencies[j].country);
			//if ((currencies[j].currency == table_elements[to_select].currency) && (currencies[j].country == table_elements[to_select].country)) {element.setAttribute("selected",true);}
			opt_element.appendChild(element);
		}
		
		select.appendChild(opt_element);
	} else if (sections && by_country) {
		var currencies = currency_used_associative;
		var numCur = currencies.length;
		
		var opt_element = document.createElement("optgroup");
		opt_element.setAttribute("label",getLocalizedString("all_currencies"));
		
		for (var j = 0; j < numCur; j++)
		{
			var element = document.createElement("option");
			//element.innerText = getLocalizedString(currencies[j].name);
			element.innerText = currencies[j].country_name + " - " + currencies[j].localized + " (" + currencies[j].currency + ")";
			element.setAttribute("name",currencies[j].currency);
			element.setAttribute("value",currencies[j].country);
			//if ((currencies[j].currency == table_elements[to_select].currency) && (currencies[j].country == table_elements[to_select].country)) {element.setAttribute("selected",true);}
			opt_element.appendChild(element);
		}
		
		select.appendChild(opt_element);
		
		
		var currencies = ecb_euroconversion_associative;
		var numCur = currencies.length;
		
		var opt_element = document.createElement("optgroup");
		opt_element.setAttribute("label",getLocalizedString("ecb_euroconversion"));
		
		for (var j = 0; j < numCur; j++)
		{
			var element = document.createElement("option");
			//element.innerText = getLocalizedString(currencies[j].name);
			iso_code = currencies[j].name;
			iso_code = iso_code.substring(4);
			
			element.innerText = currencies[j].country_name + " - " + currencies[j].localized + " (" + iso_code + ")";
			element.setAttribute("name",currencies[j].name);
			element.setAttribute("value",currencies[j].country);
			//if (currencies[j].name == table_elements[to_select].currency) {element.setAttribute("selected",true);}
			opt_element.appendChild(element);
		}
		
		select.appendChild(opt_element);
		
		
		var currencies = unrecognized_currencies_associative;
		var numCur = currencies.length;
		
		var opt_element = document.createElement("optgroup");
		opt_element.setAttribute("label",getLocalizedString("unrecognized_currencies"));
		
		for (var j = 0; j < numCur; j++)
		{
			var element = document.createElement("option");
			//element.innerText = getLocalizedString(currencies[j].name);
			element.innerText = currencies[j].country_name + " - " + currencies[j].localized + " (" + currencies[j].currency + ")";
			element.setAttribute("name",currencies[j].currency);
			element.setAttribute("value",currencies[j].country);
			//if ((currencies[j].currency == table_elements[to_select].currency) && (currencies[j].country == table_elements[to_select].country)) {element.setAttribute("selected",true);}
			opt_element.appendChild(element);
		}
		
		select.appendChild(opt_element);
		
		// old european currencies
		var currencies = european_legacy_associative;
		var numCur = currencies.length;
		
		var opt_element = document.createElement("optgroup");
		opt_element.setAttribute("label",getLocalizedString("euro_legacy"));
		
		for (var j = 0; j < numCur; j++)
		{
			var element = document.createElement("option");
			//element.innerText = getLocalizedString(currencies[j].name);
			element.innerText = currencies[j].country_name + " - " + currencies[j].localized + " (" + currencies[j].currency + ")";
			element.setAttribute("name",currencies[j].currency);
			element.setAttribute("value",currencies[j].country);
			//if ((currencies[j].currency == table_elements[to_select].currency) && (currencies[j].country == table_elements[to_select].country)) {element.setAttribute("selected",true);}
			opt_element.appendChild(element);
		}
		
		select.appendChild(opt_element);
		
		// old currencies
		var currencies = old_currencies_associative;
		var numCur = currencies.length;
		
		var opt_element = document.createElement("optgroup");
		opt_element.setAttribute("label",getLocalizedString("old_currencies"));
		
		for (var j = 0; j < numCur; j++)
		{
			var element = document.createElement("option");
			//element.innerText = getLocalizedString(currencies[j].name);
			element.innerText = currencies[j].country_name + " - " + currencies[j].localized + " (" + currencies[j].currency + ")";
			element.setAttribute("name",currencies[j].currency);
			element.setAttribute("value",currencies[j].country);
			//if ((currencies[j].currency == table_elements[to_select].currency) && (currencies[j].country == table_elements[to_select].country)) {element.setAttribute("selected",true);}
			opt_element.appendChild(element);
		}
		
		select.appendChild(opt_element);
		
		// virtual currencies
		var currencies = virtual_currencies_associative;
		var numCur = currencies.length;
		
		var opt_element = document.createElement("optgroup");
		opt_element.setAttribute("label",getLocalizedString("virtual_currencies"));
		
		for (var j = 0; j < numCur; j++)
		{
			var element = document.createElement("option");
			//element.innerText = getLocalizedString(currencies[j].name);
			element.innerText = currencies[j].country_name + " - " + currencies[j].localized + " (" + currencies[j].currency + ")";
			element.setAttribute("name",currencies[j].currency);
			element.setAttribute("value",currencies[j].country);
			//if ((currencies[j].currency == table_elements[to_select].currency) && (currencies[j].country == table_elements[to_select].country)) {element.setAttribute("selected",true);}
			opt_element.appendChild(element);
		}
		
		select.appendChild(opt_element);
		
		
		// commodities
		var currencies = commodities_associative;
		var numCur = currencies.length;
		
		var opt_element = document.createElement("optgroup");
		opt_element.setAttribute("label",getLocalizedString("commodities_currencies"));
		
		for (var j = 0; j < numCur; j++)
		{
			var element = document.createElement("option");
			//element.innerText = getLocalizedString(currencies[j].name);
			element.innerText = currencies[j].country_name + " - " + currencies[j].localized + " (" + currencies[j].currency + ")";
			element.setAttribute("name",currencies[j].currency);
			element.setAttribute("value",currencies[j].country);
			//if ((currencies[j].currency == table_elements[to_select].currency) && (currencies[j].country == table_elements[to_select].country)) {element.setAttribute("selected",true);}
			opt_element.appendChild(element);
		}
		
		select.appendChild(opt_element);
	}
}


//‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ
//	
// ‚Äö√Ñ¬¢ convertAmount
//
// Converts amounts between fields. If amount is not a number then result is set to the empty string
//
//‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ
function escreturn(evt)
{
	evt = (evt) ? evt : event;
    var charCode = (evt.charCode) ? evt.charCode : ((evt.keyCode) ? evt.keyCode : ((evt.which) ? evt.which : 0));
	
	if ((charCode == 27) && (inputTaxesVisibility)){register_taxes("undo");return false;} //esc key
	if ((charCode == 13 || charCode == 3) && (inputTaxesVisibility)) {register_taxes("ok");return false} // enter key
}

var mode = "normal"; // default
var expression_text = "";



function build_expr(input_expr)
{
	if (input_expr.length == 0) return;
	
	if ((input_expr.charAt(0) == "+") || (input_expr.charAt(0) == "-") || (input_expr.charAt(0) == "*") || (input_expr.charAt(0) == "/")) {
		if (input_expr.length > 1) expression_text += input_expr.charAt(0);
		build_expr(input_expr.substring(1));
		return;
	}
	
	var token_end = input_expr.search(/[+]|[-]|[*]|[/]/);
	var token;
	if (token_end != -1) {token = input_expr.substring(0,token_end);} else {token = input_expr.substring(0);}
	
	expression_text += RoundPlugin.getNumericValue(token);
	if (token_end == -1) return;
	build_expr(input_expr.substring(token_end));
	return;
}

function convert_values(the_element,evt)
{
	if (modifing_an_alement > 0){setTimeout("this.function();", 1000); return;}
	
    try{
        evt = (evt) ? evt : event;
        var charCode = (evt.charCode) ? evt.charCode : ((evt.keyCode) ? evt.keyCode : ((evt.which) ? evt.which : 0));
        
        if (((charCode == 9) && !(event.shiftKey)) || ((charCode == 25) || ((charCode == 9) && (event.shiftKey)))) return;
        if (((charCode >= 37) && (charCode <= 40)) || ((charCode >= 63232) && (charCode <= 63235))) return;
        
        if (evt.metaKey) { // command key down
            return;
        }
    } catch (ex){}
	
	var input_value = document.getElementById("value_field_" + the_element).value;
    
    //RoundPlugin.("entered value: " + input_value);
	
	var amount;
	var the_value = input_value;
	// se the_value è una espressione la calcolo prima della conversione: vedo se ci sono segni
	if (input_value.search(/[A-Z]|[=]/) > -1) { 
		// inverse mode, semplicemente return?
		return;
	} else if (input_value.search(/[+]|[-]|[*]|[/]/) > -1) {
		expression_text = "";
		if (input_value.charAt(0) == "*") {mode = "inverse"; build_expr(input_value.substring(1));} else {mode = "normal"; build_expr(input_value);}
		try{amount = eval(expression_text);} catch (ex) {amount = "";}
	} else {
		mode = "normal";
		amount = RoundPlugin.getNumericValue(input_value);
	}
	
	var fromIndex = document.getElementById("select_field_" + the_element).options[document.getElementById("select_field_" + the_element).selectedIndex].getAttribute("name");
    
    var floatAmount = parseFloat(amount);
	
	if (mode == "inverse"){ // inverse conversion! tax rates are disabled, text fields are fuchsia
		var convertedValue = "";
		
		if (isNaN(floatAmount)) {amount = "1"; floatAmount = parseFloat(amount)};
		
		var unitArray = euroconversion;
    	// fondo gli array
    	var all_unitArray = unitArray.concat(legacy_euroconversion,extraeu_main_euroconversion,extraeu_euroconversion,palple_extraeu,ecb_euroconversion,virtual_currencies,commodities_currencies,unrecognized_currencies,old_currencies);
		
		var toBase = parseFloat(getValue(all_unitArray,fromIndex));
		
		for (var i=0; i<table_elements.length; i++){
    		document.getElementById("value_field_" + i).style.color = "fuchsia";
			
			try {var toIndex = document.getElementById("select_field_" + i).options[document.getElementById("select_field_" + i).selectedIndex].getAttribute("name");} catch (exept) {continue;} // dovrei far ricominciare il giro
			
			if (i == the_element){
				//convertedValue = the_value;
			} else {
				// the conversion should be from amount 1 of destination field currency to the_value currency
				
				var fromBase = parseFloat(getValue(all_unitArray,toIndex));
				
				var baseValue = floatAmount/fromBase; // prima lo normalizzo
    			convertedValue = baseValue * toBase; // poi lo converto nella valuta originaria
				
    			convertedValue = convertedValue.toString();
    			
    			convertedValue = roundRes(convertedValue);
    		
    			if (typeof convertedValue == "undefined") convertedValue="";
				
				//var inverseConvertedValue = roundRes(amount.toString()) + toIndex + "=" + convertedValue + fromIndex;
				var inverseConvertedValue = convertedValue + fromIndex + "=" + roundRes(amount.toString()) + toIndex;
				
				document.getElementById("value_field_" + i).value = inverseConvertedValue;
			}
		}
	} else if (isNaN(floatAmount) == false) { // plain conversion
		var convertedValue = "";
		
		var unitArray = euroconversion;
    	// fondo gli array
    	var all_unitArray = unitArray.concat(legacy_euroconversion,extraeu_main_euroconversion,extraeu_euroconversion,palple_extraeu,ecb_euroconversion,virtual_currencies,commodities_currencies,unrecognized_currencies,old_currencies);
		
		var toBase = parseFloat(getValue(all_unitArray,fromIndex));
		
		for (var i=0; i<table_elements.length; i++){
    		try {var toIndex = document.getElementById("select_field_" + i).options[document.getElementById("select_field_" + i).selectedIndex].getAttribute("name");} catch (exept) {continue;} // dovrei far ricominciare il giro
            
			if (i == the_element){
				//convertedValue = the_value;
				document.getElementById("value_field_" + i).style.color = "black"; // metto sempre il black di base, potrebbe essere fuchsia
				
				if (conversion_taxes != 0){
					// evidenzia l'elemento
					document.getElementById("value_field_" + i).style.color = "red";
				}
			} else {
				// innanzi tutto toglie l'evidenziazione all'elemento
				document.getElementById("value_field_" + i).style.color = "black";
				
				var fromBase = parseFloat(getValue(all_unitArray,toIndex));
				
				var baseValue = floatAmount/toBase; // prima lo converto in euro
    			convertedValue = baseValue * fromBase; // poi lo converto nella valuta di destinazione
    			
    			//if (convertedValue < 0) convertedValue = convertedValue*(-1);
				
				convertedValue += convertedValue*(conversion_taxes/100); // computo le tasse
				
    			convertedValue = convertedValue.toString();
    			//RoundPlugin.logMessage("converted: " + convertedValue);
    			
                //RoundPlugin.logMessage("converted value of field #" + i + " and the value is: " + convertedValue);
                
    			convertedValue = roundRes(convertedValue);
                
                //RoundPlugin.logMessage("converted value of field #" + i + " and the rounded value is: " + convertedValue);
                
    			if (typeof convertedValue == "undefined") convertedValue="";
				
				document.getElementById("value_field_" + i).value = convertedValue;
			}
		}
	} else {
		for (i=0; i<table_elements.length; i++){
			//if ((i == the_element) && ((input_value == "+") || (input_value == "-"))) {/* do not modify, start with + or - */} else {document.getElementById("value_field_" + i).value = "";}
			if (i != the_element) document.getElementById("value_field_" + i).value = "";
			// toglie l'evidenziazione all'elemento
			document.getElementById("value_field_" + i).style.color = "black";
		}
	}
	
	last_selected_value.position = the_element;
	last_selected_value.value = document.getElementById("value_field_" + the_element).value;

	//saveLastSelected();
	save_options();
}

function convert_value(fromCurrency, fromValue, toElement)
{	
	check_newest_currencies_data_available();
	
	if (modifing_an_alement > 0){setTimeout("this.function();", 1000); return;}
	
	fromIndex = fromCurrency;
	
	if (fromValue.search(/[=]/) > -1){ // inverse mode
		mode = "inverse";
		amount = "1";
	} else if (fromValue.search(/[+]|[-]|[*]|[/]/) > -1) {
		expression_text = "";
		if (fromValue.charAt(0) == "*") {mode = "inverse"; build_expr(fromValue.substring(1));} else {mode = "normal"; build_expr(fromValue);}
		try{amount = eval(expression_text);} catch (ex) {amount = "";}
	} else {
		amount = RoundPlugin.getNumericValue(fromValue);
	}
    
    var floatAmount = parseFloat(amount);
    
	if (mode == "inverse") { // inverse conversion mode
		// devo cercare la valuta con * e settarla come fromIndex
		for (var i=0; i<table_elements.length; i++){
    		if (document.getElementById("value_field_" + i).value.charAt(0) == "*") break;
		}
		
		var input_value = document.getElementById("value_field_" + i).value;
		expression_text = "";
		if (input_value.charAt(0) == "*") {build_expr(input_value.substring(1));}
		try{amount = eval(expression_text);} catch (ex) {}
		
		var floatAmount = parseFloat(amount);
		if (isNaN(floatAmount)) {amount = "1"; floatAmount = parseFloat(amount)};
		
		var fromIndex = document.getElementById("select_field_" + i).options[document.getElementById("select_field_" + i).selectedIndex].getAttribute("name");
		
		var convertedValue = "";
		
		var unitArray = euroconversion;
    	// fondo gli array
    	var all_unitArray = unitArray.concat(legacy_euroconversion,extraeu_main_euroconversion,extraeu_euroconversion, palple_extraeu, ecb_euroconversion, virtual_currencies, commodities_currencies, unrecognized_currencies, old_currencies);
		
		var toBase = parseFloat(getValue(all_unitArray,fromIndex));
		
		var toIndex = document.getElementById("select_field_" + toElement).options[document.getElementById("select_field_" + toElement).selectedIndex].getAttribute("name");
		
		var fromBase = parseFloat(getValue(all_unitArray,toIndex));
		
		var baseValue = floatAmount/fromBase; // prima lo normalizzo
    	convertedValue = baseValue * toBase; // poi lo converto nella valuta originaria
		
    	convertedValue = convertedValue.toString();
    	
    	convertedValue = roundRes(convertedValue);
		
    	if (typeof convertedValue == "undefined") convertedValue="";
		
		//var inverseConvertedValue = roundRes(amount.toString()) + toIndex + "=" + convertedValue + fromIndex;
		var inverseConvertedValue = convertedValue + fromIndex + "=" + roundRes(amount.toString()) + toIndex;
		
		document.getElementById("value_field_" + toElement).value = inverseConvertedValue;
		
	} else if (isNaN(floatAmount) == false) { // plain mode
		var convertedValue = "";
		
		var unitArray = euroconversion;
    	// fondo gli array
    	var all_unitArray = unitArray.concat(legacy_euroconversion,extraeu_main_euroconversion,extraeu_euroconversion, palple_extraeu, ecb_euroconversion, virtual_currencies, commodities_currencies, unrecognized_currencies, old_currencies);
		
		var toBase = parseFloat(getValue(all_unitArray,fromIndex));
		
		var toIndex = document.getElementById("select_field_" + toElement).options[document.getElementById("select_field_" + toElement).selectedIndex].getAttribute("name");
				
		if (fromIndex == toIndex){
			convertedValue = floatAmount.toString();
		} else {
			var fromBase = parseFloat(getValue(all_unitArray,toIndex));
			
			var baseValue = floatAmount/toBase; // prima lo converto in euro
			convertedValue = baseValue * fromBase; // poi lo converto nella valuta di destinazione
			
			if (convertedValue < 0) convertedValue = convertedValue*(-1);
			
			convertedValue = convertedValue.toString();
		}
		
		convertedValue = roundRes(convertedValue);
		
		if (typeof convertedValue == "undefined") convertedValue="";

		document.getElementById("value_field_" + toElement).value = convertedValue;
	} else {
		document.getElementById("value_field_" + toElement).value = "";
	}
}

function pegged_values(the_array, the_name)
{
	// ora calcolo i valori nell'array fixed_rates
	return eval(fixed_rates[the_name].value);
}

function getValue (the_array, the_name)
{
	if (!isNotInizialized(fixed_rates[the_name])) return pegged_values(the_array, the_name);
	
    
    if (the_name == "UDI"){
        var mxn_value, udi_value, usd_value;
        
        for (i=0; i<the_array.length; i++){
            if (the_array[i].name == "MXN") {mxn_value = the_array[i].value;} else if (the_array[i].name == "UDI") {udi_value = the_array[i].value;} else if (the_array[i].name == "USD") {usd_value = the_array[i].value;}
        }
        
        return mxn_value/udi_value*usd_value;
    }
    
    /*
    if (the_name == "BTC"){
        var btc_value, usd_value, eur_value;
        
        for (i=0; i<the_array.length; i++){
            if (the_array[i].name == "BTC") {btc_value = the_array[i].value;} else if (the_array[i].name == "EUR") {eur_value = the_array[i].value;} else if (the_array[i].name == "USD") {usd_value = the_array[i].value;}
        }
        
        var btc_usd = btc_value/usd_value;
        var new_btc = 1/btc_usd;
        
        return new_btc*usd_value;
    }*/
    
    /*
    if (the_name == "CLF"){
        var clf_value, clp_value, usd_value;
        
        for (i=0; i<the_array.length; i++){
            if (the_array[i].name == "CLP") {clp_value = the_array[i].value;} else if (the_array[i].name == "CLF") {clf_value = the_array[i].value;} else if (the_array[i].name == "USD") {usd_value = the_array[i].value;}
        }
        
        return clp_value*clf_value/usd_value;
    }*/
    
	for (i=0; i<the_array.length; i++){
		if (the_array[i].name == the_name) {return the_array[i].value;}
	}
}

function roundRes(value)
{
	//debug(value);
	// uso il plugin creato in Cocoa
	if(RoundPlugin){
		value=RoundPlugin.getFormattedValue(value,"true",conversion_precision);
	}
	
	if (conversion_precision == 0){
		value = value.split(decimal_separator).join("");
	}
	
	return value;
}

function numeralsOnly(allTheData_element,evt,ontaxes)
{
    evt = (evt) ? evt : event;
    var charCode = (evt.charCode) ? evt.charCode : ((evt.keyCode) ? evt.keyCode : ((evt.which) ? evt.which : 0));
	
	if (evt.metaKey) {// command key down
    	return true;
	}
    
    //RoundPlugin.logMessage("charcode: " + charCode);
	if (charCode == 45 || charCode == 43 || charCode == 42 || charCode == 47) { // +-*/ keys
		return true;
    } else if (charCode == 63) { // '?' key
		return false;
	} else if (((charCode >= 37) && (charCode <= 40)) || ((charCode >= 63232) && (charCode <= 63235))) { // arrow keys
		return true;
    } else if ((charCode == 9) && !(event.shiftKey)) { // tab key
    	if (ontaxes) return false;
		
		var new_element;
    	if (allTheData_element == table_elements.length - 1) {new_element = 0;} else {new_element = allTheData_element + 1;}
    	document.getElementById("value_field_" + new_element).select();
    	return false;
    } else if ((charCode == 25) || ((charCode == 9) && (event.shiftKey))) { // shift-tab key
    	if (ontaxes) return false;
		
		var new_element;
    	if (allTheData_element == 0) {new_element = table_elements.length - 1;} else {new_element = allTheData_element - 1;}
    	document.getElementById("value_field_" + new_element).select();
    	return false;
    } else if (!((charCode < 32 ) || (charCode > 47 && charCode < 58) || (charCode == decimal_separator.charCodeAt()) || (charCode == thousand_separator.charCodeAt()) || (charCode == 63272) || ((charCode >= 63232) && (charCode <= 63235)))) {
        return false;
    } else if (charCode == 13 || charCode == 3) { // enter keys
		return false;
    }
    
    return true;
}

//‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ
//	
// ‚Äö√Ñ¬¢ Functions to handle preferences
//
//‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ

function switch_ad_check()
{
	if (hide_ad_check.checked){
		hide_ad_check.checked = false;
	} else {
		hide_ad_check.checked = true;
	}
}

function check_sections_radio(which)
{
	if (which == 1){
		sections_radio_yes.checked = true;
	} else {
		sections_radio_no.checked = true;
	}
}

function check_orderby_radio(which)
{
	if (which == 1){
		order_by_radio_names.checked = true;
	} else if (which == 2){
		order_by_radio_codes.checked = true;
	} else {
		order_by_radio_states.checked = true;
	}
}

function check_labels_radio(which)
{
	if (which == 1){
		show_radio_names.checked = true;
	} else {
		show_radio_codes.checked = true;
	}
}

function createkey(key)
{
	return widget.identifier + "-" + key;
}

function saveUnitsToPreferences()
{
	if (window.widget)
	{
		var	unitKey = "UnitFrom";
		widget.setPreferenceForKey (defaultFromIndex.toString(), createkey(unitKey));
		
		unitKey = "UnitTo";
		widget.setPreferenceForKey (defaultToIndex.toString(), createkey(unitKey));
	}
}


function setUnitsFromPreferences()
{
	
	// check preferences and set values if available
	if (window.widget) 
	{
		var unitKey = "UnitFrom";
		var unitValue = widget.preferenceForKey (createkey(unitKey));
		
		if( unitValue != null )
		{
			defaultFromIndex = unitValue;
			unitKey = "UnitTo";
			unitValue = widget.preferenceForKey (createkey(unitKey));
			
			if (unitValue != null )
				defaultToIndex = unitValue;
		}
	}
}

function saveConversionToPreferences(){
	if (window.widget) 
	{
		var unitKey = "ValueFrom";
		
		//RoundPlugin.logMessage(document.getElementById("valuta1").value);
		widget.setPreferenceForKey (document.getElementById("valuta1").value, createkey(unitKey));
	}
}

function saveTableElements()
{
	pref = createTableElementsJSString();
	widget.setPreferenceForKey (pref, createkey("saved_table_elements_data"));
	
	widget.setPreferenceForKey (pref, "saved_table_elements_data");
	
	//RoundPlugin.logMessage(pref);
}

function createTableElementsJSString()
{
	var str = "["
	var c = table_elements.length;
	
	for (var i = 0; i < c; ++i)
	{
		var data = table_elements[i];
		if (i != 0)
			str += ",";
		// make sure the name does not have any single quotes in it
		str += "{currency:'" + data.currency + "',country:'" + data.country + "'}";
	}
	
	str += "];";
	
	return str;
}

function read_table_elements_from_prefs()
{
	if (window.widget)
	{
		try {
			var global_data = widget.preferenceForKey ("saved_table_elements_data");
			
			if (isNotInizialized(global_data)){
				widget.setPreferenceForKey (getLocalizedString("default_currencies"),"saved_table_elements_data");
				var global_data = widget.preferenceForKey ("saved_table_elements_data");
			}
		}
		catch(excpt) {
			widget.setPreferenceForKey (getLocalizedString("default_currencies"),"saved_table_elements_data");
			var global_data = widget.preferenceForKey ("saved_table_elements_data");
		}
		
		try {
			var data = widget.preferenceForKey (createkey("saved_table_elements_data"));
		}
		catch(ex) {
			widget.setPreferenceForKey (global_data,createkey("saved_table_elements_data"));
			var data = widget.preferenceForKey (createkey("saved_table_elements_data"));
		}
	
		if (data == undefined){
			data = global_data;
		}
		
		data = eval(data);
		
		if (data.length == 0) {
			data = global_data;
			
			data = eval(data);
		}
		
		var newAllData = new Array;
		var c = data.length;

		if (c==0){
			data = getLocalizedString("default_currencies");
			data = eval(data);
			c = data.length;
		}
		
		
		for (var i = 0; i < c; ++i)
		{
			// devo mettere un sistema che legga da vecchie tabelle e le converta in nuove!!!
			
			var dataLine = data[i];
			
			try {
				dataLine_country = dataLine.country;
				dataLine_currency = dataLine.currency;
				
				//RoundPlugin.logMessage("in try, country_before: " + dataLine_country + "currency: " + dataLine_currency);
				//newAllData[newAllData.length] = {currency: dataLine_currency, country: getCountryCodeFromIso(dataLine_currency)};
				//RoundPlugin.logMessage("in try, country: " + getCountryCodeFromIso(dataLine_currency));
				
				if (isNotInizialized(dataLine_currency)){
					if (isNotInizialized(dataLine)) {dataLine = 'EUR'}; // a mali estremi...
					if ((isNotInizialized(dataLine_currency)) && (!isNotInizialized(dataLine_country))) {dataLine = 'EUR'};
					newAllData[newAllData.length] = {currency:dataLine, country:getCountryCodeFromIso(dataLine)};
				} else if (isNotInizialized(dataLine_country)){
					newAllData[newAllData.length] = {currency: dataLine_currency, country: getCountryCodeFromIso(dataLine_currency)};
				} else {
					newAllData[newAllData.length] = {currency: dataLine_currency, country: dataLine_country};
				}
				//RoundPlugin.logMessage("not exception: " + newAllData[newAllData.length-1].currency);
			}
			catch(ex) {
				//RoundPlugin.logMessage("in catch: " + i + "data: " + dataLine);
				//current_length = newAllData.length;
				//newAllData[current_length].currency = dataLine;
				//newAllData[current_length].country = '';
				newAllData[newAllData.length] = {currency:dataLine, country:getCountryCodeFromIso(dataLine)};
				//RoundPlugin.logMessage("in catch: " + i + "country: " + getCountryCodeFromIso(dataLine));
				//RoundPlugin.logMessage("exception: " + newAllData[newAllData.length-1].currency);
			}
		}
        
        
		for (var i = 0; i < newAllData.length; ++i)
		{
            if (newAllData[i].currency == "ecb_SKK"){
                newAllData[i].currency = "SKK";
            }
            
            if (newAllData[i].currency == "ecb_SIT"){
                newAllData[i].currency = "SIT";
            }
            
            if (newAllData[i].currency == "ecb_MTL"){
                newAllData[i].currency = "MTL";
            }
            
            if (newAllData[i].currency == "ecb_ISK"){
                newAllData[i].currency = "ISK";
            }
            
            if (newAllData[i].currency == "ecb_CYP"){
                newAllData[i].currency = "CYP";
            }
            
            
            
            if ((newAllData[i].country == "SOS") || (newAllData[i].country == "ABK")){
                newAllData[i].country = "GEL";
                newAllData[i].currency = "GEL";
            }
            
            if (newAllData[i].country == "CAD"){
                newAllData[i].country = "CAN";
            }
        }
        
        table_elements = newAllData;
	}
}

function saveLastSelected()
{
	var last_value;
	var fromValue = last_selected_value.value;
	
	if (fromValue.search(/[+]|[-]|[*]|[/]/) > -1) {
		expression_text = "";
		var computed_value;
		if (fromValue.charAt(0) == "*") {build_expr(fromValue.substring(1));} else {build_expr(fromValue);}
		try {
			computed_value = eval(expression_text);
			if (isNotInizialized(computed_value)) {computed_value = "";} else {computed_value = computed_value.toString();}
		} catch (ex) {}
		
		if (fromValue.charAt(0) == "*") {last_value = "*" + computed_value;} else {last_value = computed_value;}
	} else if (isNotInizialized(fromValue)) {
		last_value = "1000";
	} else {
		last_value = RoundPlugin.getNumericValue(fromValue);
	}
	
	if (isNotInizialized(last_value)) {last_value = "1000";}
	
	try{
		widget.setPreferenceForKey (last_value.toString(), createkey("saved_last_selected_value"));
		widget.setPreferenceForKey (last_selected_value.position, createkey("saved_last_selected_position"));
		
		widget.setPreferenceForKey (last_value.toString(), "saved_last_selected_value");
		widget.setPreferenceForKey (last_selected_value.position, "saved_last_selected_position");
	} catch (ex) {}
}

function read_last_selected_from_prefs()
{	
	if (window.widget)
	{
		var last_value = widget.preferenceForKey (createkey("saved_last_selected_value"));
		last_selected_value.position = widget.preferenceForKey (createkey("saved_last_selected_position"));		
		
		if ((isNotInizialized(last_value)) || (isNotInizialized(last_selected_value.position))){
			last_value = widget.preferenceForKey ("saved_last_selected_value");
			last_selected_value.position = widget.preferenceForKey ("saved_last_selected_position");
			
			if ((isNotInizialized(last_value)) || (isNotInizialized(last_selected_value.position))){
				last_selected_value = {position:'0',value:'1000'};
                last_value = '1000';
			}
			
			if (last_selected_value.position < 0){
				last_selected_value = {position:'0',value:'1000'};
                last_value = '1000';
			}
			
			saveLastSelected(); // ora sono sicuro di avere in mano buoni valori
		}
		
		last_selected_value.position = parseInt(last_selected_value.position);
		
		if (last_selected_value.position < 0){
			last_selected_value = {position:'0',value:'1000'};
			saveLastSelected(); // ora sono sicuro di avere in mano buoni valori
		}
		
		if (last_value.charAt(0) != "*") {last_selected_value.value = RoundPlugin.getFormattedValue(last_value,"true",conversion_precision);} else {last_selected_value.value = "*" + RoundPlugin.getFormattedValue(last_value.substring(1),"true",conversion_precision);}
	}
}

function change_precision(){
	conversion_precision = precision_popup.options[precision_popup.selectedIndex].value;
	widget.setPreferenceForKey (conversion_precision, createkey("precision"));
	widget.setPreferenceForKey (conversion_precision, "precision");
	convert_values(last_selected_value.position);
}

function change_taxes(){
	input_taxes_dialog.value = RoundPlugin.getFormattedValue(conversion_taxes.toString(),"false",6);
	
	if (taxes_popup.options[taxes_popup.selectedIndex].value == "other"){
		insert_taxes.style.display = "block";
		
		var itemToFadeIn = document.getElementById("insert_taxes");
		var fadeHandler = function(a, c, s, f){ itemToFadeIn.style.opacity = c; };
		var the_animator = new AppleAnimator(500, 13, 0.0, 0.8, fadeHandler);
		
		the_animator.oncomplete = function(){inputTaxesVisibility = true;};
		the_animator.start();
	} else {
		conversion_taxes = taxes_popup.options[taxes_popup.selectedIndex].value;
	}
}

function change_skin(){
	
}

// il salvataggio lo faccio a parte

function register_taxes(which)
{
	inputTaxesVisibility = false;
	
	if (which=="undo"){
		// non fare nulla
	} else {
		// ottieni il valore dal campo (ovviamente con parsing valori localizzati)
		// salva il valore
		try {the_entered_taxes = RoundPlugin.getNumericValue(input_taxes_dialog.value);} catch (ex){the_entered_taxes = conversion_taxes;}
		conversion_taxes = the_entered_taxes;
	}
	
	// ricostruisci il popup
	build_taxes_popup();
	
	var itemToFadeOut = document.getElementById("insert_taxes");	// replace with name of element to fade
	
	// Fading code
	var fadeHandler = function(a, c, s, f){ itemToFadeOut.style.opacity = c; };
	var the_animator = new AppleAnimator(500, 13, 0.8, 0.0, fadeHandler);
	
	the_animator.oncomplete = function(){document.getElementById("insert_taxes").style.display = "none";};
	
	the_animator.start();
}

function build_taxes_popup()
{
	taxes_popup_data = [{data: 0, name: getLocalizedString("taxes_popup_data_none")},{data: 1, name: "1"},{data: 2, name: "2"},{data: 3, name: "3"},{data: 4, name: "4"},{data: 5, name: "5"},{data: 6, name: "6"},{data: 7, name: "7"},{data: 8, name: "8"},{data: 9, name: "9"},{data: 10, name: "10"}];
	// verifico se conversion_taxes è già nella lista, altrimenti lo inserisco ordinatamente
	if (!isInArray(taxes_popup_data,conversion_taxes,"data")){
		taxes_popup_data[taxes_popup_data.length] = {data: conversion_taxes, name: conversion_taxes.toString()}; // in realtà devo localizzare il valore
	}
	// ora ordino l'array per il campo data
	taxes_popup_data.sort(compareData);
	
	// ora aggiungo la voce other e costruisco il popup
	taxes_popup_data[taxes_popup_data.length] = {data: 'other', name: getLocalizedString("taxes_popup_other")};
	
	the_popup = document.getElementById("taxes_popup");
	
	removeAllChildren(the_popup);
	for (var j = 0; j < taxes_popup_data.length; j++)
	{
		var element = document.createElement("option");
		element.innerText = taxes_popup_data[j].name;
		element.setAttribute("value",taxes_popup_data[j].data);
		the_popup.appendChild(element);
		
		// devo selezionare il valore giusto
		if (taxes_popup_data[j].data == conversion_taxes) {the_popup.options[j].selected = true;}
	}
}

function build_skin_popup()
{
	// devo mettere una lista delle skin disponibili (dagli elementi link in html)
	var i, a;
	for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
		if((a.getAttribute("rel").indexOf("style") != -1) && (a.getAttribute("id") != "common")) {
			skins_popup_data[skins_popup_data.length] = {data: a.getAttribute("id"), name: getLocalizedString(a.getAttribute("id"))};
		}
	}
	
	// ordino la lista per nome
	skins_popup_data.sort(compareCodes); // compareCodes sort by the name attribute
	
	// costruisco il popup e seleziono il valore giusto
	var selectedAnItem = false;
	for (var j = 0; j < skins_popup_data.length; j++) {
		if (skins_popup_data[j].data == skin_prefs) {selectedAnItem = true; break;}
	}
	
	if (selectedAnItem == false) { // la skin salvata non è stata trovata
		skin_prefs = "Default";
	}
	
	the_popup = document.getElementById("skin_popup");
	
	removeAllChildren(the_popup);
	for (var j = 0; j < skins_popup_data.length; j++) {
		var element = document.createElement("option");
		element.innerText = skins_popup_data[j].name;
		element.setAttribute("value",skins_popup_data[j].data);
		the_popup.appendChild(element);
		
		// devo selezionare la skin delle preferenze (se disponibile, altrimenti setta una skin diversa)
		if (skins_popup_data[j].data == skin_prefs) {the_popup.options[j].selected = true;}
	}
}

function getConversionFromPreferences(){
	if (window.widget) 
	{
		var unitKey = "ValueFrom";
		var unitValue = widget.preferenceForKey (createkey(unitKey));
		
		if (unitValue == undefined) {unitValue = "1";}
		document.getElementById("valuta1").value = unitValue;
	}
}

function getLocalizedString (key)
{
	try {
		var ret = localizedStrings[key];
		if (ret == undefined)
			ret = key;
		return ret;
	} catch (ex) {}
	
	return key;
}

function debug(msg) {
	if (!debug.box) {
		debug.box = document.createElement("div");
		debug.box.setAttribute("style", "background-color: white; " +
										"font-family: monospace; " +
										"border: solid black 3px; " +
										"position: absolute;top:30px;" +
										"padding: 10px;" +
										"opacity: 0.6;" + "z-index: 100");
		document.body.appendChild(debug.box);
		debug.box.innerHTML = "Debug Output";
	}
	
	var p = document.createElement("p");
	p.appendChild(document.createTextNode(msg));
	debug.box.appendChild(p);
}

//‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ
//	
// ‚Äö√Ñ¬¢ Functions to handle backside & flipper
//
//
//‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ‚Äö√Ñ√Æ

function goToMySite()
{
 	//widget.openURL(getLocalizedString('web_page_url'));
 	widget.openURL("http://www.quaerosoft.com/currencyconverterwidget/index.html");
}

function goToHelp()
{
 	widget.openURL("http://www.quaerosoft.com/currencyconverterwidget/index.html#help");
}

function go_to_store()
{
 	widget.openURL("http://phobos.apple.com/WebObjects/MZStore.woa/wa/viewSoftware?id=290527470&mt=8");
}

function selectDonate ()
{
	widget.openURL(getLocalizedString('web_page_url_donate'));
}

function save_options() // salva tutto i dati globali e locali...
{
	sections = sections_radio_yes.checked;
	widget.setPreferenceForKey(sections.toString(),createkey("sections"));
	widget.setPreferenceForKey(sections.toString(),"sections");
	
	by_name = order_by_radio_names.checked;
	widget.setPreferenceForKey(by_name.toString(),createkey("by_name"));
	widget.setPreferenceForKey(by_name.toString(),"by_name");
	
	by_country = order_by_radio_states.checked;
	widget.setPreferenceForKey(by_country.toString(),createkey("by_country"));
	widget.setPreferenceForKey(by_country.toString(),"by_country");
	
	label_byname = show_radio_names.checked;
	widget.setPreferenceForKey(label_byname.toString(),createkey("label_byname"));
	widget.setPreferenceForKey(label_byname.toString(),"label_byname");
	
	widget.setPreferenceForKey (conversion_taxes, createkey("taxes"));
	widget.setPreferenceForKey (conversion_taxes, "taxes");
    
    show_ad = !hide_ad_check.checked;
	widget.setPreferenceForKey(show_ad.toString(),createkey("showad"));
	widget.setPreferenceForKey(show_ad.toString(),"showad");
	
	// dato che sto salvando le opzioni come globali, salvo anche la tabella attuale e il last_selected_value come globali!
	saveTableElements();
	saveLastSelected();
}

function selectDone ()
{
	save_options();
	
	var new_skin = skin_popup.options[skin_popup.selectedIndex].value;
	widget.setPreferenceForKey (new_skin, createkey("skin_prefs"));
	widget.setPreferenceForKey (new_skin, "skin_prefs");
	skin_prefs = new_skin;
	set_skin();
	var new_size = table_elements.length * element_height + top_height + ads_height + bottom_height + 2;
	actual_size = new_size;
	
	sortArrays();
	
	var front = document.getElementById("front");
	var back = document.getElementById("behind");
	
	resizedWhenFlippedOver = false;
	if (window.widget)
	{
		var vert_size = 263;
		if (263 < actual_size) {
			resizedWhenFlippedOver = true;
			window.resizeTo (357, actual_size);
			vert_size = actual_size;
		}
		
		if (357 < body_width) {
			resizedWhenFlippedOver = true;
			window.resizeTo (body_width, vert_size);
		}
		
		widget.prepareForTransition("ToFront");
	}
	
	initFront();
	
	front.style.display="block";
	back.style.display="none";
	
	if (window.widget)
		setTimeout ('widget.performTransition();', 0);
	
	flipShown = true;
	
	if (there_is_a_new_version) new_version_badge.style.display = 'block';
}

function flipover()
{	
	if (document.getElementById("behind").style.display=='block'){
		finishwithback();
	}else{
		showbackside();
	}
}

function finishwithback()
{
	showfrontside();
}

function enterflip(event)
{
	document.getElementById('fliprollie').style.display = 'block';
}

function exitflip(event)
{
	document.getElementById('fliprollie').style.display = 'none';
}



// The following code is partly copyright Apple Computer Inc.;

function showbackside()
{
	var front = document.getElementById("front");
	var back = document.getElementById("behind");
	
	new_version_badge.style.display = 'none';
	
	resizedWhenFlippedOver = false;
	if (window.widget)
	{	
		var vert_size = actual_size;
		if (actual_size < 263) {
			resizedWhenFlippedOver = true;
			window.resizeTo (body_width, 263);
			vert_size = 263;
		}
		
		if (body_width < 357) {
			resizedWhenFlippedOver = true;
			window.resizeTo (357, vert_size);
		}
		
		widget.prepareForTransition("ToBack");
	}
	
	front.style.display="none";
	back.style.display="block";
	
	document.getElementById('fliprollie').style.display = 'none';
	
	if (window.widget)
		setTimeout ('widget.performTransition();', 0);	
}

function showfrontside()
{
	var front = document.getElementById("front");
	var back = document.getElementById("behind");
	
	resizedWhenFlippedOver = false;
	if (window.widget)
	{
		var vert_size = 263;
		if (263 < actual_size) {
			resizedWhenFlippedOver = true;
			window.resizeTo (357, actual_size);
			vert_size = actual_size;
		}
		
		if (357 < body_width) {
			resizedWhenFlippedOver = true;
			window.resizeTo (body_width, vert_size);
		}
		
		widget.prepareForTransition("ToFront");
	}
	
	front.style.display="block";
	back.style.display="none";
	
	if (window.widget)
		setTimeout("widget.performTransition();", 0);
	
	if (there_is_a_new_version) new_version_badge.style.display = 'block';
}


var animation = {duration:0, starttime:0, to:1.0, now:0.0, from:0.0, element:null, timer:null};
var animation_update = {duration:0, starttime:0, to:1.0, now:0.0, from:0.0, element:null, timer:null};

function limit_3 (a, b, c)
{
    return a < b ? b : (a > c ? c : a);
}

function computeNextFloat (from, to, ease)
{
    return from + (to - from) * ease;
}

function animate()
{
	var T;
	var ease;
	var time = (new Date).getTime();
	
	T = limit_3(time-animation.starttime, 0, animation.duration);
	
	if (T >= animation.duration){
		clearInterval (animation.timer);
		animation.timer = null;
		animation.now = animation.to;
	}
	else{
		ease = 0.5 - (0.5 * Math.cos(Math.PI * T / animation.duration));
		animation.now = computeNextFloat (animation.from, animation.to, ease);
	}
	
	animation.element.style.opacity = animation.now;
}

function animate_update()
{
	var T;
	var ease;
	var time = (new Date).getTime();
	
	T = limit_3(time-animation_update.starttime, 0, animation_update.duration);
	
	if (T >= animation_update.duration){
		clearInterval (animation_update.timer);
		animation_update.timer = null;
		animation_update.now = animation_update.to;
	}
	else{
		ease = 0.5 - (0.5 * Math.cos(Math.PI * T / animation_update.duration));
		animation_update.now = computeNextFloat (animation_update.from, animation_update.to, ease);
	}
	
	animation_update.element.style.opacity = animation_update.now;
}


function mousemove()
{
	if (!flipShown){
		// fade in the flip widget
		if (animation.timer != null){
			clearInterval (animation.timer);
			animation.timer  = null;
		}
		
		var starttime = (new Date).getTime() - 13; // set it back one frame
		
		animation.duration = 500;
		animation.starttime = starttime;
		animation.element = document.getElementById ('flip');
		animation.timer = setInterval ("animate();", 13);
		animation.from = animation.now;
		animation.to = 1.0;
		animate();
		flipShown = true;
	}
	if (!updateShown){
		// fade in the flip widget
		if (animation_update.timer != null){
			clearInterval (animation_update.timer);
			animation_update.timer  = null;
		}
		
		var starttime = (new Date).getTime() - 13; // set it back one frame
		
		animation_update.duration = 500;
		animation_update.starttime = starttime;
		animation_update.element = document.getElementById ('update_data');
		animation_update.timer = setInterval ("animate_update();", 13);
		animation_update.from = animation_update.now;
		animation_update.to = 1.0;
		animate_update();
		updateShown = true;
	}
}

function mouseexit()
{
	if (flipShown)
	{
		// fade in the flip widget
		if (animation.timer != null)
		{
			clearInterval (animation.timer);
			animation.timer  = null;
		}
		
		var starttime = (new Date).getTime() - 13; // set it back one frame
		
		animation.duration = 500;
		animation.starttime = starttime;
		animation.element = document.getElementById ('flip');
		animation.timer = setInterval ("animate();", 13);
		animation.from = animation.now;
		animation.to = 0.0;
		animate();
		flipShown = false;
	}
	if (updateShown)
	{
		// fade in the flip widget
		if (animation_update.timer != null)
		{
			clearInterval (animation_update.timer);
			animation_update.timer  = null;
		}
		
		var starttime = (new Date).getTime() - 13; // set it back one frame
		
		animation_update.duration = 500;
		animation_update.starttime = starttime;
		animation_update.element = document.getElementById ('update_data');
		animation_update.timer = setInterval ("animate_update();", 13);
		animation_update.from = animation_update.now;
		animation_update.to = 0.0;
		animate_update();
		updateShown = false;
	}
}