This file is indexed.

/usr/share/xul-ext/ubiquity/standard-feeds/search.xhtml is in xul-ext-ubiquity 0.6.4~pre20140729-1.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

   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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
<?xml version="1.0" encoding="UTF-8"?>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
  <title>Ubiquity Web Search Commands</title>
  <link rel="commands" href="search.xhtml"/>
</head>
<style>
  div[id] {display: none}
  script {display: block; white-space: pre; font-family: monospace}
</style>
<body>
<p>This XHTML feed contains commands for searching the Web.</p>

<div id="google-search">
{if results.length}
{for result in results}
<div class="gresult">
  <div>
    ${result.key}: <a href="${result.unescapedUrl}" accesskey="${result.key}">${result.title}</a>
  </div>
  <div class="gresult-content">${result.content}</div>
  <div class="gresult-url">${result.visibleUrl}</div>
</div>
{/for}
<small>${tipsMessage}</small>
{else}
${noResultsMessage}
{/if}
</div>

<div id="amazon-search">
<style>
  ol, ul {list-style: none; margin: 0; padding: 0}
  img {float: right; margin: 0 0 0.5em 0.5em}
  kbd {vertical-align: middle; text-transform: uppercase}
  kbd:after {content: ":"}
  kbd, .price {font-weight: bolder}
  .item {margin-top: 0.4em; clear: right}
  .feature {margin-top: 0.2em}
  .price, .author, .label, .feature {font-size: 88%}
  .author:before {content: "by "}
  .feature:before {content: "\2022  "}
</style>
${matchMessage}
<ol>
{for item in items}
  <li class="item">
    {if item.image}
      <a href="${item.url}"><img src="${item.image.src}" border="0"
        height="${item.image.height}" width="${item.image.width}"/></a>
    {/if}
    <kbd>${item.key}</kbd>
    <a href="${item.url}" accesskey="${item.key}">${item.title}</a>
    {if item.price}
      <nobr class="price">
        ${item.price.amount} (${item.price.currency})
      </nobr>
    {/if}
    {if item.author}
      <div class="author">${item.author}</div>
    {/if}
    {if item.label}
      <div class="label">${item.label}</div>
    {/if}
    <ul>
    {for feature in item.features}
      <li class="feature">${feature}</li>
    {/for}
    </ul>
  </li>
{/for}
</ol>
</div>

<div id="flickr-search">
<b>${foundMessage}</b><br/><br/>
<table style="border-width: 0px;">
{for photo in photos}
  {if photo_index % numcols == 0}
  <tr height="100">
  {/if}
  <td>
    <a href="http://www.flickr.com/photos/${photo.owner}/${photo.id}" title="${photo.title|escape}">
      <img src="http://farm${photo.farm}.static.flickr.com/${photo.server}/${photo.id}_${photo.secret}_t.jpg" />
    </a>
  </td>
  {if photo_index % numcols == (numcols - 1)}
  </tr>
  {/if}
{/for}
</table>
</div>

<div id="weather-search">
  <style>
  .mainimg { float: left }
  .weather { font-family: arial, helvetica, sans-serif }
  .forecast { clear: both }
  .forecast th, .forecast td { text-align: center }
  .forecast .icon { text-align: right }
  .forecast img { width: 75% }
  .temp { font-size: 60px }
  .high { color: #f66 }
  .low  { color: #66f }
  </style>
  <div class="weather">
    ${weatherMessage}<br />
    {if w.img}<img class="mainimg" src="${w.img}"/>{/if}
    <div class="temp">${w.temp}</div>
    <div class="extra">
      ${w.condition}<br/>
      ${w.wind}<br/>
      ${w.humidity}<br/>
    </div>
    <table class="forecast">
    <tr>{for day in w.forecast}
      <td class="icon">{if day.img}<img src="${day.img}"/>{/if}</td>
    {/for}</tr>
    <tr>{for day in w.forecast}
      <th class="label">${day.label}</th>
    {/for}</tr>
    <tr>{for day in w.forecast}
      <td class="condition">${day.condition}</td>
    {/for}</tr>
    <tr>{for day in w.forecast}
      <td class="high">${day.high}</td>
    {/for}</tr>
    <tr>{for day in w.forecast}
      <td class="low">${day.low}</td>
    {/for}</tr>
    </table>
  </div>
</div>

<div id="wikipedia-search">
<style>
.wikipedia { margin: 0 }
.title { clear: left; margin-top: 0.4em }
.title a { font-weight: bold }
.key:after {content: ":"}
.summary { margin: 0.2em 0 0 1em; font-size: smaller }
.thumbnail {
  float: left; max-width: 80px; max-height: 80px; background-color: white;
  margin-right: 0.2em;
}
</style>
<dl class="wikipedia">
${foundMessage}
{for article in results}
  <dt class="title">
    <span class="key">${article.key}</span>
    <a href="${article.title|wikilink}" accesskey="${article.key}"
    >${article.title}</a>
  </dt>
  <dd class="summary" wikiarticle="${article.title}">
    <i>${retrievingArticleSummary}</i>
  </dd>
{forelse}
  <p class='error'>${noArticlesFound}</p>
{/for}
</dl>
</div>

<div id="yelp-search">
<style>
.biz {
  margin-bottom: 10px;
}

.name{ font-size: 120%;}

.biz a {
  color: #0066cc;
  text-decoration: underline;
  font-size: small;
}

.biz img{ position: relative; top: 15px;}

.content {
  margin-right: 10px;
  font-size: x-small;
}
</style>

{for biz in businesses}
<div class="biz">
  <img src="${biz.photo_url_small}" height="40" width="40"/>
  ${biz|yelpBusiness}
</div>
{/for}
</div>
<div id="youtube-search">
  <p>
   Found <b>${numresults}</b> YouTube Videos matching <b>${query}</b>
  </p>
  {for entry in results}
  <div style="display: block; margin-bottom: 10px; clear: both;" >
   <a style="color: blue; font-size: 14px;" href="${entry.link[0].href}">
   <img style="float:left; margin-right: 10px; border:thin solid white; height: ${entry['media$group']['media$thumbnail'][0].height}px; width: ${entry['media$group']['media$thumbnail'][0].width}px;"
   src="${entry['media$group']['media$thumbnail'][0].url}" />
   ${entry.title.$t}
   </a>
   <br/>
   <small>${entry['media$group']['yt$duration'].seconds} seconds</small>
   <p>
     <!-- TODO: for some stupid reason, this doesn't work or am I missing something? -->
     <!-- {if entry.content.$t.length > 300}
         ${entry.content.$t.substr(0,300)} ...
      {else}
         ${entry.content.$t}
      {/if} -->

      ${entry.content.$t.substr(0,300)}
   </p>
  </div>
  {/for}
  <br/><br/>
</div>

<div id="map-css">
body {margin:0; padding:0}
#buttons {position:absolute; top:4px; left:64px; opacity:0.6}
#buttons > input:not([accesskey=c]):not([accesskey=v])
  {position:absolute; top:-9999px}
#buttons > input {font:bold small monospace; padding:0}
.adp-listsel {color:#fff !important; background-color:#666 !important}
.adp-list {color:#ddd !important; background-color:#333 !important}
.adp-list td {font-size:88%}
.adp-placemark {
  color:#eee !important; background-color:#555 !important; font-size:112%;
}
.adp-summary, .adp-directions {color:#ccc; font-size:96%}
.adp-listheader, .adp-legal {display:none}
#trips, #addrs {
  max-width: 40%;
  position:absolute; bottom:12px; right:4px; z-index:5;
  background-color:#000; opacity:0.666; font-size:76%;
  border-radius:6px;
}
#trips {max-height:88%; overflow-y:auto}
#addrs, #trips, #trips td {color:#eee}
#addrs {padding:0 3px; border-radius:8px; background-color:#000}
#addrs > a {display:block; text-decoration:none; color:#ccc}
#addrs > a::before {
  content:attr(accesskey); margin-right:0.4em;
  font:bold monospace; text-decoration:underline}
#addrs > .active {color:#fff}
#addrs > .active::before {text-decoration:none}
</div>

<script type="?" class="commands"><![CDATA[

const SEARCH_TERM = _("search term")
    , H = Utils.escapeHtml

// TODO this should use a provider plugin
CmdUtils.CreateCommand({
  names: ["search", "find", "look for"],
  description: "Search using your installed search engines",
  help: "Specify any Open Search engine you have installed by entering " +
        "e.g. 'search with google', 'search with yahoo', etc.",
  icon: "chrome://ubiquity/skin/icons/search.png",
  arguments: [
    {role: "object", nountype: noun_arb_text, label: SEARCH_TERM},
    {role: "instrument", nountype: noun_type_search_engine},
  ],
  preview: function search_preview(previewBlock, {object, instrument}) {
    previewBlock.innerHTML = _(
      "Search using <b>${engine}</b> for:<br /><b>${query}</b>",
      {engine: instrument.data.name, query : object.text});
  },
  execute: function search_execute({object, instrument}) {
    var submission = instrument.data.getSubmission(object.text, null);
    Utils.openUrlInBrowser(submission.uri.spec, submission.postData);
  }
});

CmdUtils.makeSearchCommand({
  names: ["Google"],
  url: "http://www.google.com/search?q={QUERY}",
  icon: "chrome://ubiquity/skin/icons/google.ico",
  description: "Searches Google for your words.",
  help: "You can use the keyboard shortcut ctrl + alt + number to open one " +
        "of the Google results shown in the preview.",
  preview: function google_preview(pblock, {object}) {
    var searchTerm = object.text;
    // Don't even display any text before fetching search results,
    // since the results come back nearly instantaneously. In the
    // future, we can display a throbber.
    if (!searchTerm) return void this.previewDefault(pblock);

    var url = "http://ajax.googleapis.com/ajax/services/search/web";
    var params = {v: "1.0", q: searchTerm, rsz: "small"};

    CmdUtils.previewGet(pblock, url, params, function google_get(data) {
      var {results} = data.responseData;
      results.forEach(function (r, i) { r.key = i + 1 });

      var noResultsMessage = _(
        "Your search - ${searchTerm} - did not match any documents.",
        {searchTerm: object.html.bold()});
      var tipsMessage = _(
        "Tip: You can go to any result in this preview by pressing " +
        "control, alt, and the result number at the same time.");

      pblock.innerHTML = CmdUtils.renderTemplate(
        feed.dom.getElementById("google-search").innerHTML,
        { results: results,
          noResultsMessage: noResultsMessage,
          tipsMessage: tipsMessage });
    }, "json");
  }
});

const ARTICLE_ERROR = _("Error retrieving summary");

function fetchWikipediaArticle(previewBlock, articleTitle, langCode) {
  var apiUrl = "http://" + langCode + ".wikipedia.org/w/api.php";
  var apiParams = {
    format: "json",
    action: "parse",
    page: articleTitle
  };

  CmdUtils.previewAjax(previewBlock, {
    type: "GET",
    url: apiUrl,
    data: apiParams,
    dataType: "json",
    error: function() {
      previewBlock.innerHTML = "<p class='error'>" + ARTICLE_ERROR + "</p>";
    },
    success: function(responseData) {
      //remove relative <img>s beforehand to suppress
      //the "No chrome package registered for ..." message
      var parse = jQuery(("<div>" + responseData.parse.text["*"])
                         .replace(/<img src="\/[^>]+>/g, ""));
      //take only the text from summary because links won't work either way
      var articleSummary = parse.find("p:first").text();
      //remove citations [3], [citation needed], etc.
      articleSummary = articleSummary.replace(/\[.+?\]/g, "");
      //TODO: also remove audio links (.audiolink & .audiolinkinfo)
      //TODO: remove "may refer to" summaries
      var articleImageSrc = (parse.find(".infobox img").attr("src") ||
                             parse.find(".thumbimage") .attr("src") || "");
      previewBlock.innerHTML =
        (articleImageSrc &&
         '<img src="'+ H(articleImageSrc) +'" class="thumbnail"/>') +
        H(articleSummary);
    }
  });
}

CmdUtils.CreateCommand({
  names: ["Wikipedia", "lookup"],
  arguments: [
    {role: "object", nountype: noun_arb_text, label: SEARCH_TERM},
    {role: "format", nountype: noun_type_lang_wikipedia}],
  homepage: "http://theunfocused.net/moz/ubiquity/verbs/",
  author: {name: "Blair McBride", email: "blair@theunfocused.net"},
  contributors: ["Viktor Pyatkovka"],
  license: "MPL",
  icon: "chrome://ubiquity/skin/icons/wikipedia.ico",
  description: "Searches Wikipedia for your words, in a given language.",
  preview: function wikipedia_preview(previewBlock, args) {
    var searchText = Utils.trim(args.object.text);
    if (!searchText) {
      previewBlock.innerHTML = _("Searches Wikipedia in ${lang}.",
                                 {lang: args.format.html || "English"});
      return;
    }
    var previewData = {query: args.object.html};
    previewBlock.innerHTML = _("Searching Wikipedia for <b>${query}</b> ...",
                               previewData);
    var apiParams = {
      format: "json",
      action: "query",
      list: "search",
      srlimit: 5, // is this a good limit?
      srwhat: "text",
      srsearch: searchText
    };

    function onerror() {
      previewBlock.innerHTML =
        "<p class='error'>" + _("Error searching Wikipedia") + "</p>";
    }

    var langCode = args.format.data || "en";
    var apiUrl = "http://" + langCode + ".wikipedia.org/w/api.php";

    CmdUtils.previewAjax(previewBlock, {
      type: "GET",
      url: apiUrl,
      data: apiParams,
      dataType: "json",
      error: onerror,
      success: function wikipedia_success(searchResponse) {
        if (!("query" in searchResponse && "search" in searchResponse.query)) {
          onerror();
          return;
        }

        function generateWikipediaLink(title) (
          "http://" + langCode + ".wikipedia.org/wiki/" +
          title.replace(/ /g, "_"));

        (previewData.results = searchResponse.query.search)
          .forEach(function genKey(o, i) { o.key = i + 1 });
        previewData._MODIFIERS = {wikilink: generateWikipediaLink};
        previewData.foundMessage =
          _("Wikipedia articles found matching <b>${query}</b>:", previewData);
        previewData.retrievingArticleSummary =
          _("Retreiving article summary...");
        previewData.noArticlesFound = _("No articles found.");


        previewBlock.innerHTML = CmdUtils.renderTemplate(
          feed.dom.getElementById("wikipedia-search").innerHTML,
          previewData);

        jQuery("dd", previewBlock).each(function eachDD() {
          var article = this.getAttribute("wikiarticle");
          fetchWikipediaArticle(this, article, langCode);
        });
      }
    });
  },
  execute: function wikipedia_execute(args) {
    var lang = args.format.data || "en";
    var searchUrl = "http://" + lang + ".wikipedia.org/wiki/Special:Search";
    var searchParams = {search: args.object.text};
    Utils.openUrlInBrowser(searchUrl + Utils.paramsToString(searchParams));
  }
});

CmdUtils.makeSearchCommand({
  names: ["Yahoo!"],
  url: "http://search.yahoo.com/search?ei=UTF-8&p={QUERY}",
  defaultUrl: "http://www.yahoo.com",
  icon: "chrome://ubiquity/skin/icons/yahoo.ico",
  description: "Searches <a href='http://search.yahoo.com'>Yahoo!</a> " +
               "for pages matching your words.",
  parser: {
    container  : ".res",
    title      : "h3",
    body       : ".abstr, .sm-abs",
    maxResults : 10,
  },
});

var noun_type_amazon_com_index = CmdUtils.NounType("index", {
  All: 0,
  Apparel: 1036592,
  Appliances: 2619525011,
  ArtsAndCrafts: 2617941011,
  Automotive: 15690151,
  Baby: 165796011,
  Beauty: 11055981,
  Books: 1000,
  Classical: 301668,
  Collectibles: 4991425011,
  DigitalMusic: 195208011,
  DVD: 2625373011,
  Electronics: 493964,
  GourmetFood: 3580501,
  Grocery: 16310101,
  HealthPersonalCare: 3760931,
  HomeGarden: 285080,
  Industrial: 228239,
  Jewelry: 3880591,
  KindleStore: 133141011,
  Kitchen: 1063498,
  LawnGarden: 2972638011,
  Magazines: 599872,
  Miscellaneous: 10304191,
  MobileApps: 2350149011,
  MP3Downloads: 195211011,
  Music: 301668,
  MusicalInstruments: 11091801,
  OfficeProducts: 1084128,
  OutdoorLiving: 1063498,
  PCHardware: 493964,
  PetSupplies: 1063498,
  Photo: 493964,
  Software: 409488,
  SportingGoods: 3375251,
  Tools: 468240,
  Toys: 493964,
  VHS: 404272,
  Video: 130,
  VideoGames: 493964,
  Watches: 377110011,
  Wireless: 508494,
  WirelessAccessories: 13900851,
}, "All");

var Amazon = "http://www.amazon.com/";
var AmazLink = "Amazon.com".link(Amazon);
var AWS_ENDPOINT = "ecs.amazonaws.com";
var AWS_REQUESTURI = "/onca/xml";
// This key is linked to Satyr's AWS account (only free services are enabled).
// Please don't reuse and/or abuse it. Get your own AWS key instead.
var AWS_KEY = "0SP5F78NM10ZVNWWG482";
var AWS_SECRET = "DlSRkBtC3WDAMjA5fVJO4Fg04omvXYVXs49oNPlo";

function amazon_doEscape(aString) (
  encodeURIComponent(aString)
  .replace(/[!\'()*]+/g, function escape0(s) escape(s, 0)));
function amazon_signRequest(aParams) {
  var key;
  var params = {};
  for (key in aParams)
    params[key] = aParams[key];
  params.Timestamp = new Date().toISOString().slice(0, -5) + "Z";
  params.AWSAccessKeyId = AWS_KEY;
  var paramArray = [];
  for (key in params)
    paramArray.push(amazon_doEscape(key) + "=" + amazon_doEscape(params[key]));
  paramArray.sort();
  var paramString = paramArray.join("&");
  var sigBaseString =
    "GET\n" + AWS_ENDPOINT + "\n" + AWS_REQUESTURI + "\n" + paramString;
  var signature = Utils.signHmac("SHA256", AWS_SECRET, sigBaseString);
  return ("http://" + AWS_ENDPOINT + AWS_REQUESTURI + "?" +
          paramString + "&Signature=" + amazon_doEscape(signature));
}

CmdUtils.CreateCommand({
  names: ["Amazon.com"],
  icon: "chrome://ubiquity/skin/icons/amazon.ico",
  description: "Searches " + AmazLink + " for items matching your words.",
  help: '<dl><dt>Available Indices</dt><dd><b>'+
    noun_type_amazon_com_index._list.reduce(function (dd, s) {
      return dd + s.text + ' '
    }, '')
  +'</b></dd></dl>',
  arguments: [
    {role: "object", nountype: noun_arb_text, label: SEARCH_TERM},
    {role: "format", nountype: noun_type_amazon_com_index}],
  execute: function amazon_execute({object: {text}, format: {data}}) {
    var url = Amazon + "s/?"
    if (data) url += "node=" + data + "&"
    url += "field-keywords=" + encodeURIComponent(text)
    Utils.openUrlInBrowser(url)
  },
  preview: function(previewBlock,
                    {object: {text, summary}, format: {text: searchIndex}}) {
    if (!text) return void this.previewDefault(previewBlock);

    var me = this;
    previewBlock.innerHTML =
      _("Searching ${AmazLink} for items matching <b>${query}</b>.",
        {AmazLink: AmazLink, query: summary});
    CmdUtils.previewAjax(previewBlock, {
      url: amazon_signRequest({
        Service: "AWSECommerceService",
        Version: "2011-08-01",
        Operation: "ItemSearch",
        Condition: "All",
        Merchant: "All",
        ResponseGroup: "ItemAttributes,Images",
        AssociateTag: "matyr-20", // required
        SearchIndex: searchIndex,
        Keywords: text,
      }),
      dataType: "xml",
      error: function amazon_error(xhr, info) {
        previewBlock.innerHTML = (
          "<p class='error'>" +
          _("Error searching ${AmazLink}.", {AmazLink: AmazLink}) +
          "<br/><em>" + xhr.status + " " + xhr.statusText +
          " (" + info + ")</em></p>");
        // TODO: think of a better way to localize API errors, if possible.
      },
      success: function amazon_success(responseData) {
        responseData = jQuery(responseData);
        var errorMessage = responseData.find("Error > Message").text();
        if (errorMessage) {
          previewBlock.innerHTML =
            "<p class='error'>" + _(errorMessage) + "</p>";
          return;
        }
        const MAX_RESULTS = 35; // 1 ~ 9, a ~ z
        function iter(itemIndex) {
          var itemDetails = jQuery(this),
          itemAttrs = itemDetails.find("ItemAttributes"),
          listPrice = itemAttrs.find("ListPrice"),
          smallImage = itemDetails.find("SmallImage:first");
          return {
            title: itemAttrs.find("Title").text(),
            url: itemDetails.find("DetailPageURL").text(),
            key: (itemIndex + 1).toString(MAX_RESULTS + 1),
            author: (itemAttrs.find("Author")
                     .map(function() this.textContent).get().join(', ')),
            features: (itemAttrs.find("Feature")
                       .map(function() this.textContent).get()),
            label: itemAttrs.find("Label").text(),
            price: listPrice.length && {
              amount: listPrice.find("FormattedPrice").text(),
              currency: listPrice.find("CurrencyCode").text(),
            },
            image: smallImage.length && {
              src: smallImage.find("URL").text(),
              height: smallImage.find("Height").text(),
              width: smallImage.find("Width").text(),
            }
          };
        }
        previewBlock.innerHTML = CmdUtils.renderTemplate(
          feed.dom.getElementById("amazon-search").innerHTML,
          { items: (responseData.find("Items > Item").slice(0, MAX_RESULTS)
                    .map(iter).get()),
            matchMessage: _(
              ("Found <b>${numitems}</b> item{if numitems > 1}s{/if} on " +
               "<a href='http://www.amazon.com/'>Amazon.com</a> " +
               "matching <b>${query}</b>."),
              { numitems: responseData.find("Items > TotalResults").text(),
                query: text }) });
      }
    });
  }
});

CmdUtils.makeSearchCommand({
  names: ["YouTube"],
  url: ("http://www.youtube.com/results?search_type=search_videos" +
        "&search=Search&search_sort=relevance&search_query={QUERY}"),
  icon: "chrome://ubiquity/skin/icons/youtube.ico",
  description: ("Searches <a href='http://www.youtube.com'>YouTube</a> " +
                "for videos matching your words. Previews the top results."),
  preview: function(pblock, {object: {text, summary}}) {
    if (!text) return void this.previewDefault(pblock);

    pblock.innerHTML = _("Searches YouTube for ${it}.", {it: summary.bold()});
    CmdUtils.previewGet(
      pblock,
      "http://gdata.youtube.com/feeds/api/videos",
      {alt: "json", "max-results": 3, vq: text},
      function youtube_success(data) {
        pblock.innerHTML = CmdUtils.renderTemplate(
          feed.dom.getElementById("youtube-search").innerHTML, {
            results: data.feed.entry,
            query: summary,
            numresults: data.feed["openSearch$totalResults"]["$t"],
          });
      },
      "json");
  }
});

CmdUtils.makeSearchCommand({
  names: ["Flickr", "images"],
  url: "http://www.flickr.com/search/?w=all&q={QUERY}",
  icon: "chrome://ubiquity/skin/icons/flickr.ico",
  description: (
    "Searches <a href=\"http://www.flickr.com\">Flickr</a> " +
    "for pictures matching your keywords. Previews the top pictures."),
  preview: function flickr_preview(previewBlock, {object: {text: inputText}}) {
    if (!inputText) return void this.previewDefault(previewBlock);

    previewBlock.innerHTML = _("Searching for photos on Flickr...");
    CmdUtils.previewAjax(previewBlock, {
      url: "http://api.flickr.com/services/rest/",
      data: {
        api_key: "4ca9aaaf5c2d83260eba9ab68ac1b1ac",
        format: "json",
        nojsoncallback: 1,
        method: "flickr.photos.search",
        media: "photos",
        text: inputText,
        per_page: 12,
        sort: "relevance",
      },
      dataType: "json",
      error: function flickr_error({statusText}) {
        previewBlock.innerHTML = (
          "<p class='error'>" + _("Error searching Flickr.") +
          " (" + Utils.escapeHtml(statusText) + ")</p>");
      },
      success: function flickr_success(responseData) {
        if (responseData.stat !== "ok") {
          this.error({statusText: responseData.stat});
          return;
        }
        previewBlock.innerHTML = CmdUtils.renderTemplate(
          feed.dom.getElementById("flickr-search").innerHTML, {
            numcols: 4,
            photos: responseData.photos.photo,
            foundMessage: _("${nummatches} photos were found on Flickr.",
                            {nummatches: responseData.photos.total}),
          });
      },
    });
  },
});

CmdUtils.makeSearchCommand({
  names: ["Bugzilla"],
  url: "https://bugzilla.mozilla.org/buglist.cgi?quicksearch=%s",
  defaultUrl: "https://bugzilla.mozilla.org",
  help: "Bugzilla QuickSearch".link(
    "https://bugzilla.mozilla.org/page.cgi?id=quicksearch.html"),
  icon: "chrome://ubiquity/skin/icons/mozilla.ico",
  preview: function bugz_preview(pb, args) {
    var query = args.object.text.trim(), me = this;
    if (!query) return void me.previewDefault(pb);
    var shortUrl = "http://bugzil.la/" +
      query.replace(/\S+/g, encodeURIComponent).replace(/\s+/g, "+");
    pb.innerHTML = (
      '<div id="bugzilla">' +
      '<input type="button" class="copy" value="Copy" accesskey="C"/> ' +
      '<a href="' + shortUrl + '" accesskey="H">' + shortUrl + '</a>' +
      '</div>');
    pb.querySelector(".copy").addEventListener("click", function bugz_copy() {
      displayMessage(Utils.clipboard.text = shortUrl, me);
    }, false);
  },
});

CmdUtils.makeSearchCommand({
  names: ["bing"],
  url: "http://www.bing.com/search?q=%s",
  defaultUrl: "http://www.bing.com/",
  icon: "chrome://ubiquity/skin/icons/bing.ico",
  parser: {
    container: "#results li",
    title: "h3 > a",
    body: "p",
    maxResults: 10,
  },
});

CmdUtils.makeSearchCommand({
  name: "IMDb",
  url: "http://www.imdb.com/find?q=%s",
  defaultUrl: "http://www.imdb.com",
  icon: "chrome://ubiquity/skin/icons/imdb.ico",
  parser: {
    container  : ".findResult",
    title      : ".result_text",
    thumbnail  : ".primary_photo",
    maxResults : 8,
  },
});


// -----------------------------------------------------------------
// WEATHER COMMANDS
// -----------------------------------------------------------------

var TEMPERATURE_UNITS = ["fahrenheit", "celsius"];

var noun_type_temperature_unit = CmdUtils.NounType("temperature unit",
                                                   TEMPERATURE_UNITS);

var WEATHER_TYPES = "none|tropical storm|hurricane|severe thunderstorms|thunderstorms|mixed rain and snow|mixed rain and sleet|mixed snow and sleet|freezing drizzle|drizzle|freezing rain|rain|rain|snow flurries|light snow showers|blowing snow|snow|hail|sleet|dust|foggy|haze|smoky|blustery|windy|cold|cloudy|mostly cloudy|mostly cloudy|partly cloudy|partly cloudy|clear|sunny|fair|fair|mixed rain and hail|hot|isolated thunderstorms|scattered thunderstorms|scattered thunderstorms|scattered showers|heavy snow|scattered snow showers|heavy snow|partly cloudy|thundershowers|snow showers|isolated thundershowers".split("|");

var YAHOO_WEATHER_MAP = {
  "unknown": null,
  "snow grains": "light snow showers",
  "ice crystals": "hail",
  "ice pellets": "hail",
  mist: "rain",
  fog: "foggy",
  smoke: "smoky",
  "volcanic ash": "haze",
  "widespread dust": "dust",
  sand: null,
  spray: null,
  "dust whirls": "dust",
  "showers rain": "rain",
  sandstorm: null,
  "low drifting snow": "snow",
  "low drifting widespread dust": "dust",
  "low drifting sand": null,
  "blowing widespread dust": "dust",
  "blowing sand": null,
  "rain showers": "scattered showers",
  "ice pellet showers": "mixed rain and hail",
  "hail showers": "hail",
  "small hail showers": "hail",
  thunderstorm: "thunderstorms",
  "thunderstorms and rain": "thunderstorms",
  "thunderstorms and snow": "mixed rain and snow",
  "thunderstorms and ice pellets": "mixed rain and hail",
  "thunderstorms with hail": "mixed rain and hail",
  "thunderstorms with small hail": "mixed rain and hail",
  "freezing fog": "foggy",
  "overcast": "cloudy",
  "scattered clouds": "partly cloudy",
  "n/a": null,
  // forcast conditions
  "flurries": "snow flurries",
  "freezing rain": "mixed rain and snow",
  "a thunderstorm": "thunderstorms",
  hazy: "haze",
  "mostly sunny": "sunny",
  "partly sunny": "sunny"
};

function yahooWeatherImage(condition,dayOrNight) {
  // dayOrNight must be 'd' or 'n'. By default, it'll be 'd'.
  var conditionCode = condition.toLowerCase().trim();
  if (conditionCode != "heavy snow" && conditionCode != "light snow showers")
    conditionCode = conditionCode.replace(/^(?:heavy|light) /, "");
  conditionCode = conditionCode.replace(/^chance of /, "");

  // map some Weather Underground weather codes to Yahoo! ones.
  if (conditionCode in YAHOO_WEATHER_MAP)
    conditionCode = YAHOO_WEATHER_MAP[conditionCode];

  if (!conditionCode)
    return null;

  var weatherId = WEATHER_TYPES.indexOf(conditionCode);
  return ("http://l.yimg.com/us.yimg.com/i/us/nws/weather/gr/" +
          weatherId + (dayOrNight || "d") + ".png");
}

function formatLatLon(data) data && data.lat + "," + data.lon;

CmdUtils.CreateCommand({
  names: ["check weather", "get weather", "weather"],
  author: {
    name: "mitcho (Michael Yoshitaka Erlewine)",
    email: "mitcho@mitcho.com",
  },
  contributor: "satyr",
  arguments: {
    location: {
      __proto__: noun_type_geo_town,
      default: noun_type_geolocation.default,
    },
    format: noun_type_temperature_unit,
  },
  icon: "chrome://ubiquity/skin/icons/wunderground.ico",
  description: ("Checks the weather for a given location. It detects your " +
                "current location as a default."),
  help: ("Try issuing &quot;weather near chicago&quot;.  It works with " +
         "zip-codes, too.  You can add 'in celsius' or 'in farenheit' to " +
         "specify the temperature scale."),
  execute: function weather_execute({location: {text, data}}) {
    Utils.openUrlInBrowser(
      "http://www.wunderground.com/cgi-bin/findweather/getForecast?query=" +
      encodeURIComponent(formatLatLon(data) || text));
  },
  preview: function weather_preview(pblock, {
    location: {text, data}, format: {text: tempUnit}}) {
    if (!text) {
      pblock.innerHTML = _("Gets the weather for a zip code/city.");
      return;
    }

    const W4L = _("Weather for ${location}");
    pblock.innerHTML = (CmdUtils.renderTemplate(W4L, {location: text}) +
                        " " + Utils.prefs.get("intl.ellipsis", "..."));

    var userLocation = CmdUtils.getGeoLocation();
    //use either the specified "in" unit or get from geolocation
    tempUnit = tempUnit || TEMPERATURE_UNITS[
      +!(userLocation && /^(?:U[SM]|BZ)$/.test(userLocation.country_code))];
    var xmls = {}, param = {query: formatLatLon(data) || text};
    ["WXCurrentObXML", "ForecastXML"].forEach(function (api) {
      CmdUtils.previewGet(
        pblock,
        "http://api.wunderground.com/auto/wui/geo/" + api + "/index.xml",
        param,
        function (x) { xmls[api] = x; weather_tryToPreview(); },
        "xml");
    });
    function weather_tryToPreview() {
      var {WXCurrentObXML: weatherXml, ForecastXML: forecastXml} = xmls;
      if (!weatherXml || !forecastXml) return;

      function qstc(xml, selector) {
        try{
        return xml.querySelector(selector).textContent;
        } catch(e) { Utils.reportInfo(e.stack) }
      }

      //change wind speed to kmh based on geolocation
      var windText = qstc(weatherXml, "wind_string");
      var windSpeed = parseFloat(qstc(weatherXml, "wind_mph"));
      var windUnit = "mph";
      //http://en.wikipedia.org/wiki/Si_units
      if (userLocation) switch (userLocation.country_code) {
        case "US": case "UM": case "LR": case "MM": case "GB":
        break;
        case "JP":
        windUnit = "m/s";
        windSpeed *= .45;
        break;
        default:
        windUnit = "km/h";
        windSpeed *= 1.6;
      }
      var [tempChar] = tempUnit, condition = qstc(weatherXml, "weather");
      var weather = {
        condition: condition,
        temp: (qstc(weatherXml, "temp_" + tempChar) +
               "&#xB0;" + tempChar.toUpperCase()),
        humidity: qstc(weatherXml, "relative_humidity"),
        wind: /^\D+/.exec(windText) + windSpeed.toFixed(1) + windUnit,
        img: yahooWeatherImage(condition),
        forecast: []
      };

      $("simpleforecast > forecastday", forecastXml).each(function (i) {
        var condition = qstc(this, "conditions");
        weather.forecast.push({
          label: i ? _("${month}/${day}", {
            month: qstc(this, "month"),
            day: qstc(this, "day"),
          }) : _("today"),
          condition: condition,
          img: yahooWeatherImage(condition),
          high: qstc(this, "high > " + tempUnit),
          low: qstc(this, "low > " + tempUnit),
        });
      });

      var loc = qstc(weatherXml, "display_location > full");
      pblock.innerHTML = CmdUtils.renderTemplate(
        feed.dom.getElementById("weather-search").innerHTML, {
          w: weather, location: loc,
          weatherMessage: _(W4L, {location: loc}),
        });
    }
  }
});

CmdUtils.CreateCommand({
  names: ["define", "get definition"],
  description: "Gives the meaning of a word, using answers.com.",
  help: "Try issuing &quot;define aglet&quot;",
  icon: "chrome://ubiquity/skin/icons/answers.ico",
  arguments: [{role: "object", nountype: noun_arb_text, label: "word"}],
  execute: function define_execute({object}) {
    Utils.openUrlInBrowser("http://www.answers.com/" + encodeURI(object.text));
  },
  preview: function define_preview(pblock, {object: {text: word, html}}) {
    if (!word) return void this.previewDefault(pblock);

    pblock.innerHTML = _("Gives the definition of the word ${word}.",
                         {word: html});
    CmdUtils.previewAjax(pblock, {
      url: ("http://services.aonaware.com/" +
            "DictService/DictService.asmx/DefineInDict"),
      data: {
        word: word,
        dictId: "wn", // wn: WordNet, gcide: Collaborative Dictionary
      },
      success: function define_success(xml) {
        pblock.innerHTML = (
          jQuery(xml)
          .find("WordDefinition > Definitions > Definition:first-child" +
                " > WordDefinition")
          .text()
          .replace(/^\s*.+/, "<h2>$&</h2>")
          .replace(/\[[^\]]*\]/g, "")
          .replace(/\d+:/g, "<br/><strong>$&</strong>")
          .replace(/1:/g, "<br/>$&"));
      },
    });
  }
});
const GI_TEMPLATE = '<div id="container${counter}" title="${imgurl}" style="position: absolute; border:0px; " class="thumbnail"><a id="anchor${counter}" href="${imgurl}" accesskey="${directNumber}" style="text-decoration: none;"></a><img id="img${counter}" src="${thumb}" title="${imgurl}" style="position: absolute; height:80px; margin: 5px; border:0px; vertical-align:top; z-index: 0; border: 0px solid #00C600; border-radius: 3px;" alt="."/><canvas id="canvas${counter}" width="${miniwidth}" height="80" style="margin: 5px; border:0px; vertical-align:top; z-index:1000;"></canvas><span id="code${counter}" style="color: #FFFFFF;position:absolute;vertical-align:top;border:0px;margin:5px;z-index:1001;">${directNumber}</span></div>';
var gGIPageCounter = 0;
CmdUtils.makeSearchCommand({
  names: ["google image search", "get images"],
  arguments: [{role: "object", nountype: noun_arb_text, label: "query"}],
  version: "0.3.1+",
  author: {name: "Federico Parodi", email: "getimages@jimmy2k.it"},
  homepage: "http://www.jimmy2k.it/getimagescommand",
  license: "MPL",
  icon: "chrome://ubiquity/skin/icons/google.ico",
  description: "Browse and embed pictures from Google Images",
  help: "Press return to show the Google Images results, left click on a picture to watch it, right click to insert it in a text or rich text area",
  url: "http://images.google.com/images?q={QUERY}",
  imgsPerPage: 8,
  previewDelay: 500,
  preview: function gis_preview(pblock, {object: {text: nameText}}) {
    if (!nameText) return void this.previewDefault(pblock);

    // keeps track of the page we are previewing
    gGIPageCounter = 0;
    // saves the first img of every previewed page
    var pageArray = [];
    // saves the first img of the last previewed page
    var previousResult = 0;
    function refresh(currentResult, imgsPerPage) {
      pblock.innerHTML = _("Searching on Google Images...");

      if (currentResult > previousResult)
        gGIPageCounter++;
      else
        gGIPageCounter--;

      previousResult = currentResult;
      pageArray[gGIPageCounter] = currentResult;
      var newPageItem = (gGIPageCounter * imgsPerPage) - 8;
      // This number will be the base for img elements naming.
      var randomCode = Math.floor(Math.random() * 1000000001);
      CmdUtils.previewAjax(pblock, {
        dataType: "json",
        url: "http://ajax.googleapis.com/ajax/services/search/images",
        data: {
          q: nameText,
          v: "1.0",
          rsz: "large",
          start: newPageItem,
        },
        beforeSend: function(xhr) {
          xhr.setRequestHeader("referer",
                               "http://www.jimmy2k.it/getimagescommand");
        },
        error: function() {
          pblock.innerHTML =
            "<em class='error'>" + _("Connection error") + "</em>";
        },
        success: function({responseData}) {
          function action(e, image) {
            var rightclick = false;
            if (e.which) rightclick = (e.which == 3);
            else if (e.button) rightclick = (e.button == 2);

            if (rightclick)
              CmdUtils.setSelection(
                "<img src='" + Utils.escapeHtml(image.title) + "'/>",
                {text: image.title});
            else
              Utils.openUrlInBrowser(image.title);
          }

          var htmlData = (
            _('Image Search results for ${text}', {text: nameText}) +
            '<br><small>' + _('(ctrl + alt + number to open)') + '</small>' +
            '<div id="resImg" style="position: relative; height:370px;font-size:11pt !important;font-family:Calibri, Helvetica, Verdana, Arial !important;">');

          var numberOfResults = responseData.results.length;
          if (numberOfResults == 0) {
            pblock.innerHTML = _('Sorry, there are no results');
            return;
          }
          var resultsArray = responseData.results;
          for (var index = 0; index < numberOfResults; index++) {
            htmlData += CmdUtils.renderTemplate(GI_TEMPLATE, {
              imgurl: resultsArray[index].unescapedUrl,
              thumb: resultsArray[index].tbUrl,
              counter: randomCode + index,
              miniwidth: (80 / resultsArray[index].tbHeight *
                          resultsArray[index].tbWidth | 0),
              directNumber: index + 1,
            });
          }
          htmlData += '<div id="controls" style="position: relative; width: 95%; top:270px;"><div id="prev" class="control" style="display:none; float: left;width: 80px; height: 50px; border: 2px solid #00C600; border-radius: 3px; text-align: center; padding-top: 30px; opacity: 0.5">' + _('Prev') + '(9)</div>';
          if (gGIPageCounter < 8)
            htmlData += '<div id="next" class="control" style="float: right;width: 80px; height: 50px;  border: 2px solid #00C600; border-radius: 3px; text-align: center; padding-top: 30px; opacity: 0.5">' + _('Next') + '(0)</div></div>';
          else
            htmlData += '<div id="next" class="control" style="float: right;width: 80px; height: 50px;  border: 2px solid #00C600; border-radius: 3px; text-align: center; padding-top: 30px; opacity: 0.5">More<br/>on site(0)</div></div>';
          htmlData += '<form><input id="pButton" type="button" accesskey="9" style="opacity:0; display:none;"/><input id="nButton" type="button" accesskey="0" style="opacity: 0;"/></form></div>';
          pblock.innerHTML = htmlData;
          var {ownerDocument} = pblock;
          var moreButton = jQuery("#next", ownerDocument);
          var prevButton = jQuery("#prev", ownerDocument);
          var controls = jQuery(".control", ownerDocument);
          var prevInputButton = jQuery("#pButton", ownerDocument);
          // input tags for getting ctrl + number commands
          var nextInputButton = jQuery("#nButton", ownerDocument);

          if (numberOfResults != 8) moreButton.css("display", "none");

          controls.mouseover(function() {
            jQuery(this).animate({opacity: 1}, 250);
          });

          controls.mouseout(function() {
            jQuery(this).animate({opacity: 0.5}, 250);
          });

          function prevPage() {
            refresh(pageArray[gGIPageCounter - 1], imgsPerPage);
          }

          function nextPage() {
            if (gGIPageCounter < 8)
              refresh(currentResult, imgsPerPage);
            else {
              Utils.openUrlInBrowser(
                "http://images.google.com/images?q=" +
                encodeURIComponent(nameText) + "&start=64");
              context.chromeWindow.gUbiquity.closeWindow();
            }
          }

          moreButton.click(function() {
            nextPage();
          });

          nextInputButton.click(function() {
            nextPage();
          });

          prevInputButton.click(function() {
            prevPage();
          });

          prevButton.click(function() {
            prevPage();
          });

          if (gGIPageCounter !== 1) {
            prevButton.css("display", "inline");
            prevInputButton.css("display", "inline");
          }

          var col = 0;
          var row = 0;

          for (var index = 0; index < numberOfResults; index++) {
            var imgTag = jQuery("#img" + (randomCode + index), ownerDocument);
            var containerTag = jQuery("div#container" + (randomCode + index),
                                      ownerDocument);
            containerTag.mousedown(function(e) {
              action(e, this);
            });
            // positioning stuff
            var thisWidth = Math.floor(
              resultsArray[index].tbWidth / resultsArray[index].tbHeight * 80);
            if (thisWidth > 470) {
              thisWidth = 470;
              imgTag.css("width", thisWidth);
            }

            if ((col + thisWidth) > 470) {
              row += 85;
              col = 0;
            }

            imgTag.css("left", col);
            imgTag.css("top", row);

            // zoom in effect
            var leftBig = Math.floor((thisWidth * -0.0625) + 5);

            containerTag.mouseover(function(e) {
              if (!e) return;
              var relTarg = e.relatedTarget;
              if (relTarg == null) return;
              // no animation if I'm moving on different parts of the same thumbnail
              if (relTarg != null && relTarg.id.length >= 4 &&
                  (relTarg.id.substring(relTarg.id.length - 4,
                                        relTarg.id.length) ==
                   e.currentTarget.id.substring(e.currentTarget.id.length - 4,
                                                e.currentTarget.id.length)))
                return;
              var $this = jQuery(this);
              $this.children("canvas").animate({opacity: 0});
              $this.children("span").animate({opacity: 0});
              ($this.children("img")
               .css("z-index", 1002)
               .animate({
                 height: "90px",
                 marginTop: "0px",
                 marginLeft: leftBig,
                 borderWidth: "2px",
               }, 80));
            });

            // zoom out effect
            containerTag.mouseout(function(e) {
              if (!e) return;
              var relTarg = e.relatedTarget;
              // no animation if I'm moving on different parts of the same thumbnail
              if (relTarg != null && relTarg.id.length >= 4 &&
                  (relTarg.id.substring(relTarg.id.length - 4,
                                        relTarg.id.length) ==
                   e.currentTarget.id.substring(e.currentTarget.id.length - 4,
                                                e.currentTarget.id.length)))
                return;
              var $this = jQuery(this);
              ($this.children("img")
               .css("z-index", 0)
               .animate({
                 height: "80px",
                 marginTop: "5px",
                 marginLeft: "5px",
                 borderWidth: "0px",
               }, 80));
              $this.children("canvas").animate({opacity: 1});
              $this.children("span").animate({opacity: 1});
            });

            // green background for numbers on thumbnails
            var id = "canvas" + (randomCode + index);
            var canvasEl = pblock.ownerDocument.getElementById(id);
            var canvas =
              $(canvasEl).css({left: col, top: row, position: "absolute"});

            var ctx = canvasEl.getContext("2d");
            ctx.fillStyle = "white";
            ctx.beginPath();
            ctx.lineTo(thisWidth, 0);
            ctx.lineTo(0, 60);
            ctx.fill();

            var radgrad = ctx.createRadialGradient(0, 80, 0, 0, 80, 25);
            radgrad.addColorStop(0, 'rgba(0,230,0,0.8)');
            radgrad.addColorStop(1, 'rgba(0,198,0,0.8)');

            ctx.fillStyle = radgrad;
            ctx.beginPath();
            var x = 0;
            var y = 80;
            var radius = 25;
            var startAngle = 0;
            var endAngle = 2 * Math.PI;
            var anticlockwise = false;
            ctx.arc(x, y, radius, startAngle, endAngle, anticlockwise);
            ctx.fill();

            // white number position
            var codeTag = jQuery("#code" + (randomCode + index),
                                 pblock.ownerDocument);
            codeTag.css("left", col + 5).css("top", row + 62);
            col += thisWidth + 5;

            if (row >= 255) {
              // if image is out of the last line, it hides it and it doesnt' count it
              imgTag.css("display", "none");
              canvas.css("display", "none");
              codeTag.css("display", "none");
            }
            else
              currentResult++;
          }
        }
      });
    }
    refresh(1, this.imgsPerPage);
  }
});

const
MAPS = 'http://maps.google.com/',
MAP_INIT = '!'+ function init([lat, lng, type, zoom]){
  self.maps = google.maps
  self.M = new maps.Map(document.getElementById('map'), {
    center: new maps.LatLng(lat, lng),
    mapTypeId: type || maps.MapTypeId.ROADMAP,
    zoom: zoom || 12,
    scaleControl: true,
  })
  self.onbeforeunload = mapact
  addEventListener('go', function mapdo(e){
    var data = JSON.parse(e.data)
    maptie(document.getElementById('buttons'), mapkey)
    data.q || ([data.q, data.dest] = [data.dest, ''])
    if(data.zoom) M.setZoom(data.zoom)
    if(data.type) M.setMapTypeId(data.type)
    if(!data.q){
      M.panTo(new maps.LatLng(data.lat, data.lon))
      return
    }
    var addrs = document.getElementById('addrs')
      , trips = document.getElementById('trips')
    addrs.innerHTML = 'Searching <b></b> ...'
    trips.innerHTML = ''
    addrs.firstElementChild.textContent = data.q
    var req = {}
    if(data.dest){
      let dr = new maps.DirectionsRenderer()
      dr.setMap(M)
      dr.setPanel(trips)
      ;({q: req.origin, dest: req.destination}) = data
      req.travelMode = maps.DirectionsTravelMode.DRIVING
      req.provideRouteAlternatives = true
      new maps.DirectionsService().route(req, function maproute(res, stat){
        if(stat !== maps.DirectionsStatus.OK) return
        data.steps = res.routes[0].legs[0].steps
        dr.setDirections(res)
      })
      return
    }
    req.address = data.q
    new maps.Geocoder().geocode(req, function mapgeo(rs){
      if(!rs || !rs.length){
        addrs.innerHTML = 'No results for <b></b>'
        addrs.firstElementChild.textContent = data.q
        return
      }
      addrs.innerHTML = ''
      rs.slice(0, 10).forEach(function(r, i){
        let a = document.createElement('a')
        a.href = 'javascript:'
        a.value = i
        a.accessKey = -~i % 10
        a.textContent = r.formatted_address
        a.onclick = mapgo
        addrs.appendChild(a)
      })
      addrs.children[0].onclick()
      function mapgo(e){
        if(e) e.stopPropagation(), this.blur()
        M.panTo(rs[this.value].geometry.location)
        ;(this.parentNode.querySelector('.active') || 0).className = ''
        this.className = 'active'
      }
    })
    function mapkey(e){
      var {body} = document
        , b = e.target
        , k = b.accessKey.toLowerCase()
      e.preventDefault()
      b.blur()
      if(~'hjkl'.indexOf(k)){
        let [x, y] = v.split(',')
        M.panBy(.9 * x * body.clientWidth,
                .9 * y * body.clientHeight)
        return
      }
      if(~'pm'.indexOf(k))
        M.setZoom(M.getZoom() + +(b.value + 1))
      else if(~'yuio'.indexOf(k))
        M.setMapTypeId(maps.MapTypeId[b.value])
      else var u =
        'http://maps.google.com/staticmap?key&sensor=false'+
        '&maptype='+ M.getMapTypeId() +
        '&center='+ M.getCenter().toUrlValue() +
        '&zoom='+ M.getZoom() +
        '&size='+ body.clientWidth +'x'+ body.clientHeight +
        (!('steps' in data) ? '' :
         ['&path='+ s.start_point.toUrlValue() +'|'+ s.end_point.toUrlValue()
          for each(s in data.steps)].join('')) +
        (data.lang && '&language='+ data.lang)
      mapact(k, u)
    }
  }, false)
  function maptie(it, fn){
    'tied' in it || it.addEventListener('click', fn, it.tied = true)
  }
  function mapact(key, url){
    dispatchEvent(new MessageEvent('action', {
      data: url || '',
      origin: '*',
      lastEventId: key || '',
      source: self,
    }))
  }
}
{ let loc = CmdUtils.geoLocation
  var gCoords = {
    lat: loc ? loc.lat : 180 * Math.random() -  90,
    lon: loc ? loc.lon : 360 * Math.random() - 180,
  }
}
CmdUtils.CreateCommand({
  names: ['map', 'Google Maps'],
  description: 'Explores '+ 'Google Maps'.link(MAPS) +'.',
  help: (
    '<b>[ accesskeys ]</b><pre style="line-height:1.5">'+
    ['Y/U/I/O : Roadmap / Satellite / Hybrid / Terrain',
     'H/J/K/L : \u2190 / \u2193 / \u2191 / \u2192',
     'P/M     : + / -',
     'C/V     : Copy / Insert'].join('\n') +
    '</pre>').replace(/\b[A-Z]\b/g, '$&'.bold()),
  icon: 'chrome://ubiquity/skin/icons/google.ico',
  arguments: {
    object: {
      name: 'map-suggest', rankLast: true,
      suggest: function map_suggest(txt, htm, cb, sx){
        if(!txt) return
        var ss = [CmdUtils.makeSugg(txt, htm, 0, .4)]
        if(!sx || sx[1]) ss.push($.ajax({
          url: 'https://maps-api-ssl.google.com/maps/suggest',
          data: {q: txt}, dataType: 'text',
          success: function map_success(js0n){
            cb([{text: q, summary: q, score: .3}
                for each({query: q} in eval('0,'+ js0n).suggestion)])
          },
        }))
        return ss
      },
    },
    goal   : noun_arb_text,
    format : noun_type_lang_google
  },
  execute: function map_execute({
    object: {text: q}, goal: {text: dest}, format: {data: lang}
  }){
    q || (q = dest)
    Utils.openUrlInBrowser(MAPS + (!q ? "" : Utils.paramsToString({
      q : q, hl: lang || 'en'
    })))
  },
  preview: function map_preview(pb, {
    object: {text: q}, goal: {text: dest}, format: {data: lang}
  }){
    var doc = pb.ownerDocument, dat = Bin.mapData() || {}
    if(!doc.getElementById('init')){
      let div = doc.createElement('div'), script = doc.createElement('script')
      div.innerHTML =
        '<style id="init">'+ feed.dom.getElementById("map-css").textContent +
        '</style><div id="buttons">'+ [
          '<input type="button" accesskey="'+ k +'" value="'+ v +'">'
          for([k, v] of new Iterator({
            h: '-1,', j: ',1', k: ',-1', l: '1,', p: '+', m: '-',
            y: 'ROADMAP', u: 'SATELLITE', i: 'HYBRID', o: 'TERRAIN',
            c: '(C)opy', v: 'Insert (V)',
          }))
        ].join('') + '</div>'
      pb.appendChild(div)
      script.type = 'application/javascript;version=1.8'
      script.innerHTML = MAP_INIT +
        '('+ uneval([gCoords.lat, gCoords.lon, dat.type, dat.zoom]) +')'
      pb.appendChild(script)
    }
    var win = doc.defaultView
    win.dispatchEvent(new win.MessageEvent('go', {
      data: JSON.stringify({
        q: q, dest: dest,
        lat: gCoords.lat,
        lon: gCoords.lon,
        lang: lang || 'en',
        type: dat.type,
        zoom: dat.zoom,
      }),
      origin: '*',
      source: win,
    }))
    win.addEventListener('action', this._act, false)
    this._act.me = this
  },
  previewUrl:
    'data:text/html,<head><meta charset=UTF-8>'+
    '<script src='+ MAPS + 'maps/api/js?sensor=false></script></head>'+
    '<div id=map style="width:100%;height:100%"></div>'+
    '<div id=addrs></div><div id=trips></div>',
  _act: function map_act(e){
    var url = e.data
    if(url){
      if(e.lastEventId === 'log') return Utils.reportInfo(url)
      let img = '<img src="'+ Utils.escapeHtml(url) +'">'
      e.lastEventId === 'c'
      ? (Utils.clipboard.set({text: url, html: img}),
         displayMessage(url, map_act.me))
      : CmdUtils.setSelection(img, {text: url})
      return
    }
    let {M} = XPCNativeWrapper.unwrap(this)
    Bin.mapData({type: M.getMapTypeId(), zoom: M.getZoom()})
  },
})

]]></script>
</body>
</html>