summaryrefslogtreecommitdiffstats
path: root/chrome/browser/resources/new_new_tab.js
blob: e9618a98b4239c3721cc88b52c08d88f7a1f45ef (plain)
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
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639

// Helpers

function $(id) {
  return document.getElementById(id);
}

// TODO(arv): Remove these when classList is available in HTML5.
// https://bugs.webkit.org/show_bug.cgi?id=20709
function hasClass(el, name) {
  return el.nodeType == 1 && el.className.split(/\s+/).indexOf(name) != -1;
}

function addClass(el, name) {
  el.className += ' ' + name;
}

function removeClass(el, name) {
  var names = el.className.split(/\s+/);
  el.className = names.filter(function(n) {
    return name != n;
  }).join(' ');
}

function findAncestorByClass(el, className) {
  return findAncestor(el, function(el) {
    return hasClass(el, className);
  });
}

/**
 * Return the first ancestor for which the {@code predicate} returns true.
 * @param {Node} node The node to check.
 * @param {function(Node) : boolean} predicate The function that tests the
 *     nodes.
 * @return {Node} The found ancestor or null if not found.
 */
function findAncestor(node, predicate) {
  var last = false;
  while (node != null && !(last = predicate(node))) {
    node = node.parentNode;
  }
  return last ? node : null;
}

// WebKit does not have Node.prototype.swapNode
// https://bugs.webkit.org/show_bug.cgi?id=26525
function swapDomNodes(a, b) {
  var afterA = a.nextSibling;
  if (afterA == b) {
    swapDomNodes(b, a);
    return;
  }
  var aParent = a.parentNode;
  b.parentNode.replaceChild(a, b);
  aParent.insertBefore(b, afterA);
}

function bind(fn, selfObj, var_args) {
  var boundArgs = Array.prototype.slice.call(arguments, 2);
  return function() {
    var args = Array.prototype.slice.call(arguments);
    args.unshift.apply(args, boundArgs);
    return fn.apply(selfObj, args);
  }
}

var loading = true;
var mostVisitedData = [];
var gotMostVisited = false;
var gotShownSections = false;

function mostVisitedPages(data, firstRun) {
  logEvent('received most visited pages');

  // We append the class name with the "filler" so that we can style fillers
  // differently.
  var maxItems = 8;
  data.length = Math.min(maxItems, data.length);
  var len = data.length;
  for (var i = len; i < maxItems; i++) {
    data[i] = {filler: true};
  }

  mostVisitedData = data;
  renderMostVisited(data);

  gotMostVisited = true;
  onDataLoaded();

  // Only show the first run notification if first run.
  if (firstRun) {
    showFirstRunNotification();
  }
}

var tipCache = {};

function tips(data) {
  logEvent('received tips');
  tipCache = data;
  renderTip();
}

function createTip(data) {
  var parsedTips;
  try {
    parsedTips = parseHtmlSubset(data[0].tip_html_text);
  } catch (parseErr) {
    console.log('Error parsing tips: ' + parseErr.message);
  }
  return parsedTips;
}

function renderTip() {
  var tipElement = $('tip-line');
  // There should always be only one tip.
  tipElement.textContent = '';
  tipElement.appendChild(createTip(tipCache));
}

function recentlyClosedTabs(data) {
  logEvent('received recently closed tabs');
  // We need to store the recent items so we can update the layout on a resize.
  recentItems = data;
  renderRecentlyClosed();
}

var recentItems = [];

function renderRecentlyClosed() {
  // We remove all items but the header and the nav
  var recentlyClosedElement = $('recently-closed');
  var headerEl = recentlyClosedElement.firstElementChild;
  var navEl = recentlyClosedElement.lastElementChild;

  for (var el = navEl.previousElementSibling; el != headerEl;
       el = navEl.previousElementSibling) {
    recentlyClosedElement.removeChild(el);
  }

  // Create new items
  recentItems.forEach(function(item) {
    var el = createRecentItem(item);
    recentlyClosedElement.insertBefore(el, navEl);
  });

  layoutRecentlyClosed();
}

function createRecentItem(data) {
  var isWindow = data.type == 'window';
  var el;
  if (isWindow) {
    el = document.createElement('span');
    el.className = 'item link window';
    el.tabItems = data.tabs;
    el.tabIndex = 0;
    el.textContent = formatTabsText(data.tabs.length);
  } else {
    el = document.createElement('a');
    el.className = 'item';
    el.href = data.url;
    el.style.backgroundImage = url('chrome://favicon/' + data.url);
    el.dir = data.direction;
    el.textContent = data.title;
  }
  el.sessionId = data.sessionId;
  el.xtitle = data.title;
  var wrapperEl = document.createElement('span');
  wrapperEl.appendChild(el);
  return wrapperEl;
}

function onShownSections(mask) {
  logEvent('received shown sections');
  if (mask != shownSections) {
    var oldShownSections = shownSections;
    shownSections = mask;

    // Only invalidate most visited if needed.
    if ((mask & Section.THUMB) != (oldShownSections & Section.THUMB) ||
        (mask & Section.LIST) != (oldShownSections & Section.LIST)) {
      mostVisited.invalidate();
    }

    mostVisited.updateDisplayMode();
    layoutRecentlyClosed();
    updateOptionMenu();
  }

  gotShownSections = true;
  onDataLoaded();
}

function saveShownSections() {
  chrome.send('setShownSections', [String(shownSections)]);
}

function processData(selector, data) {
  var output = document.querySelector(selector);

  // Wait until ready
  if (typeof JsEvalContext !== 'function' || !output) {
    logEvent('JsEvalContext is not yet available, ' + selector);
    document.addEventListener('DOMContentLoaded', function() {
      processData(selector, data);
    });
  } else {
    var d0 = Date.now();
    var input = new JsEvalContext(data);
    jstProcess(input, output);
    logEvent('processData: ' + selector + ', ' + (Date.now() - d0));
  }
}

function getThumbnailClassName(data) {
  return 'thumbnail-container' +
      (data.pinned ? ' pinned' : '') +
      (data.filler ? ' filler' : '');
}

function url(s) {
  return 'url("' + encodeURI(s) + '")';
}

function renderMostVisited(data) {
  var parent = $('most-visited');
  var children = parent.children;
  for (var i = 0; i < data.length; i++) {
    var d = data[i];
    var t = children[i];

    // If we have a filler continue
    var oldClassName = t.className;
    var newClassName = getThumbnailClassName(d);
    if (oldClassName != newClassName) {
      t.className = newClassName;
    }

    // No need to continue if this is a filler.
    if (newClassName == 'thumbnail-container filler') {
      continue;
    }

    t.href = d.url;
    t.querySelector('.pin').title = localStrings.getString(d.pinned ?
        'unpinthumbnailtooltip' : 'pinthumbnailtooltip');
    t.querySelector('.remove').title =
        localStrings.getString('removethumbnailtooltip');

    // There was some concern that a malformed malicious URL could cause an XSS
    // attack but setting style.backgroundImage = 'url(javascript:...)' does
    // not execute the JavaScript in WebKit.

    var thumbnailUrl = d.thumbnailUrl || 'chrome://thumb/' + d.url;
    t.querySelector('.thumbnail-wrapper').style.backgroundImage =
        url(thumbnailUrl);
    var titleDiv = t.querySelector('.title > div');
    titleDiv.xtitle = titleDiv.textContent = d.title;
    var faviconUrl = d.faviconUrl || 'chrome://favicon/' + d.url;
    titleDiv.style.backgroundImage = url(faviconUrl);
    titleDiv.dir = d.direction;
  }
}

/**
 * Calls chrome.send with a callback and restores the original afterwards.
 */
function chromeSend(name, params, callbackName, callback) {
  var old = global[callbackName];
  global[callbackName] = function() {
    // restore
    global[callbackName] = old;

    var args = Array.prototype.slice.call(arguments);
    return callback.apply(global, args);
  };
  chrome.send(name, params);
}

function useSmallGrid() {
  return window.innerWidth <= 920;
}

var LayoutMode = {
  SMALL: 1,
  NORMAL: 2
};

var layoutMode = useSmallGrid() ? LayoutMode.SMALL : LayoutMode.NORMAL;

function handleWindowResize() {
  if (window.innerWidth < 10) {
    // We're probably a background tab, so don't do anything.
    return;
  }

  var oldLayoutMode = layoutMode;
  layoutMode = useSmallGrid() ? LayoutMode.SMALL : LayoutMode.NORMAL

  if (layoutMode != oldLayoutMode){
    mostVisited.invalidate();
    mostVisited.layout();
    layoutRecentlyClosed();
  }
}

/**
 * Bitmask for the different UI sections.
 * This matches the Section enum in ../dom_ui/shown_sections_handler.h
 * @enum {number}
 */
var Section = {
  THUMB: 1,
  LIST: 2,
  RECENT: 4
};

var shownSections = Section.THUMB | Section.RECENT;

function showSection(section) {
  if (!(section & shownSections)) {
    shownSections |= section;

    // THUMBS and LIST are mutually exclusive.
    if (section == Section.THUMB) {
      // hide LIST
      shownSections &= ~Section.LIST;
      mostVisited.invalidate();
    } else if (section == Section.LIST) {
      // hide THUMB
      shownSections &= ~Section.THUMB;
      mostVisited.invalidate();
    } else {
      layoutRecentlyClosed();
    }

    updateOptionMenu();
    mostVisited.updateDisplayMode();
    mostVisited.layout();
  }
}

function hideSection(section) {
  if (section & shownSections) {
    shownSections &= ~section;

    if (section & Section.THUMB || section & Section.LIST) {
      mostVisited.invalidate();
    }

    if (section & Section.RECENT) {
      layoutRecentlyClosed();
    }

    updateOptionMenu();
    mostVisited.updateDisplayMode();
    mostVisited.layout();
  }
}

var mostVisited = {
  getItem: function(el) {
    return findAncestorByClass(el, 'thumbnail-container');
  },

  getHref: function(el) {
    return el.href;
  },

  togglePinned: function(el) {
    var index = this.getThumbnailIndex(el);
    var data = mostVisitedData[index];
    data.pinned = !data.pinned;
    if (data.pinned) {
      chrome.send('addPinnedURL', [data.url, data.title, String(index)]);
    } else {
      chrome.send('removePinnedURL', [data.url]);
    }
    this.updatePinnedDom_(el, data.pinned);
  },

  updatePinnedDom_: function(el, pinned) {
    el.querySelector('.pin').title = localStrings.getString(pinned ?
        'unpinthumbnailtooltip' : 'pinthumbnailtooltip');
    if (pinned) {
      addClass(el, 'pinned');
    } else {
      removeClass(el, 'pinned');
    }
  },

  getThumbnailIndex: function(el) {
    var nodes = el.parentNode.querySelectorAll('.thumbnail-container');
    return Array.prototype.indexOf.call(nodes, el);
  },

  swapPosition: function(source, destination) {
    var nodes = source.parentNode.querySelectorAll('.thumbnail-container');
    var sourceIndex = this.getThumbnailIndex(source);
    var destinationIndex = this.getThumbnailIndex(destination);
    swapDomNodes(source, destination);

    var sourceData = mostVisitedData[sourceIndex];
    chrome.send('addPinnedURL', [sourceData.url, sourceData.title,
                                 String(destinationIndex)]);
    sourceData.pinned = true;
    this.updatePinnedDom_(source, true);

    var destinationData = mostVisitedData[destinationIndex];
    // Only update the destination if it was pinned before.
    if (destinationData.pinned) {
      chrome.send('addPinnedURL', [destinationData.url, destinationData.title,
                                   String(sourceIndex)]);
    }
    mostVisitedData[destinationIndex] = sourceData;
    mostVisitedData[sourceIndex] = destinationData;
  },

  blacklist: function(el) {
    var self = this;
    var url = this.getHref(el);
    chrome.send('blacklistURLFromMostVisited', [url]);

    addClass(el, 'hide');

    // Find the old item.
    var oldUrls = {};
    var oldIndex = -1;
    var oldItem;
    for (var i = 0; i < mostVisitedData.length; i++) {
      if (mostVisitedData[i].url == url) {
        oldItem = mostVisitedData[i];
        oldIndex = i;
      }
      oldUrls[mostVisitedData[i].url] = true;
    }

    // Send 'getMostVisitedPages' with a callback since we want to find the new
    // page and add that in the place of the removed page.
    chromeSend('getMostVisited', [], 'mostVisitedPages', function(data) {
      // Find new item.
      var newItem;
      for (var i = 0; i < data.length; i++) {
        if (!(data[i].url in oldUrls)) {
          newItem = data[i];
          break;
        }
      }

      if (!newItem) {
        // If no other page is available to replace the blacklisted item,
        // we need to reorder items s.t. all filler items are in the rightmost
        // indices.
        mostVisitedPages(data);

      // Replace old item with new item in the mostVisitedData array.
      } else if (oldIndex != -1) {
        mostVisitedData.splice(oldIndex, 1, newItem);
        mostVisitedPages(mostVisitedData);
        addClass(el, 'fade-in');
      }

      // We wrap the title in a <span class=blacklisted-title>. We pass an empty
      // string to the notifier function and use DOM to insert the real string.
      var actionText = localStrings.getString('undothumbnailremove');

      // Show notification and add undo callback function.
      var wasPinned = oldItem.pinned;
      showNotification('', actionText, function() {
        self.removeFromBlackList(url);
        if (wasPinned) {
          chromeSend('addPinnedURL', [url, oldItem.title, String(oldIndex)]);
        }
        chrome.send('getMostVisited');
      });

      // Now change the DOM.
      var textPattern = localStrings.getString('thumbnailremovednotification');
      var parts = textPattern.split('%s');
      var titleSpan = document.createElement('span');
      titleSpan.className = 'blacklist-title';
      titleSpan.textContent = oldItem.title;
      var notifySpan = document.querySelector('#notification > span');
      notifySpan.appendChild(document.createTextNode(parts[0]));
      notifySpan.appendChild(titleSpan);
      notifySpan.appendChild(document.createTextNode(parts[1]));
    });
  },

  removeFromBlackList: function(url) {
    chrome.send('removeURLsFromMostVisitedBlacklist', [url]);
  },

  clearAllBlacklisted: function() {
    chrome.send('clearMostVisitedURLsBlacklist', []);
  },

  updateDisplayMode: function() {
    if (!this.dirty_) {
      return;
    }

    var thumbCheckbox = $('thumb-checkbox');
    var listCheckbox = $('list-checkbox');
    var mostVisitedElement = $('most-visited');

    if (shownSections & Section.THUMB) {
      thumbCheckbox.checked = true;
      listCheckbox.checked = false;
      removeClass(mostVisitedElement, 'list');
    } else if (shownSections & Section.LIST) {
      thumbCheckbox.checked = false;
      listCheckbox.checked = true;
      addClass(mostVisitedElement, 'list');
    } else {
      thumbCheckbox.checked = false;
      listCheckbox.checked = false;
    }
  },

  dirty_: false,

  invalidate: function() {
    this.dirty_ = true;
    this.calculationsDirty_ = true;
  },

  layout: function() {
    if (!this.dirty_) {
      return;
    }
    var d0 = Date.now();

    this.calculateLayout_();

    var mostVisitedElement = $('most-visited');
    var thumbnails = mostVisitedElement.children;

    if (shownSections & Section.LIST) {
      addClass(mostVisitedElement, 'list');
    } else if (shownSections & Section.THUMB) {
      removeClass(mostVisitedElement, 'list');
    }

    var cache = this.layoutCache_;
    mostVisitedElement.style.height = cache.sumHeight + 'px';
    mostVisitedElement.style.opacity = cache.opacity;
    // We set overflow to hidden so that the most visited element does not
    // "leak" when we hide and show it.
    if (!cache.opacity) {
      mostVisitedElement.style.overflow = 'hidden';
    }

    if (shownSections & Section.THUMB || shownSections & Section.LIST) {
      for (var i = 0; i < thumbnails.length; i++) {
        var t = thumbnails[i];

        // Remove temporary ID that was used during startup layout.
        t.id = '';

        var rect = cache.rects[i];
        t.style.left = rect.left + 'px';
        t.style.top = rect.top + 'px';
        t.style.width = rect.width != undefined ? rect.width + 'px' : '';
        var innerStyle = t.firstElementChild.style;
        innerStyle.left = innerStyle.top = '';
      }
    }

    afterTransition(function() {
      // Only set overflow to visible if the element is shown.
      if (cache.opacity) {
        mostVisitedElement.style.overflow = '';
      }
    });

    this.dirty_ = false;

    logEvent('mostVisited.layout: ' + (Date.now() - d0));
  },

  layoutCache_: {},
  calculationsDirty_: true,

  /**
   * Calculates and caches the layout positions for the thumbnails.
   */
  calculateLayout_: function() {
    if (!this.calculationsDirty_) {
      return;
    }

    var small = useSmallGrid();

    var cols = 4;
    var rows = 2;
    var marginWidth = 10;
    var marginHeight = 7;
    var borderWidth = 4;
    var thumbWidth = small ? 150 : 207;
    var thumbHeight = small ? 93 : 129;
    var w = thumbWidth + 2 * borderWidth + 2 * marginWidth;
    var h = thumbHeight + 40 + 2 * marginHeight;
    var sumWidth = cols * w  - 2 * marginWidth;
    var sumHeight = rows * h;
    var opacity = 1;
    // Since the list mode does not have a toolbar move it down a little to add
    // some spacing at the top.
    var LIST_TOP_SPACING = 22;

    if (shownSections & Section.LIST) {
      w = sumWidth;
      h = 34;
      rows = 8;
      cols = 1;
      sumHeight = rows * h + LIST_TOP_SPACING;
    } else if (!(shownSections & Section.THUMB)) {
      sumHeight = 0;
      opacity = 0;
    }

    var rtl = document.documentElement.dir == 'rtl';
    var rects = [];

    if (shownSections & Section.THUMB || shownSections & Section.LIST) {
      for (var i = 0; i < rows * cols; i++) {
        var row, col, left, top, width;
        if (shownSections & Section.THUMB) {
          row = Math.floor(i / cols);
          col = i % cols;
        } else {
          col = Math.floor(i / rows);
          row = i % rows;
        }

        if (shownSections & Section.THUMB) {
          left = rtl ? sumWidth - col * w - thumbWidth - 2 * borderWidth :
              col * w;
        } else {
          left = rtl ? sumWidth - col * w - w + 2 * marginWidth : col * w;
        }
        top = row * h;

        if (shownSections & Section.LIST) {
          width = w;
          top += LIST_TOP_SPACING;
        }

        rects[i] = {left: left, top: top, width: width};
      }
    }

    this.layoutCache_ = {
      opacity: opacity,
      sumHeight: sumHeight,
      rects: rects
    }

    this.calculationsDirty_ = false;
  },

  getRectByIndex: function(index) {
    this.calculateLayout_();
    return this.layoutCache_.rects[index]
  }
};

// Recently closed

function layoutRecentlyClosed() {
  var recentElement = $('recently-closed');
  var recentShown = shownSections & Section.RECENT;
  var style = recentElement.style;

  if (!recentShown) {
    style.opacity = style.height = 0;
  } else {
    style.opacity = style.height = '';

    // Show all items.
    for (var i = 0, child; child = recentElement.children[i]; i++) {
      child.style.display = '';
    }

    // We cannot use clientWidth here since the width has a transition.
    var spacing = 20;
    var headerEl = recentElement.firstElementChild;
    var navEl = recentElement.lastElementChild;
    var navWidth = navEl.offsetWidth;
    // Subtract 10 for the padding
    var availWidth = (useSmallGrid() ? 690 : 918) - navWidth - 10;

    // Now go backwards and hide as many elements as needed.
    var elementsToHide = [];
    for (var el = navEl.previousElementSibling; el != headerEl;
         el = el.previousElementSibling) {
      if (el.offsetLeft + el.offsetWidth + spacing > availWidth) {
        elementsToHide.push(el);
      }
    }

    elementsToHide.forEach(function(el) {
      el.style.display = 'none';
    });
  }
}

/**
 * This function is called by the backend whenever the sync status section
 * needs to be updated to reflect recent sync state changes. The backend passes
 * the new status information in the newMessage parameter. The state includes
 * the following:
 *
 * syncsectionisvisible: true if the sync section needs to show up on the new
 *                       tab page and false otherwise.
 * msgtype: represents the states - "error", "presynced" or "synced".
 * title: the header for the sync status section.
 * msg: the actual message (e.g. "Synced to foo@gmail.com").
 * linkisvisible: true if the link element should be visible within the sync
 *                section and false otherwise.
 * linktext: the text to display as the link in the sync status (only used if
 *           linkisvisible is true).
 * linkurlisset: true if an URL should be set as the href for the link and false
 *               otherwise. If this field is false, then clicking on the link
 *               will result in sending a message to the backend (see
 *               'SyncLinkClicked').
 * linkurl: the URL to use as the element's href (only used if linkurlisset is
 *          true).
 */
function syncMessageChanged(newMessage) {
  var syncStatusElement = $('sync-status');
  var style = syncStatusElement.style;

  // Hide the section if the message is emtpy.
  if (!newMessage.syncsectionisvisible) {
    style.opacity = style.height = 0;
    return;
  }
  style.height = '';
  style.opacity = 1;

  // Set the sync section background color based on the state.
  if (newMessage.msgtype == "error") {
    style.backgroundColor = "tomato";
  } else if (newMessage.msgtype == "presynced") {
    style.backgroundColor = "greenyellow";
  } else {
    style.backgroundColor = "#CAFF70";
  }

  // Set the text for the header and sync message.
  var titleElement = syncStatusElement.firstElementChild;
  titleElement.textContent = newMessage.title;
  var messageElement = titleElement.nextElementSibling;
  messageElement.textContent = newMessage.msg;

  // Set up the link if we should show one or hide it otherwise.
  var linkContainer = messageElement.nextElementSibling;
  var containerStyle = linkContainer.style;
  var linkElement = linkContainer.firstElementChild;
  linkElement.removeEventListener('click', syncSectionLinkClicked);

  // TODO(idana): when we don't have an URL to set, using an href is not a good
  // idea because the user will still be able to right click on the link and
  // open the empty href in a new tab/window.
  //
  // See http://code.google.com/p/chromium/issues/detail?id=19538 for more info
  // about how to fix this.
  linkElement.href = '';
  containerStyle.display = 'none';
  if (newMessage.linkisvisible) {
    containerStyle.display = '';
    linkElement.textContent = newMessage.linktext;
    // We don't listen to click events if the backend specified a target URL
    // for the link.
    if (newMessage.linkurlisset) {
      linkElement.href = newMessage.linkurl;
    } else {
      linkElement.addEventListener('click', syncSectionLinkClicked);
    }
  }
}

/**
 * Invoked when the link in the sync status section is clicked.
 */
function syncSectionLinkClicked(e) {
  chrome.send('SyncLinkClicked');
  e.preventDefault();
}

/**
 * Returns the text used for a recently closed window.
 * @param {number} numTabs Number of tabs in the window.
 * @return {string} The text to use.
 */
function formatTabsText(numTabs) {
  if (numTabs == 1)
    return localStrings.getString('closedwindowsingle');
  return localStrings.formatString('closedwindowmultiple', numTabs);
}

/**
 * We need both most visited and the shown sections to be considered loaded.
 * @return {boolean}
 */
function onDataLoaded() {
  if (gotMostVisited && gotShownSections) {
    mostVisited.layout();
    loading = false;
    // Remove class name in a timeout so that changes done in this JS thread are
    // not animated.
    window.setTimeout(function() {
      removeClass(document.body, 'loading');
    }, 1);
  }
}

// Theme related

function themeChanged() {
  $('themecss').href = 'chrome://theme/css/newtab.css?' + Date.now();
  updateAttribution();
}

function updateAttribution() {
  $('attribution-img').src = 'chrome://theme/theme_ntp_attribution?' +
      Date.now();
}

function bookmarkBarAttached() {
  document.documentElement.setAttribute("bookmarkbarattached", "true");
}

function bookmarkBarDetached() {
  document.documentElement.setAttribute("bookmarkbarattached", "false");
}

function viewLog() {
  var lines = [];
  var start = log[0][1];

  for (var i = 0; i < log.length; i++) {
    lines.push((log[i][1] - start) + ': ' + log[i][0]);
  }

  console.log(lines.join('\n'));
}

// Updates the visibility of the menu items.
function updateOptionMenu() {
  var menuItems = $('option-menu').children;
  for (var i = 0; i < menuItems.length; i++) {
    var item = menuItems[i];
    var command = item.getAttribute('command');
    if (command == 'show' || command == 'hide') {
      var section = Section[item.getAttribute('section')];
      var visible;
      if (section == Section.THUMB || section == Section.LIST) {
        visible = shownSections & Section.THUMB || shownSections & Section.LIST;
        // If visible we need to make sure we are hiding the visible section.
        if (visible) {
          item.setAttribute('section',
                            shownSections & Section.THUMB ? 'THUMB' : 'LIST');
        }
      } else {
        visible = shownSections & section;
      }
      item.setAttribute('command', visible ? 'hide' : 'show');
    }
  }
}

// We apply the size class here so that we don't trigger layout animations
// onload.

handleWindowResize();

var localStrings = new LocalStrings();

///////////////////////////////////////////////////////////////////////////////
// Things we know are not needed at startup go below here

function afterTransition(f) {
  if (loading) {
    // Make sure we do not use a timer during load since it slows down the UI.
    f();
  } else {
    // The duration of all transitions are 500ms
    window.setTimeout(f, 500);
  }
}

// Notification


var notificationTimeout;

function showNotification(text, actionText, opt_f, opt_delay) {
  var notificationElement = $('notification');
  var f = opt_f || function() {};
  var delay = opt_delay || 10000;

  function show() {
    window.clearTimeout(notificationTimeout);
    addClass(notificationElement, 'show');
  }

  function delayedHide() {
    notificationTimeout = window.setTimeout(hideNotification, delay);
  }

  function doAction() {
    f();
    hideNotification();
  }

  // Remove any possible first-run trails.
  removeClass(notification, 'first-run');

  var actionLink = notificationElement.querySelector('.link');
  notificationElement.firstElementChild.textContent = text;
  actionLink.textContent = actionText;

  actionLink.onclick = doAction;
  actionLink.onkeydown = handleIfEnterKey(doAction);
  notificationElement.onmouseover = show;
  notificationElement.onmouseout = delayedHide;
  actionLink.onfocus = show;
  actionLink.onblur = delayedHide;

  show();
  delayedHide();
}

function hideNotification() {
  var notificationElement = $('notification');
  removeClass(notificationElement, 'show');
}

function showFirstRunNotification() {
  showNotification(localStrings.getString('firstrunnotification'),
                   localStrings.getString('closefirstrunnotification'),
                   null, 30000);
  var notificationElement = $('notification');
  addClass(notification, 'first-run');
}


/**
 * This handles the option menu.
 * @param {Element} button The button element.
 * @param {Element} menu The menu element.
 * @constructor
 */
function OptionMenu(button, menu) {
  this.button = button;
  this.menu = menu;
  this.button.onmousedown = bind(this.handleMouseDown, this);
  this.button.onkeydown = bind(this.handleKeyDown, this);
  this.boundHideMenu_ = bind(this.hide, this);
  this.boundMaybeHide_ = bind(this.maybeHide_, this);
  this.menu.onmouseover = bind(this.handleMouseOver, this);
  this.menu.onmouseout = bind(this.handleMouseOut, this);
  this.menu.onmouseup = bind(this.handleMouseUp, this);
}

OptionMenu.prototype = {
  show: function() {
    this.menu.style.display = 'block';
    this.button.focus();

    // Listen to document and window events so that we hide the menu when the
    // user clicks outside the menu or tabs away or the whole window is blurred.
    document.addEventListener('focus', this.boundMaybeHide_, true);
    document.addEventListener('mousedown', this.boundMaybeHide_, true);
  },

  hide: function() {
    this.menu.style.display = 'none';
    this.setSelectedIndex(-1);

    document.removeEventListener('focus', this.boundMaybeHide_, true);
    document.removeEventListener('mousedown', this.boundMaybeHide_, true);
  },

  isShown: function() {
    return this.menu.style.display == 'block';
  },

  /**
   * Callback for document mousedown and focus. It checks if the user tried to
   * navigate to a different element on the page and if so hides the menu.
   * @param {Event} e The mouse or focus event.
   * @private
   */
  maybeHide_: function(e) {
    if (!this.menu.contains(e.target) && !this.button.contains(e.target)) {
      this.hide();
    }
  },

  handleMouseDown: function(e) {
    if (this.isShown()) {
      this.hide();
    } else {
      this.show();
    }
  },

  handleMouseOver: function(e) {
    var el = e.target;
    if (!el.hasAttribute('command')) {
      this.setSelectedIndex(-1);
    } else {
      var index = Array.prototype.indexOf.call(this.menu.children, el);
      this.setSelectedIndex(index);
    }
  },

  handleMouseOut: function(e) {
    this.setSelectedIndex(-1);
  },

  handleMouseUp: function(e) {
    var item = this.getSelectedItem();
    if (item) {
      this.executeItem(item);
    }
  },

  handleKeyDown: function(e) {
    var item = this.getSelectedItem();

    var self = this;
    function selectNextVisible(m) {
      var children = self.menu.children;
      var len = children.length;
      var i = self.selectedIndex_;
      if (i == -1 && m == -1) {
        // Edge case when we need to go the last item fisrt.
        i = 0;
      }
      while (true) {
        i = (i + m + len) % len;
        item = children[i];
        if (item && item.hasAttribute('command') &&
            item.style.display != 'none') {
          break;
        }
      }
      if (item) {
        self.setSelectedIndex(i);
      }
    }

    switch (e.keyIdentifier) {
      case 'Down':
        if (!this.isShown()) {
          this.show();
        }
        selectNextVisible(1);
        e.preventDefault();
        break;
      case 'Up':
        if (!this.isShown()) {
          this.show();
        }
        selectNextVisible(-1);
        e.preventDefault();
        break;
      case 'Esc':
      case 'U+001B': // Maybe this is remote desktop playing a prank?
        this.hide();
        break;
      case 'Enter':
      case 'U+0020': // Space
        if (this.isShown()) {
          if (item) {
            this.executeItem(item);
          } else {
            this.hide();
          }
        } else {
          this.show();
        }
        e.preventDefault();
        break;
    }
  },

  selectedIndex_: -1,
  setSelectedIndex: function(i) {
    if (i != this.selectedIndex_) {
      var items = this.menu.children;
      var oldItem = items[this.selectedIndex_];
      if (oldItem) {
        oldItem.removeAttribute('selected');
      }
      var newItem = items[i];
      if (newItem) {
        newItem.setAttribute('selected', 'selected');
      }
      this.selectedIndex_ = i;
    }
  },

  getSelectedItem: function() {
    return this.menu.children[this.selectedIndex_] || null;
  },

  executeItem: function(item) {
    var command = item.getAttribute('command');
    if (command in this.commands) {
      this.commands[command].call(this, item);
    }

    this.hide();
  }
};

var optionMenu = new OptionMenu($('option-button'), $('option-menu'));
optionMenu.commands = {
  'clear-all-blacklisted' : function() {
    mostVisited.clearAllBlacklisted();
    chrome.send('getMostVisited');
  },
  'show': function(item) {
    var section = Section[item.getAttribute('section')];
    showSection(section);
    saveShownSections();
  },
  'hide': function(item) {
    var section = Section[item.getAttribute('section')];
    hideSection(section);
    saveShownSections();
  }
};

$('most-visited').addEventListener('click', function(e) {
  var target = e.target;
  if (hasClass(target, 'pin')) {
    mostVisited.togglePinned(mostVisited.getItem(target));
    e.preventDefault();
  } else if (hasClass(target, 'remove')) {
    mostVisited.blacklist(mostVisited.getItem(target));
    e.preventDefault();
  }
});

function handleIfEnterKey(f) {
  return function(e) {
    if (e.keyIdentifier == 'Enter') {
      f(e);
    }
  };
}

function maybeOpenFile(e) {
  var el = findAncestor(e.target, function(el) {
    return el.fileId !== undefined;
  });
  if (el) {
    chrome.send('openFile', [String(el.fileId)]);
    e.preventDefault();
  }
}

function maybeReopenTab(e) {
  var el = findAncestor(e.target, function(el) {
    return el.sessionId !== undefined;
  });
  if (el) {
    chrome.send('reopenTab', [String(el.sessionId)]);
    e.preventDefault();
  }
}

function maybeShowWindowTooltip(e) {
  var f = function(el) {
    return el.tabItems !== undefined;
  };
  var el = findAncestor(e.target, f);
  var relatedEl = findAncestor(e.relatedTarget, f);
  if (el && el != relatedEl) {
    windowTooltip.handleMouseOver(e, el, el.tabItems);
  }
}


var recentlyClosedElement = $('recently-closed');
recentlyClosedElement.addEventListener('click', maybeOpenFile);
recentlyClosedElement.addEventListener('keydown',
                                       handleIfEnterKey(maybeOpenFile));

recentlyClosedElement.addEventListener('click', maybeReopenTab);
recentlyClosedElement.addEventListener('keydown',
                                       handleIfEnterKey(maybeReopenTab));

recentlyClosedElement.addEventListener('mouseover', maybeShowWindowTooltip);
recentlyClosedElement.addEventListener('focus', maybeShowWindowTooltip, true);

/**
 * This object represents a tooltip representing a closed window. It is
 * shown when hovering over a closed window item or when the item is focused. It
 * gets hidden when blurred or when mousing out of the menu or the item.
 * @param {Element} tooltipEl The element to use as the tooltip.
 * @constructor
 */
function WindowTooltip(tooltipEl) {
  this.tooltipEl = tooltipEl;
  this.boundHide_ = bind(this.hide, this);
  this.boundHandleMouseOut_ = bind(this.handleMouseOut, this);
}

WindowTooltip.trackMouseMove_ = function(e) {
  WindowTooltip.clientX = e.clientX;
  WindowTooltip.clientY = e.clientY;
};

WindowTooltip.prototype = {
  timer: 0,
  handleMouseOver: function(e, linkEl, tabs) {
    this.linkEl_ = linkEl;
    if (e.type == 'mouseover') {
      this.linkEl_.addEventListener('mousemove', WindowTooltip.trackMouseMove_);
      this.linkEl_.addEventListener('mouseout', this.boundHandleMouseOut_);
    } else { // focus
      this.linkEl_.addEventListener('blur', this.boundHide_);
    }
    this.timer = window.setTimeout(bind(this.show, this, e.type, linkEl, tabs),
                                   300);
  },
  show: function(type, linkEl, tabs) {
    window.addEventListener('blur', this.boundHide_);
    this.linkEl_.removeEventListener('mousemove',
                                     WindowTooltip.trackMouseMove_);
    clearTimeout(this.timer);

    processData('#window-tooltip', tabs);
    var rect = linkEl.getBoundingClientRect();
    var bodyRect = document.body.getBoundingClientRect();
    var rtl = document.documentElement.dir == 'rtl';

    this.tooltipEl.style.display = 'block';
    var tooltipRect = this.tooltipEl.getBoundingClientRect();
    var x, y;

    // When focused show below, like a drop down menu.
    if (type == 'focus') {
      x = rtl ?
          rect.left + bodyRect.left + rect.width - this.tooltipEl.offsetWidth :
          rect.left + bodyRect.left;
      y = rect.top + bodyRect.top + rect.height;
    } else {
      x = bodyRect.left + (rtl ?
          WindowTooltip.clientX - this.tooltipEl.offsetWidth :
          WindowTooltip.clientX);
      // Offset like a tooltip
      y = 20 + WindowTooltip.clientY + bodyRect.top;
    }

    // We need to ensure that the tooltip is inside the window viewport.
    x = Math.min(x, bodyRect.width - tooltipRect.width);
    x = Math.max(x, 0);
    y = Math.min(y, bodyRect.height - tooltipRect.height);
    y = Math.max(y, 0);

    this.tooltipEl.style.left = x + 'px';
    this.tooltipEl.style.top = y + 'px';
  },
  handleMouseOut: function(e) {
    // Don't hide when move to another item in the link.
    var f = function(el) {
      return el.tabItems !== undefined;
    };
    var el = findAncestor(e.target, f);
    var relatedEl = findAncestor(e.relatedTarget, f);
    if (el && el != relatedEl) {
      this.hide();
    }
  },
  hide: function() {
    window.clearTimeout(this.timer);
    window.removeEventListener('blur', this.boundHide_);
    this.linkEl_.removeEventListener('mousemove',
                                     WindowTooltip.trackMouseMove_);
    this.linkEl_.removeEventListener('mouseout', this.boundHandleMouseOut_);
    this.linkEl_.removeEventListener('blur', this.boundHide_);
    this.linkEl_ = null;

    this.tooltipEl.style.display  = 'none';
  }
};

var windowTooltip = new WindowTooltip($('window-tooltip'));

function getCheckboxHandler(section) {
  return function(e) {
    if (e.type == 'keydown') {
      if (e.keyIdentifier == 'Enter') {
        e.target.checked = !e.target.checked;
      } else {
        return;
      }
    }
    if (e.target.checked) {
      showSection(section);
    } else {
      hideSection(section);
    }
    saveShownSections();
  }
}

$('thumb-checkbox').addEventListener('change',
                                     getCheckboxHandler(Section.THUMB));
$('thumb-checkbox').addEventListener('keydown',
                                     getCheckboxHandler(Section.THUMB));
$('list-checkbox').addEventListener('change',
                                    getCheckboxHandler(Section.LIST));
$('list-checkbox').addEventListener('keydown',
                                    getCheckboxHandler(Section.LIST));

window.addEventListener('load', bind(logEvent, global, 'onload fired'));
window.addEventListener('load', onDataLoaded);
window.addEventListener('resize', handleWindowResize);
document.addEventListener('DOMContentLoaded', bind(logEvent, global,
                                                   'domcontentloaded fired'));

// Whether or not we should send the initial 'GetSyncMessage' to the backend
// depends on the value of the attribue 'syncispresent' which the backend sets
// to indicate if there is code in the backend which is capable of processing
// this message. This attribute is loaded by the JSTemplate and therefore we
// must make sure we check the attribute after the DOM is loaded.
document.addEventListener('DOMContentLoaded',
                          callGetSyncMessageIfSyncIsPresent);

/**
 * The sync code is not yet built by default on all platforms so we have to
 * make sure we don't send the initial sync message to the backend unless the
 * backend told us that the sync code is present.
 */
function callGetSyncMessageIfSyncIsPresent() {
  if (document.documentElement.getAttribute("syncispresent") == "true") {
    chrome.send('GetSyncMessage');
  }
}

function hideAllMenus() {
  optionMenu.hide();
}

window.addEventListener('blur', hideAllMenus);
window.addEventListener('keydown', function(e) {
  if (e.keyIdentifier == 'Alt' || e.keyIdentifier == 'Meta') {
    hideAllMenus();
  }
}, true);

// Tooltip for elements that have text that overflows.
document.addEventListener('mouseover', function(e) {
  // We don't want to do this while we are dragging because it makes things very
  // janky
  if (dnd.dragItem) {
    return;
  }

  var el = findAncestor(e.target, function(el) {
    return el.xtitle;
  });
  if (el && el.xtitle != el.title) {
    if (el.scrollWidth > el.clientWidth) {
      el.title = el.xtitle;
    } else {
      el.title = '';
    }
  }
});

// DnD

var dnd = {
  currentOverItem_: null,
  get currentOverItem() {
    return this.currentOverItem_;
  },
  set currentOverItem(item) {
    var style;
    if (item != this.currentOverItem_) {
      if (this.currentOverItem_) {
        style = this.currentOverItem_.firstElementChild.style;
        style.left = style.top = '';
      }
      this.currentOverItem_ = item;

      if (item) {
        // Make the drag over item move 15px towards the source. The movement is
        // done by only moving the edit-mode-border (as in the mocks) and it is
        // done with relative positioning so that the movement does not change
        // the drop target.
        var dragIndex = mostVisited.getThumbnailIndex(this.dragItem);
        var overIndex = mostVisited.getThumbnailIndex(item);
        if (dragIndex == -1 || overIndex == -1) {
          return;
        }

        var dragRect = mostVisited.getRectByIndex(dragIndex);
        var overRect = mostVisited.getRectByIndex(overIndex);

        var x = dragRect.left - overRect.left;
        var y = dragRect.top - overRect.top;
        var z = Math.sqrt(x * x + y * y);
        var z2 = 15;
        var x2 = x * z2 / z;
        var y2 = y * z2 / z;

        style = this.currentOverItem_.firstElementChild.style;
        style.left = x2 + 'px';
        style.top = y2 + 'px';
      }
    }
  },
  dragItem: null,
  startX: 0,
  startY: 0,
  startScreenX: 0,
  startScreenY: 0,
  dragEndTimer: null,

  handleDragStart: function(e) {
    var thumbnail = mostVisited.getItem(e.target);
    if (thumbnail) {
      // Don't set data since HTML5 does not allow setting the name for
      // url-list. Instead, we just rely on the dragging of link behavior.
      this.dragItem = thumbnail;
      addClass(this.dragItem, 'dragging');
      this.dragItem.style.zIndex = 2;
    }
  },

  handleDragEnter: function(e) {
    if (this.canDropOnElement(this.currentOverItem)) {
      e.preventDefault();
    }
  },

  handleDragOver: function(e) {
    var item = mostVisited.getItem(e.target);
    this.currentOverItem = item;
    if (this.canDropOnElement(item)) {
      e.preventDefault();
    }
  },

  handleDragLeave: function(e) {
    var item = mostVisited.getItem(e.target);
    if (item) {
      e.preventDefault();
    }

    this.currentOverItem = null;
  },

  handleDrop: function(e) {
    var dropTarget = mostVisited.getItem(e.target);
    if (this.canDropOnElement(dropTarget)) {
      dropTarget.style.zIndex = 1;
      mostVisited.swapPosition(this.dragItem, dropTarget);
      // The timeout below is to allow WebKit to see that we turned off
      // pointer-event before moving the thumbnails so that we can get out of
      // hover mode.
      window.setTimeout(function() {
        mostVisited.invalidate();
        mostVisited.layout();
      }, 10);
      e.preventDefault();
      if (this.dragEndTimer) {
        window.clearTimeout(this.dragEndTimer);
        this.dragEndTimer = null;
      }
      afterTransition(function() {
        dropTarget.style.zIndex = '';
      });
    }
  },

  handleDragEnd: function(e) {
    // WebKit fires dragend before drop.
    var dragItem = this.dragItem;
    if (dragItem) {
      dragItem.style.pointerEvents = '';
      removeClass(dragItem, 'dragging');

      afterTransition(function() {
        // Delay resetting zIndex to let the animation finish.
        dragItem.style.zIndex = '';
        // Same for overflow.
        dragItem.parentNode.style.overflow = '';
      });
      var self = this;
      this.dragEndTimer = window.setTimeout(function() {
        // These things needto happen after the drop event.
        mostVisited.invalidate();
        mostVisited.layout();
        self.dragItem = null;
      }, 10);
    }
  },

  handleDrag: function(e) {
    // Moves the drag item making sure that it is not displayed outside the
    // browser viewport.
    var item = mostVisited.getItem(e.target);
    var rect = document.querySelector('#most-visited').getBoundingClientRect();
    item.style.pointerEvents = 'none';

    var x = this.startX + e.screenX - this.startScreenX;
    var y = this.startY + e.screenY - this.startScreenY;

    // The position of the item is relative to #most-visited so we need to
    // subtract that when calculating the allowed position.
    x = Math.max(x, -rect.left);
    x = Math.min(x, document.body.clientWidth - rect.left - item.offsetWidth -
                 2);
    // The shadow is 2px
    y = Math.max(-rect.top, y);
    y = Math.min(y, document.body.clientHeight - rect.top - item.offsetHeight -
                 2);

    item.style.left = x + 'px';
    item.style.top = y + 'px';
  },

  // We listen to mousedown to get the relative position of the cursor for dnd.
  handleMouseDown: function(e) {
    var item = mostVisited.getItem(e.target);
    if (item) {
      this.startX = item.offsetLeft;
      this.startY = item.offsetTop;
      this.startScreenX = e.screenX;
      this.startScreenY = e.screenY;
    }
  },

  canDropOnElement: function(el) {
    return this.dragItem && el && hasClass(el, 'thumbnail-container') &&
        !hasClass(el, 'filler');
  },

  init: function() {
    var el = $('most-visited');
    el.addEventListener('dragstart', bind(this.handleDragStart, this));
    el.addEventListener('dragenter', bind(this.handleDragEnter, this));
    el.addEventListener('dragover', bind(this.handleDragOver, this));
    el.addEventListener('dragleave', bind(this.handleDragLeave, this));
    el.addEventListener('drop', bind(this.handleDrop, this));
    el.addEventListener('dragend', bind(this.handleDragEnd, this));
    el.addEventListener('drag', bind(this.handleDrag, this));
    el.addEventListener('mousedown', bind(this.handleMouseDown, this));
  }
};

dnd.init();

/**
 * Whitelist of tag names allowed in parseHtmlSubset.
 * @type {[string]}
 * /
var allowedTags = ['A', 'B', 'STRONG'];

/**
 * Parse a very small subset of HTML.
 * @param {string} s The string to parse.
 * @throws {Error} In case of non supported markup.
 * @return {DocumentFragment} A document fragment containing the DOM tree.
 */
var allowedAttributes = {
  'href': function(node, value) {
    // Only allow a[href] starting with http:// and https://
    return node.tagName == 'A' && (value.indexOf('http://') == 0 ||
        value.indexOf('https://') == 0);
  }
}

/**
 * Parse a very small subset of HTML.  This ensures that insecure HTML /
 * javascript cannot be injected into the new tab page.
 * @param {string} s The string to parse.
 * @throws {Error} In case of non supported markup.
 * @return {DocumentFragment} A document fragment containing the DOM tree.
 */
function parseHtmlSubset(s) {
  function walk(n, f) {
    f(n);
    for (var i = 0; i < n.childNodes.length; i++) {
      walk(n.childNodes[i], f);
    }
  }

  function assertElement(node) {
    if (allowedTags.indexOf(node.tagName) == -1)
      throw Error(node.tagName + ' is not supported');
  }

  function assertAttribute(attrNode, node) {
    var n = attrNode.nodeName;
    var v = attrNode.nodeValue;
    if (!allowedAttributes.hasOwnProperty(n) || !allowedAttributes[n](node, v))
      throw Error(node.tagName + '[' + n + '="' + v + '"] is not supported');
  }

  var r = document.createRange();
  r.selectNode(document.body);
  // This does not execute any scripts.
  var df = r.createContextualFragment(s);
  walk(df, function(node) {
    switch (node.nodeType) {
      case Node.ELEMENT_NODE:
        assertElement(node);
        var attrs = node.attributes;
        for (var i = 0; i < attrs.length; i++) {
          assertAttribute(attrs[i], node);
        }
        break;

      case Node.COMMENT_NODE:
      case Node.DOCUMENT_FRAGMENT_NODE:
      case Node.TEXT_NODE:
        break;

      default:
        throw Error('Node type ' + node.nodeType + ' is not supported');
    }
  });
  return df;
}