This file is indexed.

/usr/share/routino/www/router.leaflet.js is in routino-www 3.0-3.

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
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
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
//
// Routino router web page Javascript
//
// Part of the Routino routing software.
//
// This file Copyright 2008-2015 Andrew M. Bishop
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//


var vismarkers, markers, icons, markersmoved, paramschanged;
var homelat=null, homelon=null;


////////////////////////////////////////////////////////////////////////////////
/////////////////////////////// Initialisation /////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

// Make a deep copy of the routino profile.

var routino_default={};
for(var l1 in routino)
   if(typeof(routino[l1])!="object")
      routino_default[l1]=routino[l1];
   else
     {
      routino_default[l1]={};
      for(var l2 in routino[l1])
         if(typeof(routino[l1][l2])!="object")
            routino_default[l1][l2]=Number(routino[l1][l2]);
         else
           {
            routino_default[l1][l2]={};
            for(var l3 in routino[l1][l2])
               routino_default[l1][l2][l3]=Number(routino[l1][l2][l3]);
           }
     }

// Store the latitude and longitude in the routino variable

routino.point=[];
for(var marker=1;marker<=mapprops.maxmarkers;marker++)
  {
   routino.point[marker]={};

   routino.point[marker].lon="";
   routino.point[marker].lat="";
   routino.point[marker].search="";
   routino.point[marker].active=false;
   routino.point[marker].used=false;
   routino.point[marker].home=false;
  }

// Process the URL query string and extract the arguments

var legal={"^lon"             : "^[-0-9.]+$",
           "^lat"             : "^[-0-9.]+$",
           "^zoom"            : "^[0-9]+$",

           "^lon[1-9]"        : "^[-0-9.]+$",
           "^lat[1-9]"        : "^[-0-9.]+$",
           "^search[1-9]"     : "^.+$",
           "^transport"       : "^[a-z]+$",
           "^highway-[a-z]+"  : "^[0-9.]+$",
           "^speed-[a-z]+"    : "^[0-9.]+$",
           "^property-[a-z]+" : "^[0-9.]+$",
           "^oneway"          : "^(1|0|true|false|on|off)$",
           "^turns"           : "^(1|0|true|false|on|off)$",
           "^weight"          : "^[0-9.]+$",
           "^height"          : "^[0-9.]+$",
           "^width"           : "^[0-9.]+$",
           "^length"          : "^[0-9.]+$",

           "^language"        : "^[-a-zA-Z]+$"};

var args={};

if(location.search.length>1)
  {
   var query,queries;

   query=location.search.replace(/^\?/,"");
   query=query.replace(/;/g,"&");
   queries=query.split("&");

   for(var i=0;i<queries.length;i++)
     {
      queries[i].match(/^([^=]+)(=(.*))?$/);

      var k=RegExp.$1;
      var v=decodeURIComponent(RegExp.$3);

      for(var l in legal)
        {
         if(k.match(RegExp(l)) && v.match(RegExp(legal[l])))
            args[k]=v;
        }
     }
  }


//
// Fill in the HTML - add the missing waypoints
//

function html_init()            // called from router.html
{
 var waypoints=document.getElementById("waypoints");

 var waypoint_html=waypoints.firstElementChild.outerHTML.split("XXX");

 waypoints.removeChild(waypoints.firstElementChild);

 for(var marker=1;marker<=mapprops.maxmarkers;marker++)
   {
    var waypoint=document.createElement('div');

    waypoints.appendChild(waypoint);

    waypoint.outerHTML=waypoint_html.join(marker);
   }

 waypoints.addEventListener('dragstart',dragWaypointStart,false);
 waypoints.addEventListener('dragend'  ,dragWaypointEnd  ,false);
 waypoints.addEventListener('dragenter',dragWaypointEnter,false);
 waypoints.addEventListener('dragover' ,dragWaypointOver ,false);
 waypoints.addEventListener('dragleave',dragWaypointLeave,false);
 waypoints.addEventListener('drop'     ,dragWaypointDrop ,false);


 var map=document.getElementById("map");

 map.addEventListener('dragenter',dragWaypointMapEnter,false);
 map.addEventListener('dragover' ,dragWaypointMapOver ,false);
 map.addEventListener('dragleave',dragWaypointMapLeave,false);
 map.addEventListener('drop'     ,dragWaypointMapDrop ,false);
}


////////////////////////////////////////////////////////////////////////////////
//////////////////////////////// Form handling /////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

//
// Form initialisation - fill in the uninitialised parts
//

function form_init()            // called from router.html
{
 // Fill in the waypoints

 vismarkers=0;

 for(var marker=mapprops.maxmarkers;marker>=1;marker--)
   {
    var lon=args["lon" + marker];
    var lat=args["lat" + marker];
    var search=args["search" + marker];

    if(lon !== undefined && lat !== undefined && search !== undefined && lon !== "" && lat !== "" && search !== "")
      {
       markerAddForm(marker);

       formSetSearch(marker,search);
       formSetCoords(marker,lon,lat);

       markerAddMap(marker);

       markerSearch(marker);

       vismarkers++;
      }
    else if(lon !== undefined && lat !== undefined && lon !== "" && lat !== "")
      {
       markerAddForm(marker);

       formSetCoords(marker,lon,lat);

       markerAddMap(marker);

       markerCoords(marker);

       vismarkers++;
      }
    else if(search !== undefined && search !== "")
      {
       markerAddForm(marker);

       formSetSearch(marker,search);

       markerSearch(marker);

       DoSearch(marker);

       vismarkers++;
      }
    else if(vismarkers || marker<=2)
      {
       markerAddForm(marker);

       vismarkers++;
      }

    var searchfield=document.forms["form"].elements["search" + marker];

    if(searchfield.addEventListener)
       searchfield.addEventListener("keyup", searchOnReturnKey, false);
    else if(searchfield.attachEvent)
       searchfield.attachEvent("keyup", searchOnReturnKey); // Internet Explorer
   }

 // Update the transport type with the URL settings which updates all HTML forms to defaults.

 var transport=routino.transport;

 if(args["transport"] !== undefined)
    transport=args["transport"];

 formSetTransport(transport);

 // Update the HTML with the URL settings

 if(args["language"] !== undefined)
    formSetLanguage(args["language"]);

 for(var key in routino.profile_highway)
    if(args["highway-" + key] !== undefined)
       formSetHighway(key,args["highway-" + key]);

 for(var key in routino.profile_speed)
    if(args["speed-" + key] !== undefined)
       formSetSpeed(key,args["speed-" + key]);

 for(var key in routino.profile_property)
    if(args["property-" + key] !== undefined)
       formSetProperty(key,args["property-" + key]);

 for(var key in routino.restrictions)
   {
    if(key=="oneway" || key=="turns")
      {
       if(args[key] !== undefined)
          formSetRestriction(key,args[key]);
      }
    else
      {
       if(args["restrict-" + key] !== undefined)
          formSetRestriction(key,args["restrict-" + key]);
      }
   }

 // Get the home location cookie and compare to each waypoint

 var cookies=document.cookie.split("; ");

 for(var cookie=0;cookie<cookies.length;cookie++)
    if(cookies[cookie].substr(0,"Routino-home".length)=="Routino-home")
      {
       var data=cookies[cookie].split(/[=:;]/);

       if(data[1]=="lon") homelon=Number(data[2]);
       if(data[3]=="lat") homelat=Number(data[4]);
      }

 if(homelon!==null && homelat!==null)
   {
    for(var m=1;m<=vismarkers;m++)
       markerCheckHome(m);

    // If the first location is empty and the cookie is set then fill it.

    if(!routino.point[1].used)
       markerMoveHome(1);
   }

 updateURLs();

 updateSearchButtons();
}


//
// Function to perform the search if the return key is pressed.
// (using 'onchange' only triggers once and is confusing when clicking outside the field).
//

function searchOnReturnKey(ev)
{
 if(ev.keyCode==13)
    if(this.name.match(/^search([0-9]+)$/))
       formSetSearch(RegExp.$1);

 return(true);
}


//
// Change of language in the form
//

function formSetLanguage(value) // called from router.html (with no arguments)
{
 if(value === undefined)
   {
    for(var lang=0;lang<document.forms["form"].elements["language"].length;lang++)
       if(document.forms["form"].elements["language"][lang].checked)
          routino.language=document.forms["form"].elements["language"][lang].value;
   }
 else
   {
    for(var lang=0;lang<document.forms["form"].elements["language"].length;lang++)
       if(document.forms["form"].elements["language"][lang].value==value)
          document.forms["form"].elements["language"][lang].checked=true;
       else
          document.forms["form"].elements["language"][lang].checked=false;

    routino.language=value;
   }

 updateURLs();
}


//
// Change of transport in the form
//

function formSetTransport(value) // called from router.html
{
 routino.transport=value;

 for(var key in routino.transports)
    document.forms["form"].elements["transport"][routino.transports[key]-1].checked=(key==routino.transport);

 for(var key in routino.profile_highway)
    document.forms["form"].elements["highway-" + key].value=routino.profile_highway[key][routino.transport];

 for(var key in routino.profile_speed)
    document.forms["form"].elements["speed-" + key].value=routino.profile_speed[key][routino.transport];

 for(var key in routino.profile_property)
    document.forms["form"].elements["property-" + key].value=routino.profile_property[key][routino.transport];

 for(var key in routino.restrictions)
   {
    if(key=="oneway" || key=="turns")
       document.forms["form"].elements["restrict-" + key].checked=routino.profile_restrictions[key][routino.transport];
    else
       document.forms["form"].elements["restrict-" + key].value=routino.profile_restrictions[key][routino.transport];
   }

 paramschanged=true;

 updateURLs();
}


//
// Change of highway in the form
//

function formSetHighway(type,value) // called from router.html (with one argument)
{
 if(value == "+")
   {
    value=routino.profile_highway[type][routino.transport];
    value=10*Math.floor(value/10)+10;
   }
 else if(value == "-")
   {
    value=routino.profile_highway[type][routino.transport]-10;
    value=10*Math.ceil(value/10)-10;
   }
 else if(value == "=")
    value=document.forms["form"].elements["highway-" + type].value;

 value=Number(value);
 if(isNaN(value)) value= 50;
 if(value>100)    value=100;
 if(value<  0)    value=  0;

 document.forms["form"].elements["highway-" + type].value=value;
 routino.profile_highway[type][routino.transport]=value;

 paramschanged=true;

 updateURLs();
}


//
// Change of Speed in the form
//

function formSetSpeed(type,value) // called from router.html (with one argument)
{
 if(value == "+")
   {
    value=routino.profile_speed[type][routino.transport];
    if(value<10) value=2*Math.floor(value/2)+2;
    else if(value<30) value=5*Math.floor(value/5)+5;
    else value=10*Math.floor(value/10)+10;
   }
 else if(value == "-")
   {
    value=routino.profile_speed[type][routino.transport];
    if(value<=10) value=2*Math.ceil(value/2)-2;
    else if(value<=30) value=5*Math.ceil(value/5)-5;
    else value=10*Math.ceil(value/10)-10;
   }
 else if(value == "=")
    value=document.forms["form"].elements["speed-" + type].value;

 value=Number(value);
 if(isNaN(value)) value= 60;
 if(value>150)    value=150;
 if(value<  0)    value=  0;

 document.forms["form"].elements["speed-" + type].value=value;
 routino.profile_speed[type][routino.transport]=value;

 paramschanged=true;

 updateURLs();
}


//
// Change of Property in the form
//

function formSetProperty(type,value) // called from router.html (with one argument)
{
 if(value == "+")
   {
    value=routino.profile_property[type][routino.transport];
    if(value>=40 && value<60) value=2*Math.floor(value/2)+2;
    else value=5*Math.floor(value/5)+5;
   }
 else if(value == "-")
   {
    value=routino.profile_property[type][routino.transport];
    if(value>40 && value<=60) value=2*Math.ceil(value/2)-2;
    else value=5*Math.ceil(value/5)-5;
   }
 else if(value == "=")
    value=document.forms["form"].elements["property-" + type].value;

 value=Number(value);
 if(isNaN(value)) value= 50;
 if(value>100)    value=100;
 if(value<  0)    value=  0;

 document.forms["form"].elements["property-" + type].value=value;
 routino.profile_property[type][routino.transport]=value;

 paramschanged=true;

 updateURLs();
}


//
// Change of Restriction rule in the form
//

function formSetRestriction(type,value) // called from router.html (with one argument)
{
 if(type=="oneway" || type=="turns")
   {
    if(value === undefined)
       routino.profile_restrictions[type][routino.transport]=document.forms["form"].elements["restrict-" + type].checked;
    else
       document.forms["form"].elements["restrict-" + type].checked=value;

    routino.profile_restrictions[type][routino.transport]=value;
   }
 else if(type=="weight")
   {
    if(value == "+")
       value=routino.profile_restrictions[type][routino.transport]+5;
    else if(value == "-")
       value=routino.profile_restrictions[type][routino.transport]-5;
    else if(value == "=")
       value=document.forms["form"].elements["restrict-" + type].value;

    value=Number(value);
    if(isNaN(value)) value= 0;
    if(value>50)     value=50;
    if(value< 0)     value= 0;

    document.forms["form"].elements["restrict-" + type].value=value;
    routino.profile_restrictions[type][routino.transport]=value;
   }
 else /* if(type=="height" || type=="width" || type=="length") */
   {
    if(value == "+")
       value=routino.profile_restrictions[type][routino.transport]+1;
    else if(value == "-")
       value=routino.profile_restrictions[type][routino.transport]-1;
    else if(value == "=")
       value=document.forms["form"].elements["restrict-" + type].value;

    value=Number(value);
    if(isNaN(value)) value= 0;
    if(value>25)     value=25;
    if(value< 0)     value= 0;

    document.forms["form"].elements["restrict-" + type].value=value;
    routino.profile_restrictions[type][routino.transport]=value;
   }

 paramschanged=true;

 updateURLs();
}


//
// Set the feature coordinates from the form when the form changes.
//

function formSetCoords(marker,lon,lat) // called from router.html (with one argument)
{
 clearSearchResult(marker);

 if(lon === undefined && lat === undefined)
   {
    lon=document.forms["form"].elements["lon" + marker].value;
    lat=document.forms["form"].elements["lat" + marker].value;
   }

 if(lon === "" && lat === "")
   {
    document.forms["form"].elements["lon" + marker].value="";
    document.forms["form"].elements["lat" + marker].value="";

    routino.point[marker].lon="";
    routino.point[marker].lat="";

    updateURLs();
   }
 else
   {
    var lonlat;

    if(lon==="")
      {
       lonlat=map.getCenter();

       lon=lonlat.lon;
      }

    if(lon<-180) lon=-180;
    if(lon>+180) lon=+180;

    if(lat==="")
      {
       lonlat=map.getCenter();

       lat=lonlat.lat;
      }

    if(lat<-90 ) lat=-90 ;
    if(lat>+90 ) lat=+90 ;

    lonlat = L.latLng(lat,lon);

    markers[marker].setLatLng(lonlat);

    markersmoved=true;

    document.forms["form"].elements["lon" + marker].value=format5f(lon);
    document.forms["form"].elements["lat" + marker].value=format5f(lat);

    routino.point[marker].lon=lon;
    routino.point[marker].lat=lat;
    routino.point[marker].used=true;

    markerCheckHome(marker);
   }
}


//
// Set the search field from the form when the form changes.
//

function formSetSearch(marker,search) // called from event handler linked to router.html (with one argument)
{
 clearSearchResult(marker);

 if(search === undefined)
   {
    routino.point[marker].search=document.forms["form"].elements["search" + marker].value;

    DoSearch(marker);
   }
 else
   {
    document.forms["form"].elements["search" + marker].value=search;

    routino.point[marker].search=search;
   }
}


//
// Format a number in printf("%.5f") format.
//

function format5f(number)
{
 var newnumber=Math.floor(number*100000+0.5);
 var delta=0;

 if(newnumber>=0 && newnumber<100000) delta= 100000;
 if(newnumber<0 && newnumber>-100000) delta=-100000;

 var string=String(newnumber+delta);

 var intpart =string.substring(0,string.length-5);
 var fracpart=string.substring(string.length-5,string.length);

 if(delta>0) intpart="0";
 if(delta<0) intpart="-0";

 return(intpart + "." + fracpart);
}


//
// Build a set of URL arguments
//

function buildURLArguments(lang)
{
 var url= "transport=" + routino.transport;

 for(var marker=1;marker<=vismarkers;marker++)
    if(routino.point[marker].active)
      {
       url=url + ";lon" + marker + "=" + format5f(routino.point[marker].lon);
       url=url + ";lat" + marker + "=" + format5f(routino.point[marker].lat);
       if(routino.point[marker].search !== "")
          url=url + ";search" + marker + "=" + encodeURIComponent(routino.point[marker].search);
      }

 for(var key in routino.profile_highway)
    if(routino.profile_highway[key][routino.transport]!=routino_default.profile_highway[key][routino.transport])
       url=url + ";highway-" + key + "=" + routino.profile_highway[key][routino.transport];

 for(var key in routino.profile_speed)
    if(routino.profile_speed[key][routino.transport]!=routino_default.profile_speed[key][routino.transport])
       url=url + ";speed-" + key + "=" + routino.profile_speed[key][routino.transport];

 for(var key in routino.profile_property)
    if(routino.profile_property[key][routino.transport]!=routino_default.profile_property[key][routino.transport])
       url=url + ";property-" + key + "=" + routino.profile_property[key][routino.transport];

 for(var key in routino.restrictions)
    if(routino.profile_restrictions[key][routino.transport]!=routino_default.profile_restrictions[key][routino.transport])
       url=url + ";" + key + "=" + routino.profile_restrictions[key][routino.transport];

 if(lang && routino.language)
    url=url + ";language=" + routino.language;

 return(url);
}


//
// Build a set of URL arguments for the map location
//

function buildMapArguments()
{
 var lonlat = map.getCenter();

 var zoom = map.getZoom();

 return "lat=" + format5f(lonlat.lat) + ";lon=" + format5f(lonlat.lng) + ";zoom=" + zoom;
}


//
// Update the URLs
//

function updateURLs()
{
 var urlargs1=buildURLArguments(true);
 var urlargs2=buildURLArguments(false);
 var mapargs=buildMapArguments();

 var links=document.getElementsByTagName("a");

 for(var i=0; i<links.length; i++)
   {
    var element=links[i];

    if(element.id == "permalink_url")
       element.href=location.pathname + "?" + urlargs1 + ";" + mapargs;

    if(element.id == "visualiser_url")
       element.href="visualiser.html" + "?" + mapargs;

    if(element.id == "edit_url")
       element.href=mapprops.editurl + "?" + mapargs;

    if(element.id.match(/^lang_([a-zA-Z-]+)_url$/))
       element.href="router.html" + "." + RegExp.$1 + "?" + urlargs2 + ";" + mapargs;
   }
}


////////////////////////////////////////////////////////////////////////////////
///////////////////////////////// Map handling /////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

var map;
var layerMap=[], layerVectors, layerGPX;
var routing_type;

//
// Initialise the 'map' object
//

function map_init()             // called from router.html
{
 // Create the map (Map URLs and limits are in mapprops.js)

 map = L.map("map",
             {
              attributionControl: false,
              zoomControl: false,

              minZoom: mapprops.zoomout,
              maxZoom: mapprops.zoomin,

              maxBounds: L.latLngBounds(L.latLng(mapprops.southedge,mapprops.westedge),L.latLng(mapprops.northedge,mapprops.eastedge))
              });

 map.setView({lng: 0, lat: 0}, 2);

 // Add map tile layers

 var baselayers={};

 for(var l=0; l<mapprops.mapdata.length; l++)
   {
    var urls=mapprops.mapdata[l].tiles.url.replace(/\${/g,"{");

    if(mapprops.mapdata[l].tiles.subdomains===undefined)
       layerMap[l] = L.tileLayer(urls);
    else
       layerMap[l] = L.tileLayer(urls, {subdomains: mapprops.mapdata[l].tiles.subdomains});

    baselayers[mapprops.mapdata[l].label]=layerMap[l];

    if(l===0)
       map.addLayer(layerMap[l]);
   }

 // Add the controls

 map.addControl(L.control.zoom());
 map.addControl(L.control.scale());
 map.addControl(L.control.layers(baselayers));

 // Update the attribution if the layer changes

 function change_attribution_event(event)
 {
  for(var l=0; l<mapprops.mapdata.length; l++)
     if(layerMap[l] == event.layer)
        change_attribution(l);
 }

 map.on("baselayerchange",change_attribution_event);

 function change_attribution(l)
 {
  var data_url =mapprops.mapdata[l].attribution.data_url;
  var data_text=mapprops.mapdata[l].attribution.data_text;
  var tile_url =mapprops.mapdata[l].attribution.tile_url;
  var tile_text=mapprops.mapdata[l].attribution.tile_text;

  document.getElementById("attribution_data").innerHTML="<a href=\"" + data_url + "\" target=\"data_attribution\">" + data_text + "</a>";
  document.getElementById("attribution_tile").innerHTML="<a href=\"" + tile_url + "\" target=\"tile_attribution\">" + tile_text + "</a>";
 }

 change_attribution(0);

 // Define a GPX layer but don't add it yet

 layerGPX={shortest: null, quickest: null};

 // Add a markers vectors layer

 layerVectors = L.layerGroup();
 map.addLayer(layerVectors);

 // A set of markers

 markers={};
 icons={};
 markersmoved=false;
 paramschanged=false;

 for(var marker=1;marker<=mapprops.maxmarkers;marker++)
   {
    icons[marker]=L.icon({iconUrl: "icons/marker-" + marker + "-red.png",
                          iconSize: L.point(21,25),
                          iconAnchor: L.point(10,25)});

    markers[marker]=L.marker(L.point(0,0), {clickable: true, draggable: true, icon: icons[marker]});

    markers[marker].on("drag"   , (function(m) { return function(evt) { dragMarkerMove    (m,evt); }; }(marker)));
    markers[marker].on("dragend", (function(m) { return function(evt) { dragMarkerComplete(m,evt); }; }(marker)));
   }

 icons.home=L.icon({iconUrl: "icons/marker-home-red.png",
                    iconSize: L.point(21,25),
                    iconAnchor: L.point(11,-25)});

 // Markers to highlight a selected point

 for(var highlight in highlights)
   {
    highlights[highlight]=L.circleMarker(L.latLng(0,0), {radius: 10, stroke: true, weight: 4, color: route_dark_colours[highlight], opacity: 1.0,
                                                         fill: false});
   }

 // A popup for routing results

 for(var popup in popups)
    popups[popup] = createPopup(popup);

 // Move the map

 map.on("moveend", updateURLs);

 var lon =args["lon"];
 var lat =args["lat"];
 var zoom=args["zoom"];

 if(lon !== undefined && lat !== undefined && zoom !== undefined)
   {
    if(lon<mapprops.westedge) lon=mapprops.westedge;
    if(lon>mapprops.eastedge) lon=mapprops.eastedge;

    if(lat<mapprops.southedge) lat=mapprops.southedge;
    if(lat>mapprops.northedge) lat=mapprops.northedge;

    if(zoom<mapprops.zoomout) zoom=mapprops.zoomout;
    if(zoom>mapprops.zoomin)  zoom=mapprops.zoomin;

    map.setView(L.latLng(lat,lon),zoom);
   }
 else
    map.fitBounds(map.options.maxBounds);

 // Unhide editing URL if variable set

 if(mapprops.editurl !== undefined && mapprops.editurl !== "")
   {
    var edit_url=document.getElementById("edit_url");

    edit_url.style.display="";
    edit_url.href=mapprops.editurl;
   }

 updateURLs();
}


//
// Callback for a marker drag occuring on the map.
//

function dragMarkerMove(marker,event)
{
 dragMarkerSetForm(marker);
}


//
// Callback for completing a drag occuring on the map.
//

function dragMarkerComplete(marker,event)
{
 dragMarkerSetForm(marker);

 updateURLs();
}


//
// Set the feature coordinates in the form after dragging it on the map.
//

function dragMarkerSetForm(marker)
{
 var lonlat = markers[marker].getLatLng();

 formSetCoords(marker,lonlat.lng,lonlat.lat);
}


////////////////////////////////////////////////////////////////////////////////
/////////////////////////////// Marker dragging ////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

var dragged_waypoint=null,dragged_marker=null;
var dragged_waypoint_over=null,dragged_marker_over=null;
 var dragged_icon_x,dragged_icon_y;

//
// Drag a waypoint up or down the list.
//

function dragWaypointStart(e)
{
 var w=e.target;

 while(w!=null && w.className != "waypoint")
    w=w.parentElement;

 if(w===null)
    return;

 w.style.opacity = "0.5";

 dragged_waypoint=w;
 dragged_marker=Number.parseInt(dragged_waypoint.id.substring(8));

 dragged_icon_x=e.clientX-e.target.offsetLeft;
 dragged_icon_y=e.clientY-e.target.offsetTop;
}

function dragWaypointEnd(e)
{
 e.preventDefault();

 if(dragged_waypoint===null)
    return;

 dragged_waypoint.style.opacity = "";

 dragged_waypoint=null;
 dragged_marker=null;

 if(dragged_waypoint_over===null)
    return;

 dragged_waypoint_over.style.border = "";

 dragged_waypoint_over=null;
 dragged_marker_over=null;
}


//
// Drag a waypoint over another one up or down the list.
//

function dragWaypointEnter(e)
{
 var w=e.target;

 while(w!=null && w.className != "waypoint")
    w=w.parentElement;

 if(w===null)
    return;

 if(dragged_waypoint_over!==null)
    dragged_waypoint_over.style.border = "";

 if(w==dragged_waypoint)
    return;

 dragged_waypoint_over=w;
 dragged_marker_over=Number.parseInt(dragged_waypoint_over.id.substring(8));

 if(dragged_marker>dragged_marker_over)
    w.style.borderTop = "3px solid black";
 else
    w.style.borderBottom = "3px solid black";
}

function dragWaypointOver(e)
{
 e.preventDefault();
}

function dragWaypointLeave(e)
{
 var w=e.target;

 while(w!=null && w.className != "waypoint")
    w=w.parentElement;

 if(w===null)
    return;

 if(w==dragged_waypoint_over)
    return;

 w.style.border = "";
}


//
// Drop the waypoint after dragging up or down the list.
//

function dragWaypointDrop(e)
{
 e.preventDefault();

 if(dragged_marker_over===null)
    return;

 if(dragged_marker_over>dragged_marker)
    for(var m=dragged_marker;m<dragged_marker_over;m++)
       markerSwap(m,m+1);

 if(dragged_marker_over<dragged_marker)
    for(var m=dragged_marker;m>dragged_marker_over;m--)
       markerSwap(m,m-1);
}


//
// Drag a waypoint over the map.
//

function dragWaypointMapEnter(e)
{
 e.preventDefault();

 if(dragged_waypoint_over!==null)
    dragged_waypoint_over.style.border = "";
}

function dragWaypointMapOver(e)
{
 e.preventDefault();
}

function dragWaypointMapLeave(e)
{
 e.preventDefault();
}


//
// Drop the waypoint after dragging it over the map.
//

function dragWaypointMapDrop(e)
{
 e.preventDefault();

 var rect = document.getElementById("map").getBoundingClientRect();

 var lonlat=map.containerPointToLatLng(L.point(e.clientX-rect.left-window.scrollX-dragged_icon_x+8,
                                               e.clientY-rect.top -window.scrollY-dragged_icon_y+21));

 formSetCoords(dragged_marker,lonlat.lng,lonlat.lat);

 if(!routino.point[dragged_marker].active)
    markerToggleMap(dragged_marker);
}


////////////////////////////////////////////////////////////////////////////////
/////////////////////////////// Marker handling ////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

//
// Toggle a marker on the map.
//

function markerToggleMap(marker) // called from router.html
{
 if(!routino.point[marker].used)
   {
    routino.point[marker].used=true;
    markerCentre(marker);
    markerCoords(marker);
   }

 markerAddRemoveMap(marker,!routino.point[marker].active);

 updateSearchButtons();
}


//
// Show or hide a marker on the map.
//

function markerAddRemoveMap(marker,active)
{
 if(active)
    markerAddMap(marker);
 else
    markerRemoveMap(marker);
}


//
// Show a marker on the map.
//

function markerAddMap(marker)
{
 clearSearchResult(marker);

 layerVectors.addLayer(markers[marker]);
 routino.point[marker].active=true;
 routino.point[marker].used=true;

 updateIcon(marker);

 markersmoved=true;

 updateURLs();
}


//
// Remove a marker from the map.
//

function markerRemoveMap(marker)
{
 clearSearchResult(marker);

 layerVectors.removeLayer(markers[marker]);
 routino.point[marker].active=false;

 updateIcon(marker);

 markersmoved=true;

 updateURLs();
}


//
// Display search string for the marker
//

function markerSearch(marker)   // called from router.html
{
 clearSearchResult(marker);

 document.getElementById("coords" + marker).style.display="none";
 document.getElementById("search" + marker).style.display="";
}


//
// Display coordinates for the marker
//

function markerCoords(marker)   // called from router.html
{
 clearSearchResult(marker);

 document.getElementById("search" + marker).style.display="none";
 document.getElementById("coords" + marker).style.display="";
}


//
// Centre the marker on the map
//

function markerCentre(marker)   // called from router.html
{
 if(!routino.point[marker].used)
    return;

 clearSearchResult(marker);

 var lonlat=map.getCenter();

 formSetCoords(marker,lonlat.lng,lonlat.lat);
}


//
// Centre the map on the marker
//

function markerRecentre(marker) // called from router.html
{
 if(!routino.point[marker].used)
    return;

 clearSearchResult(marker);

 var lon=routino.point[marker].lon;
 var lat=routino.point[marker].lat;

 var lonlat = L.latLng(lat,lon);

 map.panTo(lonlat);
}


//
// Clear the current marker.
//

function markerRemove(marker)   // called from router.html
{
 clearSearchResult(marker);

 for(var m=marker;m<vismarkers;m++)
    markerCopy(m,m+1);

 markerRemoveForm(vismarkers--);

 if(vismarkers==1)
    markerAddAfter(1);

 updateSearchButtons();
}


//
// Add a marker before the current one.
//

function markerAddBefore(marker)
{
 if(vismarkers==mapprops.maxmarkers || marker==1)
    return false;

 clearSearchResult(marker);

 markerAddForm(++vismarkers);

 for(var m=vismarkers;m>marker;m--)
    markerCopy(m,m-1);

 markerClearForm(marker-1);
}


//
// Add a marker after the current one.
//

function markerAddAfter(marker) // called from router.html
{
 if(vismarkers==mapprops.maxmarkers)
    return false;

 clearSearchResult(marker);

 markerAddForm(++vismarkers);

 for(var m=vismarkers;m>(marker+1);m--)
    markerCopy(m,m-1);

 markerClearForm(marker+1);
}


//
// Set this marker as the home location.
//

function markerHome(marker)     // called from router.html
{
 if(!routino.point[marker].used)
   {
    markerMoveHome(marker);
   }
 else
   {
    clearSearchResult(marker);

    markerSetClearHome(marker,!routino.point[marker].home);
   }
}


//
// Set this marker as the current location.
//

function markerLocate(marker)   // called from router.html
{
 clearSearchResult(marker);

 if(navigator.geolocation)
    navigator.geolocation.getCurrentPosition(
                                             function(position) {
                                              formSetCoords(marker,position.coords.longitude,position.coords.latitude);
                                              markerAddMap(marker);
                                             });
}


//
// Update the search buttons enable/disable.
//

function updateSearchButtons()
{
 var markersactive=0;

 for(var m=1;m<=vismarkers;m++)
    if(routino.point[m].active)
       markersactive++;

 if(markersactive<2)
   {
    document.getElementById("shortest").disabled="disabled";
    document.getElementById("quickest").disabled="disabled";
   }
 else
   {
    document.getElementById("shortest").disabled="";
    document.getElementById("quickest").disabled="";
   }
}


//
// Update an icon to set colours and home or normal marker.
//

function updateIcon(marker)
{
 if(routino.point[marker].home)
   {
    if(routino.point[marker].active)
       document.getElementById("icon" + marker).src="icons/marker-home-red.png";
    else
       document.getElementById("icon" + marker).src="icons/marker-home-grey.png";

    markers[marker].setIcon(icons.home);
   }
 else
   {
    if(routino.point[marker].active)
       document.getElementById("icon" + marker).src="icons/marker-" + marker + "-red.png";
    else
       document.getElementById("icon" + marker).src="icons/marker-" + marker + "-grey.png";

    markers[marker].setIcon(icons[marker]);
   }

 markers[marker].update();
}


//
// Move the marker to the home location
//

function markerMoveHome(marker)
{
 if(homelon===null || homelat===null)
    return;

 routino.point[marker].home=true;
 routino.point[marker].used=true;

 formSetCoords(marker,homelon,homelat);
 markerAddMap(marker);
}


//
// Set or clear the home marker icon
//

function markerSetClearHome(marker,home)
{
 var cookie;
 var date = new Date();

 if(home)
   {
    homelat=routino.point[marker].lat;
    homelon=routino.point[marker].lon;

    cookie="Routino-home=lon:" + homelon + ":lat:" + homelat;

    date.setUTCFullYear(date.getUTCFullYear()+5);

    routino.point[marker].home=true;
   }
 else
   {
    homelat=null;
    homelon=null;

    cookie="Routino-home=unset";

    date.setUTCFullYear(date.getUTCFullYear()-1);

    routino.point[marker].home=false;
   }

 document.cookie=cookie + ";expires=" + date.toGMTString();

 updateIcon(marker);

 for(var m=1;m<=mapprops.maxmarkers;m++)
    markerCheckHome(m);
}


//
// Check if a marker is the home marker
//

function markerCheckHome(marker)
{
 var home=routino.point[marker].home;

 if(routino.point[marker].lon==homelon && routino.point[marker].lat==homelat)
    routino.point[marker].home=true;
 else
    routino.point[marker].home=false;

 if(home!=routino.point[marker].home)
    updateIcon(marker);
}


//
// Move this marker up.
//

function markerMoveUp(marker)   // called from router.html
{
 if(marker==1)
   {
    for(var m=1;m<vismarkers;m++)
       markerSwap(m,m+1);
   }
 else
    markerSwap(marker,marker-1);
}


//
// Move this marker down.
//

function markerMoveDown(marker) // called from router.html
{
 if(marker==vismarkers)
   {
    for(var m=vismarkers;m>1;m--)
       markerSwap(m,m-1);
   }
 else
    markerSwap(marker,marker+1);
}


//
// Copy a marker from one place to another.
//

function markerCopy(marker1,marker2)
{
 for(var element in routino.point[marker2])
    routino.point[marker1][element]=routino.point[marker2][element];

 document.getElementById("search" + marker1).style.display=document.getElementById("search" + marker2).style.display;

 document.getElementById("coords" + marker1).style.display=document.getElementById("coords" + marker2).style.display;

 document.forms["form"].elements["search" + marker1].value=document.forms["form"].elements["search" + marker2].value;

 formSetCoords(marker1,routino.point[marker1].lon,routino.point[marker1].lat);

 markerAddRemoveMap(marker1,routino.point[marker1].active);
}


//
// Swap a pair of markers.
//

function markerSwap(marker1,marker2)
{
 for(var element in routino.point[marker2])
   {
    var temp=routino.point[marker1][element];
    routino.point[marker1][element]=routino.point[marker2][element];
    routino.point[marker2][element]=temp;
   }

 var search_display=document.getElementById("search" + marker1).style.display;
 document.getElementById("search" + marker1).style.display=document.getElementById("search" + marker2).style.display;
 document.getElementById("search" + marker2).style.display=search_display;

 var coords_display=document.getElementById("coords" + marker1).style.display;
 document.getElementById("coords" + marker1).style.display=document.getElementById("coords" + marker2).style.display;
 document.getElementById("coords" + marker2).style.display=coords_display;

 var search_value=document.forms["form"].elements["search" + marker1].value;
 document.forms["form"].elements["search" + marker1].value=document.forms["form"].elements["search" + marker2].value;
 document.forms["form"].elements["search" + marker2].value=search_value;

 formSetCoords(marker1,routino.point[marker1].lon,routino.point[marker1].lat);
 formSetCoords(marker2,routino.point[marker2].lon,routino.point[marker2].lat);

 markerAddRemoveMap(marker1,routino.point[marker1].active);
 markerAddRemoveMap(marker2,routino.point[marker2].active);
}


//
// Reverse the markers.
//

function markersReverse()       // called from router.html
{
 for(var marker=1;marker<=vismarkers/2;marker++)
    markerSwap(marker,vismarkers+1-marker);

 markersmoved=true;

 updateURLs();
}


//
// Close the loop.
//

function markersLoop()          // called from router.html
{
 if(vismarkers==mapprops.maxmarkers)
    return false;

 if(routino.point[vismarkers].lon==routino.point[1].lon && routino.point[vismarkers].lat==routino.point[1].lat)
   {
    if(routino.point[vismarkers].active)
       return false;
    else
      {
       markerToggleMap(vismarkers);
       return true;
      }
   }

 if(routino.point[vismarkers].used)
    markerAddForm(++vismarkers);

 markerCopy(vismarkers,1);

 markersmoved=true;

 updateURLs();

 updateSearchButtons();
}


//
// Display the form for a marker
//

function markerAddForm(marker)
{
 document.getElementById("waypoint" + marker).style.display="";
}


//
// Hide the form for a marker
//

function markerRemoveForm(marker)
{
 document.getElementById("waypoint" + marker).style.display="none";

 markerClearForm(marker);
}


//
// Clear the form for a marker
//

function markerClearForm(marker)
{
 markerRemoveMap(marker);
 markerCoords(marker);

 formSetCoords(marker,"","");
 formSetSearch(marker,"");

 updateIcon(marker);

 routino.point[marker].used=false;
 routino.point[marker].home=false;
 routino.point[marker].active=false;
}


////////////////////////////////////////////////////////////////////////////////
//////////////////////////// Route results handling ////////////////////////////
////////////////////////////////////////////////////////////////////////////////

var route_light_colours={shortest: "#60C060", quickest: "#6060C0"};
var route_dark_colours ={shortest: "#408040", quickest: "#404080"};

var highlights={shortest: null, quickest: null};
var popups={shortest: null, quickest: null};
var routepoints={shortest: {}, quickest: {}};

//
// Highlight a specific item in the route
//

function highlight(type,line,action)
{
 if(action == "clear")
   {
    layerVectors.removeLayer(highlights[type]);

    drawPopup(type,null);
   }
 else if(action == "zoom")
   {
    var lonlat = L.latLng(routepoints[type][line].lat,routepoints[type][line].lon);

    map.setView(lonlat,mapprops.zoomin-2);
   }
 else
   {
    // Marker

    var lonlat = L.latLng(routepoints[type][line].lat,routepoints[type][line].lon);

    highlights[type].setLatLng(lonlat);

    layerVectors.addLayer(highlights[type]);

    // Popup

    drawPopup(type,"<table>" + routepoints[type][line].html + "</table>");
   }

 highlights[type].redraw();
}


//
// Create a popup - independent of map because want it fixed on screen not fixed on map.
//

function createPopup(type)
{
 var popup=document.createElement("div");

 popup.className = "popup";

 popup.innerHTML = "<span></span>";

 popup.style.display = "none";

 popup.style.position = "fixed";
 popup.style.top = "-4000px";
 popup.style.left = "-4000px";
 popup.style.zIndex = "100";

 popup.style.padding = "5px";

 popup.style.opacity=0.85;
 popup.style.backgroundColor=route_light_colours[type];
 popup.style.border="4px solid " + route_dark_colours[type];

 document.body.appendChild(popup);

 return(popup);
}


//
// Draw a popup - independent of map because want it fixed on screen not fixed on map.
//

function drawPopup(type,html)
{
 var popup=popups[type];

 if(html===null)
   {
    popup.style.display="none";
    return;
   }

 if(popup.style.display=="none")
   {
    var map_div=document.getElementById("map");

    popup.style.left  =map_div.offsetParent.offsetLeft+map_div.offsetLeft+60 + "px";
    popup.style.top   =                                map_div.offsetTop +30 + "px";
    popup.style.width =map_div.clientWidth-120 + "px";

    popup.style.display="";
   }

 var close="<span style='float: right; cursor: pointer;' onclick='highlight(\""+type+"\",-1,\"clear\")'>X</span>";

 popup.innerHTML=close+html;
}


//
// Remove a GPX trace
//

function removeGPXTrace(type)
{
 map.removeLayer(layerGPX[type]);
 layerGPX[type]=null;

 displayStatus(type,"no_info");

 document.getElementById(type + "_links").style.display = "none";

 document.getElementById(type + "_route").innerHTML = "";

 hideshow_hide(type);
}


////////////////////////////////////////////////////////////////////////////////
/////////////////////////////// Server handling ////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

//
// Define an AJAX request object
//

function ajaxGET(url,success,failure,state)
{
 var ajaxRequest=new XMLHttpRequest();

 function ajaxGOT(options) {
  if(this.readyState==4)
     if(this.status==200)
       { if(typeof(options.success)=="function") options.success(this,options.state); }
     else
       { if(typeof(options.failure)=="function") options.failure(this,options.state); }
 }

 ajaxRequest.onreadystatechange = function(){ ajaxGOT.call(ajaxRequest,{success: success, failure: failure, state: state}); };
 ajaxRequest.open("GET", url, true);
 ajaxRequest.send(null);
}


//
// Display data statistics
//

function displayStatistics() // called from router.html
{
 // Use AJAX to get the statistics

 ajaxGET("statistics.cgi", runStatisticsSuccess);
}


//
// Success in running data statistics generation.
//

function runStatisticsSuccess(response)
{
 document.getElementById("statistics_data").innerHTML="<pre>" + response.responseText + "</pre>";
 document.getElementById("statistics_link").style.display="none";
}


//
// Submit form - perform the routing
//

function findRoute(type) // called from router.html
{
 tab_select("results");

 hideshow_hide("help_options");
 hideshow_hide("shortest");
 hideshow_hide("quickest");

 displayStatus("result","running");

 var url="router.cgi" + "?" + buildURLArguments(true) + ";type=" + type;

 // Destroy the existing layer(s)

 highlight("shortest",-1,"clear");
 highlight("quickest",-1,"clear");

 if(markersmoved || paramschanged)
   {
    if(layerGPX.shortest!==null)
       removeGPXTrace("shortest");
    if(layerGPX.quickest!==null)
       removeGPXTrace("quickest");
    markersmoved=false;
    paramschanged=false;
   }
 else if(layerGPX[type]!==null)
    removeGPXTrace(type);

 // Use AJAX to run the router

 routing_type=type;

 ajaxGET(url, runRouterSuccess, runRouterFailure);
}


//
// Success in running router.
//

function runRouterSuccess(response)
{
 var lines=response.responseText.split("\n");

 var uuid=lines[0];
 var success=lines[1];

 var link;

 // Update the status message

 if(success=="ERROR")
   {
    displayStatus("result","error");
    hideshow_show("help_route");

    link=document.getElementById("router_log_error");
    link.href="results.cgi?uuid=" + uuid + ";type=router;format=log";

    return;
   }
 else
   {
    displayStatus("result","complete");
    hideshow_hide("help_route");

    link=document.getElementById("router_log_complete");
    link.href="results.cgi?uuid=" + uuid + ";type=router;format=log";
   }

 // Update the routing result message

 link=document.getElementById(routing_type + "_html");
 link.href="results.cgi?uuid=" + uuid + ";type=" + routing_type + ";format=html";

 link=document.getElementById(routing_type + "_gpx_track");
 link.href="results.cgi?uuid=" + uuid + ";type=" + routing_type + ";format=gpx-track";

 link=document.getElementById(routing_type + "_gpx_route");
 link.href="results.cgi?uuid=" + uuid + ";type=" + routing_type + ";format=gpx-route";

 link=document.getElementById(routing_type + "_text_all");
 link.href="results.cgi?uuid=" + uuid + ";type=" + routing_type + ";format=text-all";

 link=document.getElementById(routing_type + "_text");
 link.href="results.cgi?uuid=" + uuid + ";type=" + routing_type + ";format=text";

 document.getElementById(routing_type + "_links").style.display = "";

 // Add a GPX layer

 var url="results.cgi?uuid=" + uuid + ";type=" + routing_type + ";format=gpx-track";

 ajaxGET(url, runGPXSuccess);
 
 hideshow_show(routing_type);

 displayResult(routing_type,uuid);
}


//
// Success in getting GPX.
//

function runGPXSuccess(response)
{
 var lines=response.responseText.split("\n");

 var coords=[];
 var segment=-1;

 for(var line=0;line<lines.length;line++)
   {
    if(lines[line].match(/^<trkseg>/))
       {
        segment++;
        coords[segment]=[];
       }
    if(lines[line].match(/^<trkpt lat="([-0-9.]+)" lon="([-0-9.]+)"/))
      {
       var lat=RegExp.$1;
       var lon=RegExp.$2;

       coords[segment].push(L.latLng(lat,lon));
      }
   }

 var colour;

 if(routing_type == "shortest")
    colour="#00FF00";
 else
    colour="#0000FF";

 layerGPX[routing_type] = L.multiPolyline(coords,{weight: 3, stroke: true, color: colour, opacity: 1.0,
                                                  fill: false});

 map.addLayer(layerGPX[routing_type]);
}


//
// Failure in running router.
//

function runRouterFailure(response)
{
 displayStatus("result","failed");
}


//
// Display the status
//

function displayStatus(type,subtype,content)
{
 var child=document.getElementById(type + "_status").firstChild;

 do
   {
    if(child.id !== undefined)
       child.style.display="none";

    child=child.nextSibling;
   }
 while(child !== null);

 var chosen_status=document.getElementById(type + "_status_" + subtype);

 chosen_status.style.display="";

 if(content !== undefined)
    chosen_status.innerHTML=content;
}


//
// Display the route
//

function displayResult(type,uuid)
{
 routing_type = type;

 // Add the route

 var url="results.cgi?uuid=" + uuid + ";type=" + routing_type + ";format=html";

 // Use AJAX to get the route

 ajaxGET(url, getRouteSuccess, getRouteFailure);
}


//
// Success in getting route.
//

function getRouteSuccess(response)
{
 var lines=response.responseText.split("\n");

 routepoints[routing_type]=[];

 var points=routepoints[routing_type];

 var table=0;
 var point=0;
 var total_table,total_word;

 for(var line=0;line<lines.length;line++)
   {
    var thisline=lines[line];

    if(table===0)
      {
       if(thisline.match("<table>"))
          table=1;
       else
          continue;
      }

    if(thisline.match("</table>"))
       break;

    if(thisline.match("<tr class='([a-z])'>"))
      {
       var rowtype=RegExp.$1;

       if(rowtype=="c")
         {
          thisline.match(": *([-0-9.]+) *([-0-9.]+)");
          points[point]={lat: Number(RegExp.$1), lon: Number(RegExp.$2), html: "", highway: "", distance: "", total: ""};

          point++;
         }
       else if(rowtype=="n")
         {
          points[point-1].html += thisline;
         }
       else if(rowtype=="s")
         {
          thisline.match("<span class='h'>([^<]+)</span>");
          points[point-1].highway = RegExp.$1;

          thisline.match("<span class='d'>([^<]+)</span>");
          points[point-1].distance = RegExp.$1;

          thisline.match("(<span class='j'>[^<]+</span>)");
          points[point-1].total = RegExp.$1;

          thisline.match("^(.*).<span class='j'>");

          points[point-1].html += RegExp.$1;
         }
       else if(rowtype=="t")
         {
          points[point-1].html += thisline;

          thisline.match("<span class='j'>([^<]+)</span>");
          points[point-1].total = RegExp.$1;

          thisline.match("<td>(.*)");
          points[point-1].highway = RegExp.$1;
         }
      }
   }

 displayStatus(routing_type,"info",points[point-1].total.bold());

 var result="<table onmouseout='highlight(\"" + routing_type + "\",-1,\"clear\")'>";

 for(var p=0;p<point;p++)
   {
    if(p!=point-1)
       points[p].html += "<tr><td>" + points[p].total;

    result=result + "<tr onmouseover='highlight(\"" + routing_type + "\"," + p + ",\"show\")'>" +
                    "<td onclick='highlight(\"" + routing_type + "\"," + p + ",\"zoom\")'" +
                    " class='distance' title='" + points[p].distance + "'>#" + (p+1) +
                    "<td class='highway'>" + points[p].highway;
   }

 result=result + "</table>";

 document.getElementById(routing_type + "_route").innerHTML=result;
}


//
// Failure in getting route.
//

function getRouteFailure(response)
{
 document.getElementById(routing_type + "_route").innerHTML = "";
}


//
// Perform a search
//

function DoSearch(marker)
{
 // Use AJAX to get the search result

 var search=routino.point[marker].search;

 var mapbounds=map.getBounds();

 var url="search.cgi";

 url=url + "?marker=" + marker;
 url=url + ";lonmin=" + format5f(mapbounds.getWest());
 url=url + ";latmin=" + format5f(mapbounds.getSouth());
 url=url + ";lonmax=" + format5f(mapbounds.getEast());
 url=url + ";latmax=" + format5f(mapbounds.getNorth());
 url=url + ";search=" + encodeURIComponent(search);

 ajaxGET(url,runSearchSuccess);
}


var searchresults=[];

//
// Success in running search.
//

function runSearchSuccess(response)
{
 var lines=response.responseText.split("\n");

 var marker=lines[0];
 var cpuinfo=lines[1];  // not used
 var message=lines[2];

 if(message !== "")
   {
    alert(message);
    return;
   }

 searchresults[marker]=[];

 for(var line=3;line<lines.length;line++)
   {
    var thisline=lines[line];

    if(thisline==="")
       break;

    thisline.match("([-.0-9]+) ([-.0-9]+) (.*)");

    searchresults[marker][searchresults[marker].length]={lat: Number(RegExp.$1), lon: Number(RegExp.$2), name: RegExp.$3};
   }

 if(searchresults[marker].length==1)
   {
    formSetSearch(marker,searchresults[marker][0].name);
    formSetCoords(marker,searchresults[marker][0].lon,searchresults[marker][0].lat);
    markerAddMap(marker);
   }
 else
   {
    var results=document.getElementById("searchresults" + marker);

    var innerHTML="<td colspan=\"3\">";

    for(var n=0;n<searchresults[marker].length;n++)
      {
       if(n>0)
          innerHTML+="<br>";

       innerHTML+="<a href=\"#\" onclick=\"choseSearchResult(" + marker + "," + n + ")\">" +
                  searchresults[marker][n].name +
                  "</a>";
      }

    results.innerHTML=innerHTML;

    results.style.display="";
   }
}


//
// Display search results.
//

function choseSearchResult(marker,n)
{
 if(n>=0)
   {
    formSetSearch(marker,searchresults[marker][n].name);
    formSetCoords(marker,searchresults[marker][n].lon,searchresults[marker][n].lat);
    markerAddMap(marker);
   }
}


//
// Clear search results.
//

function clearSearchResult(marker)
{
 document.getElementById("searchresults" + marker).style.display="none";
}