-
Notifications
You must be signed in to change notification settings - Fork 2
/
UnitConverter.js
1007 lines (838 loc) · 31.1 KB
/
UnitConverter.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright _ 2005, Apple Computer, Inc. All rights reserved.
NOTE: Use of this source code is subject to the terms of the Software
License Agreement for Mac OS X, which accompanies the code. Your use
of this source code signifies your agreement to such license terms and
conditions. Except as expressly granted in the Software License Agreement
for Mac OS X, no other copyright, patent, or other intellectual property
license or right is granted, either expressly or by implication, by Apple.
*/
//————————————————————————————————————————————————————————————————————————————————————————
//
// Globals
//
//————————————————————————————————————————————————————————————————————————————————————————
var gDebug = 2;
var gMinReloadTime = 60*60*1000; // one hour
var gRetryTime = 30*1000; // thirty seconds
// Default Category is Area, and default units are:
var defaultCatIndex = 0;
var defaultFromIndex = 0;
var defaultToIndex = 4;
// Timer for ticking Time category clock
var timerTimeInterval = null;
// Timer for fetching currency rates
var timerCurrencyInterval = null;
// Flag to indicate if currency data is available
// -1 indicates data is not available, 0 indicates data is available from prefs
// and 1 indicates data is available from feed
var currencyDataAvailable = -1;
// directInput
var directInput = false;
// is the flipper showing?
var flipShown = false;
// Was the time AM the last time we updated the clock?
// N.B., this should actually be set before it's used
// but it's better safe than sorry...
var wasAM = false;
// currency load tries
var currencyLoadTries = 0;
// support for apple site parser
gLastUnitConverterXMLRequest = null;
// debuging functions
function dumpToString(o,depth,newLines,indent)
{
var retVal = "";
if ((newLines == null) || (newLines == true))
newLines = depth - 1;
if (indent == null)
indent = 1;
if (depth == null)
depth = 1;
if ((typeof o == "string") || (typeof o == "number") || (typeof o == "boolean") || (typeof o == "function")) {
if (newLines >= 0)
for (ii = 0; ii < indent; ii++) retVal += " ";
retVal += "'"+o+(newLines >= 0 ?"'\n" : "' ");
} else if (depth > 0) {
for (ii = 0; ii < indent; ii++) retVal += " ";
retVal += (newLines > 0 ? "{\n" : "{");
for (f in o) {
if (newLines > 0)
for (ii = 0; ii < indent; ii++) retVal += " ";
retVal += f+":"+dumpToString(o[f],depth-1,newLines-1,indent+1);
}
for (ii = 0; ii < (indent-1); ii++) retVal += " ";
retVal += (newLines >= 0 ? "}\n" : "}");
} else if (newLines >= 0)
retVal += "\n";
return retVal;
}
function testUnits(category)
{
alert('--------------------');
var units = Categories[category].array;
var length = units.length;
for (var i = 0; i < length; i++) {
if ( Categories[category].name == "Currency") {
alert(units[i].name+": "+1.0*units[i].fromBase+"*"+1.0*units[i].toBase+" = "+1.0*units[i].fromBase*units[i].toBase );
} else {
alert(units[i].name+": "+units[i].fromBase(1.0)+" o "+units[i].toBase(1.0)+" = "+units[i].fromBase(units[i].toBase(1.0))+" and "+units[i].toBase(units[i].fromBase(1.0)));
}
}
}
function $(id) {
return document.getElementById(id);
}
// main initialization
function load() {
new AppleInfoButton($('infoButton'), $('front'), "black", "black", showbackside);
// Set up back but do not display
new AppleGlassButton ($('done'), getLocalizedString('Done'), selectDone);
$('attribution-text').innerText = getLocalizedString('Attribution');
// Initialize static string
$('convert-label').innerText = getLocalizedString('Convert');
$("tosLink").innerText = getLocalizedString("Terms of Service");
loadPreferences();
}
function loadPreferences() {
// Setup Category and unit popups
var savedDefaultCatIndex = getCategoryFromPreferences();
populateCategorySelect();
convertAmount($('convertAmount-input').value,"left");
defaultCatIndex = savedDefaultCatIndex;
setCategory();
$('unitCategory-popup').options[defaultCatIndex].selected = true;
}
//————————————————————————————————————————————————————————————————————————————————————————
//
// Global Events
//
//————————————————————————————————————————————————————————————————————————————————————————
function onshow () {
if (Categories[defaultCatIndex].name == 'Time') {
drawClockBackground();
installTimeTimer();
}
if (Categories[defaultCatIndex].name == 'Currency') {
loadCurrencyExchangeRates();
}
}
function onhide() {
removeTimeTimer();
removeCurrencyTimer();
}
function onremove() {
if (window.widget)
{
// Remove all preferences
widget.setPreferenceForKey(null, instanceKey("defaultCategory"));
var numCat = Categories.length;
for (var j = 0; j < numCat; j++)
{
widget.setPreferenceForKey(null, instanceKey(Categories[j].name + "UnitTo"));
widget.setPreferenceForKey(null, instanceKey(Categories[j].name + "UnitFrom"));
}
}
}
function onsync() {
loadPreferences();
}
if (window.widget) {
widget.onhide = onhide;
widget.onshow = onshow;
widget.onsync = onsync;
widget.onremove = onremove;
}
//————————————————————————————————————————————————————————————————————————————————————————
//
// Functions to populate popup menus
//
//————————————————————————————————————————————————————————————————————————————————————————
function populateCategorySelect()
{
var select = $('unitCategory-popup');
var numCat = Categories.length;
for (var j = 0; j < numCat; j++)
{
var element = document.createElement("option");
element.innerText = getLocalizedString(Categories[j].name);
element.setAttribute("name",Categories[j].name);
select.appendChild(element);
}
select.options[defaultCatIndex].selected = true;
}
function populateUnitSelect(select)
{
// remove all children
while (select.hasChildNodes())
select.removeChild(select.firstChild);
var units = Categories[defaultCatIndex].array;
var length = units.length;
// Treat Currency a bit different since the names are localized by
// the system and we are appending the symbol to the currency name
if ( Categories[defaultCatIndex].name == "Currency")
{
units.sort(function (a, b) {
if (a.iso == "USD") return -1;
else if (b.iso == "USD") return 1;
else if (a.name < b.name) return -1;
else if (b.name < a.name) return 1;
return 0;
});
for (var i = 0; i < length; ++i)
{
var element = document.createElement("option");
var symbol;
if (window.ConverterPlugin) {
symbol = ConverterPlugin.currencySymbolForCode( units[i].iso );
}
element.innerText = units[i].name + " (" + symbol + ")";
element.setAttribute("name",units[i].name);
select.appendChild (element);
}
}
else {
for (var i = 0; i < length; ++i)
{
var element = document.createElement("option");
element.innerText = getLocalizedString(units[i].name);
element.setAttribute("name",units[i].name);
select.appendChild (element);
}
}
}
//————————————————————————————————————————————————————————————————————————————————————————
//
// Functions to handle selection of a category or unit
//
//————————————————————————————————————————————————————————————————————————————————————————
//————————————————————————————————————————————————————————————————————————————————————————
// • unitCategoryChanged
//
// Resets the data for the text field popups and clears the text fields.
// Selects the default units for the left (from) and right (to) menu.
//————————————————————————————————————————————————————————————————————————————————————————
function unitCategoryChanged (select)
{
if (defaultCatIndex != select.selectedIndex)
{
// remove timer if old category was time and new one is not
// clear live clock
if (Categories[defaultCatIndex].name == 'Time')
{
removeTimeTimer();
$('time-hour').innerText = "";
$('time-minutes').innerText = "";
$('time-seconds').innerText = "";
$('time-monospaced').innerText = "";
}
// remove timer if old category was currency and the new one if not
if (Categories[defaultCatIndex].name == 'Currency')
{
removeCurrencyTimer();
}
defaultCatIndex = select.selectedIndex;
setCategory();
}
}
function updateUIElements()
{
var catName = Categories[defaultCatIndex].name;
// For Currency show status text and flipper, for other categories
// hide the text and the flipped
if (catName == 'Currency') {
displayCurrencyStatusText();
$('infoButton').style.display = "block";
flipShown = true;
} else {
$('currency-status').innerText = "";
$('infoButton').style.display = "none";
flipShown = false;
}
populateUnitSelect($('fromUnit-popup'));
populateUnitSelect($('toUnit-popup'));
// if currency data is not available, only update Category
// so user can switch if data is not available.
if (catName == 'Currency' && currencyDataAvailable == -1) {
updatePopupLabels(false);
} else {
// select the default or preferred units for the given category
setUnitsFromPreferences();
$('fromUnit-popup').options[defaultFromIndex].selected = true;
$('toUnit-popup').options[defaultToIndex].selected = true;
updatePopupLabels(true);
$('convertAmount-input').focus();
}
}
function updateCurrencyUIElements() {
var catName = Categories[defaultCatIndex].name;
// For Currency show status text and flipper, for other categories
// hide the text and the flipped
if (catName == 'Currency') {
displayCurrencyStatusText();
$('infoButton').style.display = "block";
flipShown = true;
} else {
$('currency-status').innerText = "";
$('infoButton').style.display = "none";
flipShown = false;
}
// if currency data is not available, only update Category
// so user can switch if data is not available.
if( catName == 'Currency' && currencyDataAvailable == -1) {
populateUnitSelect($('fromUnit-popup'));
populateUnitSelect($('toUnit-popup'));
updatePopupLabels(false);
} else {
populateUnitSelect($('fromUnit-popup'));
populateUnitSelect($('toUnit-popup'));
// select the default or preferred units for the given category
setUnitsFromPreferences();
$('fromUnit-popup').options[defaultFromIndex].selected = true;
$('toUnit-popup').options[defaultToIndex].selected = true;
updatePopupLabels(true);
$('convertAmount-input').focus();
}
}
function setCategory ()
{
var catName = Categories[defaultCatIndex].name;
saveCategoryToPreferences();
// Show the image for the current category
// Time has a live clock, install timer and get the clock ticking...
if (catName == 'Time') {
drawClockBackground();
installTimeTimer();
} else {
$('catImage').src = "Images/"+Categories[defaultCatIndex].name+".png";
}
// clear the input fields
$('converted-input').value = "";
$('convertAmount-input').value ="" ;
if (catName == 'Currency') {
loadCurrencyExchangeRates();
}
updateUIElements();
}
function displayCurrencyStatusText()
{
var currency = Categories[defaultCatIndex].array;
var statusText = "";
if( currency.length == 0 )
{
statusText = getLocalizedString("Retrieving data.");
}
else
{
var statusDateFrom = currency[defaultFromIndex].lastUpdated;
var statusDateTo = currency[defaultToIndex].lastUpdated;
if ( (statusDateFrom == 0) || (statusDateTo == 0))
{
statusText = getLocalizedString("CurrencyNotAvailable");
}
else {
var statusDateFromMS = statusDateFrom.valueOf();
var statusDateToMS = statusDateTo.valueOf();
var statusDateMS = (statusDateFromMS<statusDateToMS ? statusDateFromMS : statusDateToMS);
var statusDate = new Date(statusDateMS);
var dateStr = statusDate.toLocaleDateString("short");
var timeStr = statusDate.toLocaleTimeString("short");
if ((timeStr.toLowerCase() == "invalid date") || (dateStr.toLowerCase() == "invalid date")) {
statusText = getLocalizedString("CurrencyNotAvailable");
} else {
statusText = getLocalizedString("CurrencyLastUpdated") + " " + getLocalizedString(dateStr) + " "+ getLocalizedString(timeStr);
}
}
}
$('currency-status').innerText = statusText;
}
//————————————————————————————————————————————————————————————————————————————————————————
// • updatePopupLabels
//
// Set the label for the popup menus.
// If no data if available (currency) then set the label to empty string
//————————————————————————————————————————————————————————————————————————————————————————
function updatePopupLabels(unitLabelsAvailable) {
$('convertCat-label').innerText = $('unitCategory-popup').options[defaultCatIndex].value;
if (unitLabelsAvailable) {
$('fromUnit-label').innerText = $('fromUnit-popup').options[defaultFromIndex].value;
$('toUnit-label').innerText = $('toUnit-popup').options[defaultToIndex].value;
saveUnitsToPreferences();
} else {
$('fromUnit-label').innerText = "";
$('toUnit-label').innerText = "";
}
}
function switchUnits(event)
{
var temp = defaultFromIndex;
defaultFromIndex = defaultToIndex;
defaultToIndex = temp;
$('fromUnit-popup').options[defaultFromIndex].selected = true;
$('toUnit-popup').options[defaultToIndex].selected = true;
updatePopupLabels(true);
convertAmount ($('convertAmount-input').value, "left");
}
function fromUnitChanged (select)
{
if (defaultFromIndex != select.selectedIndex)
{
defaultFromIndex = select.selectedIndex;
updatePopupLabels(true);
convertAmount ($('converted-input').value, "right");
$('convertAmount-input').focus();
saveUnitsToPreferences();
}
}
function toUnitChanged (select)
{
if (defaultToIndex != select.selectedIndex)
{
defaultToIndex = select.selectedIndex;
updatePopupLabels(true);
convertAmount ($('convertAmount-input').value, "left");
$('convertAmount-input').focus();
saveUnitsToPreferences();
}
}
//————————————————————————————————————————————————————————————————————————————————————————
//
// Functions to convert
//
//————————————————————————————————————————————————————————————————————————————————————————
function doConvertAmountLater(el, dir)
{
var id = el.id;
var code = "convertAmount($('"+id+"').value, '"+dir+"');";
setTimeout(code, 0);
}
//————————————————————————————————————————————————————————————————————————————————————————
// • convertAmount
//
// Converts amounts between fields. If amount is not a number then result is set to the
// empty string
//————————————————————————————————————————————————————————————————————————————————————————
function convertAmount(amount, from)
{
var unitArray = Categories[defaultCatIndex].array;
var c = unitArray.length;
var convertedValue = "";
var fromIndex = (from=="left"?defaultFromIndex:defaultToIndex);
var toIndex = (from=="left"?defaultToIndex:defaultFromIndex);
var floatAmount;
if ( Categories[defaultCatIndex].name == 'Currency' ) {
var currencyCode = unitArray[fromIndex].iso;
if (window.ConverterPlugin) {
floatAmount = ConverterPlugin.valueForFormattedString(amount,unitArray[fromIndex].iso);
}
} else {
if (window.ConverterPlugin) {
floatAmount = ConverterPlugin.valueForFormattedString(amount,null);
}
}
floatAmount = parseFloat(amount); //A quick fix saves the day!
if (isNaN(floatAmount) == false)
{
console.log("not nan");
console.log(floatAmount);
var baseValue ="";
// avoid conversion errors if from and to index are the same
if( fromIndex == toIndex )
convertedValue = floatAmount;
else {
if( Categories[defaultCatIndex].name == 'Currency' )
{
if(window.event && window.event.which == 9) //don't update which focus comes from tab
return;
if ( (unitArray[toIndex].lastUpdated != null ) && (unitArray[fromIndex].lastUpdated != null ))
{
var fromData = unitArray[fromIndex];
var toData = unitArray[toIndex];
var baseValue = floatAmount * fromData.toBase;
convertedValue = baseValue * toData.fromBase;
var fromPrec = (fromData.precision == null ? 8 : fromData.precision);
var toPrec = (toData.precision == null ? 8 : toData.precision);
precision = (fromPrec < toPrec ? fromPrec : toPrec);
// convertedValue = ConverterPlugin.formattedStringForCurrencyValue(convertedValue,precision,unitArray[toIndex].iso);
// use the above once we fix the problem with currency symbols on input
if (window.ConverterPlugin) {
convertedValue = ConverterPlugin.formattedStringForCurrencyValue(convertedValue,precision,3,null);
}
}
}
else {
var baseValue = unitArray[fromIndex].toBase(floatAmount);
convertedValue = unitArray[toIndex].fromBase(baseValue);
var precision = Categories[defaultCatIndex].precision;
if (window.ConverterPlugin) {
convertedValue = ConverterPlugin.formattedStringForValue(convertedValue,precision);
}
}
}
}
var elem = (from=="left"?$('converted-input'):$('convertAmount-input'));
elem.value = convertedValue;
}
//————————————————————————————————————————————————————————————————————————————————————————
//
// • Functions to manage clock in Time category
//
//————————————————————————————————————————————————————————————————————————————————————————
function removeTimeTimer()
{
if (timerTimeInterval != null) {
clearInterval(timerTimeInterval);
timerTimeInterval = null;
}
}
function installTimeTimer()
{
if (timerTimeInterval == null)
timerTimeInterval = setInterval("updateClock();", 1000);
}
function updateClock()
{
var timeString;
if (window.ConverterPlugin) {
timeString = ConverterPlugin.currentTimeString();
}
if ( timeString == null || timeString.match( /^[0-9]{2}:[0-9]{2}:[0-9]{2}$/ ) ) {
var now = new Date();
if ( wasAM != isAM(now) )
drawClockBackground();
else {
// drawClockBackground() calls updateClock(), so if we
// call it, we've just done all this and don't need
// to do it again
var time = now.getHours();
if ( window.ConverterPlugin && ConverterPlugin.isUserTimeFormatTwelveHours() )
if ( time > 12 )
time = time - 12;
else if ( time == 0 )
time = 12;
$('time-hour').innerText = time;
time = now.getMinutes();
if (time < 10 )
$('time-minutes').innerText = "0" + time;
else
$('time-minutes').innerText = time;
time = now.getSeconds();
if (time < 10 )
$('time-seconds').innerText = "0" + time;
else
$('time-seconds').innerText = time;
}
}
else
$('time-monospaced').innerText = timeString;
}
function drawClockBackground()
{
// Clear the time strings
$('time-monospaced').innerText = "";
$('time-hour').innerText = "";
$('time-minutes').innerText = "";
$('time-seconds').innerText = "";
// Determine which background to use and use it
var now = new Date();
var timeString;
if (window.ConverterPlugin) {
timeString = ConverterPlugin.currentTimeString();
}
if ( timeString == null || timeString.match( /^[0-9]{2}:[0-9]{2}:[0-9]{2}$/ ) ) {
wasAM = isAM(now);
if ( window.ConverterPlugin && ConverterPlugin.isUserTimeFormatTwelveHours() ) {
if (isAM(now))
$('catImage').src = "Images/Time_am.png";
else
$('catImage').src = "Images/Time_pm.png";
}
else
$('catImage').src = "Images/Time_24.png";
}
else
$('catImage').src = "Images/Time_wide.png";
// Draw the time strings for the current time
updateClock();
}
function isAM (date)
{
return date.getHours() < 12;
}
//————————————————————————————————————————————————————————————————————————————————————————
//
// • Functions to manage Currency category
//
//————————————————————————————————————————————————————————————————————————————————————————
function computeSymmetricPrecision(from,to)
{
// we look at the accuracy of the symetric operation
var product = from*to;
var deviation = Math.abs(product-1);
var precision = -Math.log(deviation)/Math.log(10);
return Math.floor(precision)+1;
}
function removeCurrencyTimer()
{
if (timerCurrencyInterval != null) {
clearInterval(timerCurrencyInterval);
timerCurrencyInterval = null;
}
}
function setCurrencyTimer()
{
// setCurrencyTimer should not be called;
}
function loadCurrencyExchangeRates()
{
removeCurrencyTimer();
var now = new Date().valueOf();
var nextUpdateTime = Categories[defaultCatIndex].nextUpdate;
if ((nextUpdateTime == null) || (nextUpdateTime < now)) {
currencyLoadTries = 0;
currencyDataAvailable = -1;
fetchCurrencyData();
}
}
function fetchCurrencyData()
{
if (gLastUnitConverterXMLRequest != null)
gLastUnitConverterXMLRequest.abort();
gLastUnitConverterXMLRequest = performXMLRequest (exchangeRatesLoaded);
}
function exchangeRatesLoaded(object) {
removeCurrencyTimer(); // do this here as well just cuz we're paranoid
gLastUnitConverterXMLRequest = null;
var currencyCategory = Categories[currencyCatIndex];
var now = new Date().valueOf();
if (!object.error && object.data) {
currencyCategory.array = object.data;
currencyDataAvailable = 1;
updateCurrencyUIElements();
var nextUpdateTime = object.nextUpdate;
if (nextUpdateTime > (now+gMinReloadTime)) {
currencyCategory.nextUpdate = object.nextUpdate;
} else {
currencyCategory.nextUpdate = now+gMinReloadTime;
}
// save the rates once they are available, in case we need them later
saveRatesToPreferences();
} else {
// there was an error
// check if we already loaded the exchange rates from preferences
if (currencyDataAvailable == -1) {
currencyDataAvailable = ratesFromPreferences();
if (currencyDataAvailable == 0) {
updateCurrencyUIElements();
currencyCategory.nextUpdate = now+gMinReloadTime;
}
}
// is data still not available then display messages
if (currencyDataAvailable == -1) {
if (currencyLoadTries < 8) {
$('currency-status').innerText = getLocalizedString("Data unavailable.");
timerCurrencyInterval = setInterval("loadCurrencyExchangeRates()",gRetryTime);
}
Categories[currencyCatIndex].nextUpdate = null;
}
}
}
//————————————————————————————————————————————————————————————————————————————————————————
//
// • Functions to handle preferences
//
//————————————————————————————————————————————————————————————————————————————————————————
function saveCategoryToPreferences()
{
setInstanceAndGlobalPreferenceForKey(defaultCatIndex.toString(), "defaultCategory");
}
function saveUnitsToPreferences()
{
if (window.widget)
{
var unitKey = Categories[defaultCatIndex].name + "UnitFrom";
setInstanceAndGlobalPreferenceForKey(defaultFromIndex.toString(), unitKey);
unitKey = Categories[defaultCatIndex].name + "UnitTo";
setInstanceAndGlobalPreferenceForKey(defaultToIndex.toString(), unitKey);
}
}
function getCategoryFromPreferences()
{
var catIndex = defaultCatIndex;
catIndex = getPreferenceForKey ("defaultCategory");
if ( catIndex == null )
catIndex = defaultCatIndex;
return catIndex;
}
function setUnitsFromPreferences()
{
// set default values
defaultFromIndex = Categories[defaultCatIndex].defaultFrom;
defaultToIndex = Categories[defaultCatIndex].defaultTo;
// check preferences and set values if available
if (window.widget)
{
var unitKey = Categories[defaultCatIndex].name + "UnitFrom";
// get instance or global value
var unitValue = getPreferenceForKey(unitKey);
if (unitValue != null)
defaultFromIndex = unitValue;
unitKey = Categories[defaultCatIndex].name + "UnitTo";
// get instance or global value
unitValue = getPreferenceForKey(unitKey);
if (unitValue != null)
defaultToIndex = unitValue;
}
}
/**
* Returns instance key for given key
*/
function instanceKey(key)
{
return widget.identifier + "-" + key;
}
/**
* Looks for instance value for given key. if instance value doesn't exist,
* returns global value for key instead. Retrns null if neither exists.
*/
function getPreferenceForKey(key)
{
var res = null;
if (window.widget) {
res = widget.preferenceForKey(instanceKey(key));
if (null == res) {
res = widget.preferenceForKey(key);
}
}
return res;
}
/**
* Sets both global and istance preferece for key to value
*/
function setInstanceAndGlobalPreferenceForKey(value, key)
{
if (window.widget) {
widget.setPreferenceForKey(value, instanceKey(key));
widget.setPreferenceForKey(value, key);
}
}
function saveRatesToPreferences()
{
if( window.widget )
{
var str = "["
var currencyData = Categories[currencyCatIndex].array;
var length = currencyData.length;
for (var i = 0; i < length; ++i)
{
var data = currencyData[i];
if (i != 0)
str += ",";
var dateInMilliseconds = data.lastUpdated.valueOf();
str += "{iso:'" + data.iso + "',toBase:'" + data.toBase + "',fromBase:'" + data.fromBase + "',lastUpdated:'" + dateInMilliseconds + "'}";
}
str += "];";
widget.setPreferenceForKey (str, "currencies");
}
}
function ratesFromPreferences()
{
var dataAvailable = -1; // no data is available (see documentation for currencyDataAvailable)
if( window.widget )
{
try {
var currencyData = widget.preferenceForKey("currencies");
var newAllData = new Array;
currencyData = eval(currencyData);
var length = currencyData.length;
if (length > 0)
{
for (var i = 0; i < length; ++i)
{
var data = currencyData[i];
var name;
if (window.ConverterPlugin) {
name = ConverterPlugin.currencyNameForCode(data.iso);
}
var time = new Date(data.lastUpdated);
// just in case we have old prefs that don't have this would be bad to blow up
var precision = computeSymmetricPrecision(data.toBase,data.fromBase);
newAllData[newAllData.length]
= {name:name, iso:data.iso, lastUpdated:time, toBase:data.toBase, fromBase:data.fromBase, precision:precision};
}
Categories[currencyCatIndex].array = newAllData;
dataAvailable = 0;
}
} catch(ex)
{
}
}
return dataAvailable;
}
//————————————————————————————————————————————————————————————————————————————————————————
//
// • Functions to handle backside
//
//————————————————————————————————————————————————————————————————————————————————————————
function showbackside(event)
{
var front = $("front");
var back = $("back");
if (window.widget)
widget.prepareForTransition("ToBack");
front.style.display="none";
back.style.display="block";
if (window.widget)
setTimeout ('widget.performTransition();', 0);
}
function selectDone ()
{
var front = $("front");
var back = $("back");
if (window.widget)
widget.prepareForTransition("ToFront");
front.style.display="block";
back.style.display="none";
if (window.widget)
setTimeout ('widget.performTransition();', 0);
if( Categories[defaultCatIndex].name == 'Currency' )
{
flipShown = true;
}
onshow();
}
function getLocalizedString (key)
{
try {
var ret = localizedStrings[key];
if (ret === undefined)
ret = key;
return ret;
} catch (ex) {}
return key;
}
function clickOnProvider(event)
{
if (window.widget)
widget.openURL("http://api.apple.go.yahoo.com/appledwuc/");
}
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:300px;" +
"padding: 10px;");
document.body.appendChild(debug.box);
debug.box.innerHTML = "<h1 style='text-align:center'>Debug Output</h1>";
}
var p = document.createElement("p");
p.appendChild(document.createTextNode(msg));
debug.box.appendChild(p);