zhanmingkan
2022-05-16 c8a1a20ba1ca73bef0cc3bbac652014367d05d75
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
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
/**
 * (c) 2013 Jexcel Plugin v1.0.2 | Bossanova UI
 * http://www.github.com/paulhodel/jexcel
 *
 * @author: Paul Hodel <paul.hodel@gmail.com>
 * @description: Create light embedded spreadsheets on your webpages
 * 
 * ROADMAP:
 * Multiple tabs
 * Merged cells
 * Drag and drop rows and columns
 * Custom renderer
 * big data (partial table loading)
 * Pagination
 * Context menu
 */
 
(function( $ ){
 
var methods = {
 
    /**
     * Innitialization, configuration and loading
     * 
     * @param {Object} options configuration
     * @return void
     */
    init : function( options ) {
        // Loading default configuration
        var defaults = {
            colHeaders:[],
            colWidths:[],
            colAlignments:[],
            columns:[],
            minSpareRows:0,
            minSpareCols:0,
        };
 
        // Configuration holder
        var options =  $.extend(defaults, options);
 
        // Id
        var id = $(this).prop('id');
 
        // Main object
        var main = $(this);
 
        // Create
        prepareTable = function () {
            // Register options
            if (! $.fn.jexcel.defaults) {
                $.fn.jexcel.defaults = new Array();
            }
            $.fn.jexcel.defaults[id] = options;
 
            // Create history track array
            $.fn.jexcel.defaults[id].history = new Array();
            $.fn.jexcel.defaults[id].historyIndex = -1;
 
            // Loading initial data from remote sources
            var results = [];
 
            // Data holder cannot be blank
            if (! options.data) {
                options.data = [];
            }
            // Length
            if (! $.fn.jexcel.defaults[id].data.length) {
                $.fn.jexcel.defaults[id].data = [[]];
            }
 
            // Number of columns
            size = options.colHeaders.length;
            if (options.data[0].length > size) {
                size = options.data[0].length;
            }
 
            // Preparations
            for (i = 0; i < size; i++) {
                // Default headers
                if (! options.colHeaders[i]) {
                    options.colHeaders[i] = $.fn.jexcel('getColumnName', i);
                }
                // Default column description
                if (! options.columns[i]) {
                    options.columns[i] = { type:'text' };
                } else if (! options.columns[i]) {
                    options.columns[i].type = 'text';
                }
                if (! options.columns[i].source) {
                    $.fn.jexcel.defaults[id].columns[i].source = [];
                }
                if (! options.columns[i].options) {
                    $.fn.jexcel.defaults[id].columns[i].options = [];
                }
                // Align
                if (! options.colAlignments[i]) {
                    options.colAlignments[i] = 'center';
                }
                // Align
                if (! options.colWidths[i]) {
                    options.colWidths[i] = '50';
                }
 
                // Pre-load initial source for json autocomplete
                if (options.columns[i].type == 'autocomplete' || options.columns[i].type == 'dropdown') {
                    // if remote content
                    if (options.columns[i].url) {
                        results.push($.ajax({
                            url: options.columns[i].url,
                            index: i,
                            dataType:'json',
                            success: function (result) {
                                // Create the dynamic sources
                                $.fn.jexcel.defaults[id].columns[this.index].source = result;
                                // Populate the combo variable
                                $.fn.jexcel.defaults[id].columns[this.index].combo = $(main).jexcel('createCombo', result);
                            }
                        }));
                    } else if (options.columns[i].source) {
                        // Create the dropdown combo based on the source
                        $.fn.jexcel.defaults[id].columns[i].combo = $(main).jexcel('createCombo', options.columns[i].source);
                    }
                } else if (options.columns[i].type == 'calendar') {
                    // Default format for date columns
                    if (! $.fn.jexcel.defaults[id].columns[i].options.format) {
                        $.fn.jexcel.defaults[id].columns[i].options.format = 'DD/MM/YYYY';
                    }
                }
            }
 
            // In case there are external json to be loaded before create the table
            if (results.length > 0) {
                // Waiting all external data is loaded
                $.when.apply(this, results).done(function() {
                    // Create the table
                    $(main).jexcel('createTable');
                });
            } else {
                // No external data to be loaded, just created the table
                $(main).jexcel('createTable');
            }
        }
 
        // Load the table data based on an CSV file
        if (options.csv) {
            if (! $.csv) {
                // Required lib not present
                console.error('Jexcel error: jquery-csv library not loaded');
            } else {
                // Comma as default
                options.delimiter = options.delimiter || ',';
 
                // Load CSV file
                $.ajax({
                    url: options.csv,
                    success: function (result) {
                        var i = 0;
                        // Convert data
                        var data = $.csv.toArrays(result);
 
                        // Headers
                        if (options.csvHeaders == true) {
                            options.colHeaders = data.shift();
                        }
 
                        // Data
                        options.data = data;
 
                        // Prepare table
                        prepareTable();
                    }
                });
            }
        } else {
            // Prepare table
            prepareTable();
        }
    },
 
    /**
     * Create the table
     * 
     * @return void
     */
    createTable : function() {
        // Id
        var id = $(this).prop('id');
 
        // Var options
        var options = $.fn.jexcel.defaults[id];
 
        // Create main table object
        var table = document.createElement('table');
        $(table).prop('class', 'jexcel bossanova-ui');
        $(table).prop('cellpadding', '0');
        $(table).prop('cellspacing', '0');
 
        // Unselectable properties
        $(table).prop('unselectable', 'yes');
        $(table).prop('onselectstart', 'return false');
        $(table).prop('draggable', 'false');
 
        // Create header and body tags
        var thead = document.createElement('thead');
        var tbody = document.createElement('tbody');
 
        // Header
        $(thead).prop('class', 'label');
 
        // Create headers
        var tr = '<td width="30" class="label"></td>';
 
        for (i = 0; i < options.colHeaders.length; i++) {
            // Default header cell properties
            width = options.colWidths[i];
            align = options.colAlignments[i];
            header = options.colHeaders[i];
 
            // Column type hidden
            if (options.columns[i].type == 'hidden') {
                // TODO: when it is first check the whole selection not include
                tr += '<td id="col-' + i + '" style="display:none;">' + options.colHeaders[i] + '</td>';
            } else {
                // Other column types
                tr += '<td id="col-' + i + '" width="' + width + '" align="' + align +'">' + header + '</td>';
            }
        }
 
        // Populate header
        $(thead).html('<tr>' + tr + '</tr>'); 
 
        // TODO: filter row
        //<tr><td></td><td><input type="text"></td></tr>
 
        // Append content
        $(table).append(thead);
        $(table).append(tbody);
 
        // Prevent dragging
        $(table).on('dragstart', function () {
            return false;
        });
 
        // Main object
        $(this).html(table);
 
        // Add the corner square and textarea one time onlly
        if (! $('.jexcel_corner').length) {
            // Corner one for all sheets in a page
            var corner = document.createElement('div');
            $(corner).prop('class', 'jexcel_corner');
            $(corner).prop('id', 'corner');
 
            // Hidden textarea copy and paste helper
            var textarea = document.createElement('textarea');
            $(textarea).prop('class', 'jexcel_textarea');
            $(textarea).prop('id', 'textarea');
 
            // Powered by
            var ads = document.createElement('div');
            $(ads).css('display', 'none');
            $(ads).html('<a href="http://github.com/paulhodel/jexcel">jExcel Spreadsheet</a>');
 
            // Append elements
            $('body').append(corner);
            $('body').append(textarea);
            $('body').append(ads);
 
            // Prevent dragging on the corner object
            $(corner).on('dragstart', function () {
                return false;
            });
 
            // Corner persistence
            $.fn.jexcel.selectedCorner = false;
            $.fn.jexcel.selectedHeader = null;
 
            // Global mouse click down controles
            $(document).on('mousedown', function (e) {
                // Click on corner icon
                if (e.target.id == 'corner') {
                    $.fn.jexcel.selectedCorner = true;
                } else {
                    // Check if the click was in an jexcel element
                    var table = $(e.target).parent().parent().parent();
 
                    // Table found
                    if ($(table).is('.jexcel')) {
 
                        // Get id
                        var current = $(table).parent().prop('id');
 
                        // Remove selection from any other jexcel if applicable
                        if ($.fn.jexcel.current) {
                            if ($.fn.jexcel.current != current) {
                                $('#' + $.fn.jexcel.current).find('td').removeClass('selected highlight highlight-top highlight-left highlight-right highlight-bottom');
                            }
                        }
 
                        // Mark as current
                        $.fn.jexcel.current = current;
 
                        // Header found
                        if ($(e.target).parent().parent().is('thead')) {
                            var o = $(e.target).prop('id');
                            if (o) {
                                o = o.split('-');
 
                                if ($.fn.jexcel.selectedHeader && (e.shiftKey || e.ctrlKey)) {
                                    var d = $($.fn.jexcel.selectedHeader).prop('id').split('-');
                                } else {
                                    // Update selection single column
                                    var d = $(e.target).prop('id').split('-');
                                    // Keep track of which header was selected first
                                    $.fn.jexcel.selectedHeader = $(e.target);
                                }
 
                                 // Get cell objects 
                                var o1 = $('#' + $.fn.jexcel.current).find('#' + o[1] + '-0');
                                var o2 = $('#' + $.fn.jexcel.current).find('#' + d[1] + '-' + parseInt($.fn.jexcel.defaults[$.fn.jexcel.current].data.length - 1));
 
                                // Update selection
                                $('#' + $.fn.jexcel.current).jexcel('updateSelection', o1, o2);
                            }
                        } else {
                            $.fn.jexcel.selectedHeader = false;
                        }
 
                        // Body found
                        if ($(e.target).parent().parent().is('tbody')) {
                            // Update row label selection
                            if ($(e.target).is('.label')) {
                                var o = $(e.target).prop('id').split('-');
 
                                if ($.fn.jexcel.selectedRow && (e.shiftKey || e.ctrlKey)) {
                                    // Updade selection multi columns
                                    var d = $($.fn.jexcel.selectedRow).prop('id').split('-');
                                } else {
                                    // Update selection single column
                                    var d = $(e.target).prop('id').split('-');
                                    // Keep track of which header was selected first
                                    $.fn.jexcel.selectedRow = $(e.target);
                                }
 
                                // Get cell objects 
                                var o1 = $('#' + $.fn.jexcel.current).find('#0-' + o[1]);
                                var o2 = $('#' + $.fn.jexcel.current).find('#' + parseInt($.fn.jexcel.defaults[$.fn.jexcel.current].columns.length - 1) + '-' + d[1]);
 
                                $('#' + $.fn.jexcel.current).jexcel('updateSelection', o1, o2);
                            } else {
                                // Update cell selection
                                if (! $($.fn.jexcel.selectedCell).hasClass('edition')) {
                                    if (! $.fn.jexcel.selectedCell || ! e.shiftKey) {
                                        $.fn.jexcel.selectedCell = $(e.target);
                                    }
                                    $('#' + $.fn.jexcel.current).jexcel('updateSelection', $.fn.jexcel.selectedCell, $(e.target));
                                } else {
                                    if ($(e.target) != $.fn.jexcel.selectedCell) {
                                        $.fn.jexcel.selectedCell = $(e.target);
                                        $('#' + $.fn.jexcel.current).jexcel('updateSelection', $.fn.jexcel.selectedCell, $(e.target));
                                    }
                                }
 
                                // No full row selected
                                $.fn.jexcel.selectedRow = null;
                            }
                        }
                    } else {
                        // Check if the object is in the jexcel domain
                        if (! $(e.target).parents('.jexcel').length) {
                            // Remove selection from any other jexcel if applicable
                            if ($.fn.jexcel.current) {
                                $('#' + $.fn.jexcel.current).find('td').removeClass('selected highlight highlight-top highlight-left highlight-right highlight-bottom');
                            }
 
                            // Hide corner
                            $(corner).css('top', '-200px');
                            $(corner).css('left', '-200px');
 
                            // Reset controls
                            $.fn.jexcel.current = null;
                            $.fn.jexcel.selectedCell = null;
                            $.fn.jexcel.selectedRow = null;
                            $.fn.jexcel.selectedHeader = null;
                        }
                    }
                }
            });
 
            // Global mouse click up controles 
            $(document).mouseup(function (o) {
                // Cancel any corner selection
                $.fn.jexcel.selectedCorner = false;
 
                // Data to be copied
                var selection = $('#' + $.fn.jexcel.current).find('tbody td.selection');
 
                if ($(selection).length > 0) {
                    // First and last cells
                    var o = $(selection[0]).prop('id').split('-');
                    var d = $(selection[selection.length - 1]).prop('id').split('-');
 
                    // Copy data
                    $('#' + $.fn.jexcel.current).jexcel('copyData', o, d);
 
                    // Remove selection
                    $(selection).removeClass('selection selection-left selection-right selection-top selection-bottom');
                }
            });
 
            // Double click
            $(document).on('dblclick', function (e) {
                // Jexcel is selected
                if ($.fn.jexcel.current) {
                    // Corner action
                    if (e.target.id == 'corner') {
                        var selection = $('#' + $.fn.jexcel.current).find('tbody td.highlight');
                        // Any selected cells
                        if (typeof(selection) == 'object') {
                            // Get selected cells
                            var o = $(selection[0]).prop('id').split('-');
                            var d = $(selection[selection.length - 1]).prop('id').split('-');
                            // Double click copy
                            o[1] = parseInt(d[1]) + 1;
                            d[1] = parseInt($.fn.jexcel.defaults[$.fn.jexcel.current].data.length);
                            // Do copy
                            $('#' + $.fn.jexcel.current).jexcel('copyData', o, d);
                        }
                    }
 
                    // Header found
                    if ($(e.target).parent().parent().is('thead')) {
                        var o = $(e.target).prop('id');
                        if (o) {
                            o = $(e.target).prop('id').split('-');
                            // Find current status
                            var c = $(e.target).parent().parent();
                            var d = $(e.target).find('.arrow-down');
                            // Remove any ordering style
                            $(c).find('.arrow-down').remove();
                            $(c).find('.arrow-up').remove();
                            $(e.target).parent().parent().find('td').css('text-decoration', 'none');
                            // Set new order
                            if ($(d).length > 0) {
                                $(e.target).append("<span class='arrow-up'></span>");
                                $('#' + $.fn.jexcel.current).jexcel('orderBy', o[1], 1);
                            } else {
                                $(e.target).append("<span class='arrow-down'></span>");
                                $('#' + $.fn.jexcel.current).jexcel('orderBy', o[1], 0);
                            }
                            // Header style
                            $(e.target).css('text-decoration', 'underline');
 
                            // Hide corner
                            $(corner).css('top', '-200px');
                            $(corner).css('left', '-200px');
                        }
                    }
 
                    // Open editor action
                    if ($(e.target).is('.highlight')) {
                        $('#' + $.fn.jexcel.current).jexcel('openEditor', $(e.target));
                    }
                }
            });
 
            $(document).on('mouseover', function (e) {
                // Get jexcel table
                var table = $(e.target).closest('.jexcel');
 
                // If the user is in the current table
                if ($.fn.jexcel.current == $(table).parent().prop('id')) {
                    // Header found
                    if ($(e.target).parent().parent().is('thead')) {
                        if ($.fn.jexcel.selectedHeader) {
                            // Updade selection
                            if (e.buttons) {
                                var o = $($.fn.jexcel.selectedHeader).prop('id');
                                var d = $(e.target).prop('id');
                                if (o && d) {
                                    o = o.split('-');
                                    d = d.split('-');
                                    // Get cell objects 
                                    var o1 = $('#' + $.fn.jexcel.current).find('#' + o[1] + '-0');
                                    var o2 = $('#' + $.fn.jexcel.current).find('#' + d[1] + '-' + parseInt($.fn.jexcel.defaults[$.fn.jexcel.current].data.length - 1));
                                    // Update selection
                                    $('#' + $.fn.jexcel.current).jexcel('updateSelection', o1, o2);
                                }
                            }
                        }
                    }
 
                    // Body found
                    if ($(e.target).parent().parent().is('tbody')) {
                        // Update row label selection
                        if ($(e.target).is('.label')) {
                            if ($.fn.jexcel.selectedRow) {
                                // Updade selection
                                if (e.buttons) {
                                    var o = $($.fn.jexcel.selectedRow).prop('id');
                                    var d = $(e.target).prop('id');
                                    if (o && d) {
                                        o = o.split('-');
                                        d = d.split('-');
                                        // Get cell objects 
                                        var o1 = $('#' + $.fn.jexcel.current).find('#0-' + o[1]);
                                        var o2 = $('#' + $.fn.jexcel.current).find('#' + parseInt($.fn.jexcel.defaults[$.fn.jexcel.current].columns.length - 1) + '-'  + d[1]);
                                        // Update selection
                                        $('#' + $.fn.jexcel.current).jexcel('updateSelection', o1, o2);
                                    }
                                }
                            }
                        } else {
                            if ($.fn.jexcel.selectedCell) {
                                if (! $($.fn.jexcel.selectedCell).hasClass('edition')) {
                                    if ($.fn.jexcel.selectedCorner == true) {
                                        // Copy option
                                        $('#' + $.fn.jexcel.current).jexcel('updateCornerSelection', $(e.target));
                                    } else {
                                        // Updade selection
                                        if (e.buttons) {
                                            $('#' + $.fn.jexcel.current).jexcel('updateSelection', $.fn.jexcel.selectedCell, $(e.target));
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            });
 
            // Copy data from the table in excel format
            $(document).on('copy', function(e) {
                if ($.fn.jexcel.current) {
                    // Copy data
                    $('#' + $.fn.jexcel.current).jexcel('copy', true);
                }
            });
 
            // Cut data from the table in excel format
            $(document).on('cut', function() {
                if ($.fn.jexcel.current) {
                    // Cut data
                    $('#' + $.fn.jexcel.current).jexcel('cut');
                }
            });
 
            // Paste data from excel format to the table
            $(document).on('paste', function(e) {
                if ($.fn.jexcel.current) {
                    $('#' + $.fn.jexcel.current).jexcel('paste', $.fn.jexcel.selectedCell, e.originalEvent.clipboardData.getData('text'));
                }
            });
 
            // Keyboard controls
            var keyBoardCell = null;
 
            $(document).keydown(function(e) {
                if ($.fn.jexcel.current) {
                    // Support variables
                    var cell = null;
                    // Get current cell
                    if ($.fn.jexcel.selectedCell) {
                        columnId = $($.fn.jexcel.selectedCell).prop('id').split('-');
 
                        // Which key
                        if (e.which == 37) {
                            // Left arrow
                            if (! $($.fn.jexcel.selectedCell).hasClass('edition')) {
                                if (e.ctrlKey) {
                                    cell = $($.fn.jexcel.selectedCell).parent().find('td').not('.label').first();
                                } else {
                                    cell = $($.fn.jexcel.selectedCell).prev();
                                }
                            }
                            e.preventDefault();
                        } else if (e.which == 39) {
                            // Right arrow
                            if (! $($.fn.jexcel.selectedCell).hasClass('edition')) {
                                if (e.ctrlKey) {
                                    cell = $($.fn.jexcel.selectedCell).parent().find('td').last();
                                } else {
                                    cell = $($.fn.jexcel.selectedCell).next();
                                }
                            }
                            e.preventDefault();
                        } else if (e.which == 38) {
                            // Top arrow
                            if (! $($.fn.jexcel.selectedCell).hasClass('edition')) {
                                if (e.ctrlKey) {
                                    cell = $($.fn.jexcel.selectedCell).parent().parent().find('tr').first().find('#' + columnId[0] + '-' + 0);
                                } else {
                                    cell = $($.fn.jexcel.selectedCell).parent().prev().find('#' + columnId[0] + '-' + (columnId[1] - 1));
                                }
                            }
                            e.preventDefault();
                        } else if (e.which == 40) {
                            // Bottom arrow
                            if (! $($.fn.jexcel.selectedCell).hasClass('edition')) {
                                if (e.ctrlKey) {
                                    cell = $($.fn.jexcel.selectedCell).parent().parent().find('tr').last().find('#' + columnId[0] + '-' + ($.fn.jexcel.defaults[$.fn.jexcel.current].data.length - 1));
                                } else {
                                    cell = $($.fn.jexcel.selectedCell).parent().next().find('#' + columnId[0] + '-' + (parseInt(columnId[1]) + 1));
                                }
                            }
                            e.preventDefault();
                        } else if (e.which == 27) {
                            // Escape
                            if ($($.fn.jexcel.selectedCell).hasClass('edition')) {
                                // Exit without saving
                                $('#' + $.fn.jexcel.current).jexcel('closeEditor', $($.fn.jexcel.selectedCell), false);
                            }
                        } else if (e.which == 13) {
                            // Edition in progress
                            if ($($.fn.jexcel.selectedCell).hasClass('edition')) {
                                // Exit saving data
                                if ($.fn.jexcel.defaults[$.fn.jexcel.current].columns[columnId[0]].type == 'calendar') {
                                    $('#' + $.fn.jexcel.current).find('editor').jcalendar('close', 1)
                                } else {
                                    $('#' + $.fn.jexcel.current).jexcel('closeEditor', $($.fn.jexcel.selectedCell), true);
                                }
                            }
                            // If not edition check if the selected cell is in the last row
                            if (columnId[1] == $.fn.jexcel.defaults[$.fn.jexcel.current].data.length - 1) {
                                // New record in case selectedCell in the last row
                                $('#' + $.fn.jexcel.current).jexcel('insertRow');
                            }
                            // Go to the next line
                            cell = $($.fn.jexcel.selectedCell).parent().next().find('#' + columnId[0] + '-' + (parseInt(columnId[1]) + 1));
                            e.preventDefault();
                        } else if (e.which == 9) {
                            // Edition in progress
                            if ($($.fn.jexcel.selectedCell).hasClass('edition')) {
                                // Exit saving data
                                if ($.fn.jexcel.defaults[$.fn.jexcel.current].columns[columnId[0]].type == 'calendar') {
                                    $('#' + $.fn.jexcel.current).find('editor').jcalendar('close', 1)
                                } else {
                                    $('#' + $.fn.jexcel.current).jexcel('closeEditor', $($.fn.jexcel.selectedCell), true);
                                }
                            }
                            // Tab key - Get the id of the selected cell
                            if (columnId[0] == $.fn.jexcel.defaults[$.fn.jexcel.current].data[0].length - 1) {
                                // New record in case selectedCell in the last column
                                $('#' + $.fn.jexcel.current).jexcel('insertColumn');
                            }
                            // Highlight new column
                            if (! $($.fn.jexcel.selectedCell).hasClass('edition')) {
                               cell = $($.fn.jexcel.selectedCell).next();
                            }
                            e.preventDefault();
                        } else if (e.which == 46) {
                            // Delete (erase cell in case no edition is running)
                            if (! $($.fn.jexcel.selectedCell).hasClass('edition')) {
                                $('#' + $.fn.jexcel.current).jexcel('setValue', $('#' + $.fn.jexcel.current).find('.highlight'), '');
                            }
                        } else {
                            if (! e.shiftKey && ! e.ctrlKey) {
                                if ($.fn.jexcel.selectedCell) {
                                    // If is not readonly
                                    if ($.fn.jexcel.defaults[$.fn.jexcel.current].columns[columnId[0]].type != 'readonly') {
                                        // Start edition in case a valid character. 
                                        if (! $($.fn.jexcel.selectedCell).hasClass('edition')) {
                                            // TODO: check the sample characters able to start a edition
                                            if (/[a-zA-Z0-9]/.test(String.fromCharCode(e.keyCode))) {
                                                $('#' + $.fn.jexcel.current).jexcel('openEditor', $($.fn.jexcel.selectedCell), true);
                                            }
                                        }
                                    }
                                }
                            } else if (! e.shiftKey && e.ctrlKey) {
                                if (e.which == 65) {
                                    // Ctrl + A
                                    t = $(this).find('.jexcel tbody td').not('.label');
                                    o = $(t).first();
                                    t = $(t).last();
                                    $('#' + $.fn.jexcel.current).jexcel('updateSelection', o, t);
                                    // Prevent page selection
                                    e.preventDefault();
                                } else if (e.which == 83) {
                                    // Ctrl + S
                                    $('#' + $.fn.jexcel.current).jexcel('download');
                                    // Prevent page selection
                                    e.preventDefault();
                                } else if (e.which == 89) {
                                    // Ctrl + Y
                                    if (!$($.fn.jexcel.selectedCell).hasClass('edition')) {
                                        $('#' + $.fn.jexcel.current).jexcel('redo');
                                    }
                                    e.preventDefault();
                                } else if (e.which == 90) {
                                    // Ctrl + Z
                                    if (!$($.fn.jexcel.selectedCell).hasClass('edition')) {
                                        $('#' + $.fn.jexcel.current).jexcel('undo');
                                    }
                                    e.preventDefault();
                                }
                            }
                        }
 
                        // Arrows control
                        if (cell) {
                            // Control selected cell
                            if ($(cell).length > 0 && $(cell).prop('id').substr(0,3) != 'row') {
                                // In case of a multiple cell selection
                                if (e.shiftKey) {
                                    // Keep first selected cell
                                    if (! keyBoardCell) {
                                        keyBoardCell = $.fn.jexcel.selectedCell;
                                    }
 
                                    // Origin cell
                                    o = keyBoardCell;
                                } else if (e.ctrlKey) {
                                    // Remove previous cell
                                    keyBoardCell = null;
 
                                    o = cell;
                                } else {
                                    // Remove previous cell
                                    keyBoardCell = null;
 
                                    // Origin cell
                                    o = cell;
                                }
 
                                // Target cell
                                t = cell;
 
                                // Current cell
                                $.fn.jexcel.selectedCell = cell;
 
                                // Focus
                                $(cell).focus();
 
                                // Update selection
                                $('#' + $.fn.jexcel.current).jexcel('updateSelection', o, t);
                            }
                        }
                    }
                }
            });
        }
 
        // Load data
        $(this).jexcel('setData');
    },
 
    /**
     * Set data
     * 
     * @param array data In case no data is sent, default is reloaded
     * @return void
     */
    setData : function(data) {
        // Id
        var id = $(this).prop('id');
 
        // Update data
        if (data) {
            if (typeof(data) == 'string') {
                data = JSON.parse(data);
            }
 
            $.fn.jexcel.defaults[id].data = data;
        }
 
        // Dynamic columns
        $.fn.jexcel.defaults[id].dynamicColumns = [];
 
        // Data container
        var tbody = $(this).find('tbody');
 
        // Reset data
        $(tbody).html('');
 
        // Create cells
        for (j = 0; j < $.fn.jexcel.defaults[id].data.length; j++) {
            // New line of data to be append in the table
            tr = document.createElement('tr');
            // Index column
            $(tr).append('<td id="row-' + j + '" class="label">' + parseInt(j + 1) + '</td>'); 
            // Data columns
            for (i = 0; i < $.fn.jexcel.defaults[id].colHeaders.length; i++) {
                // New column of data to be append in the line
                td = $(this).jexcel('createCell', i, j);
 
                // Add column to the row
                $(tr).append(td);
            }
 
            // Add row to the table body
            $(tbody).append(tr);
        }
 
        // Dynamic updates
        if ($.fn.jexcel.defaults[id].dynamicColumns.length > 0) {
            $(this).jexcel('formula');
        }
 
        // Table is ready
        if (typeof($.fn.jexcel.defaults[id].onload) == 'function') {
            $.fn.jexcel.defaults[id].onload($(this));
        }
    },
 
    /**
     * Update table settings helper. Update cells after loading
     * 
     * @param methods
     * @return void
     */
    updateSettings : function(options) {
        // Id
        var id = $(this).prop('id');
 
        // Keep options
        if (! options) {
            if ($.fn.jexcel.defaults[id].updateSettingsOptions) {
                options = $.fn.jexcel.defaults[id].updateSettingsOptions;
            }
        }
 
        // Go through all cells
        if (typeof(options) == 'object') {
            $.fn.jexcel.defaults[id].updateSettingsOptions = options;
            var cells = $(this).find('.jexcel tbody td').not('.label');
            if (typeof(options.cells) == 'function') {
                $.each(cells, function (k, v) {
                    id = $(v).prop('id').split('-');
                    options.cells($(v), id[0], id[1]);
                });
            }
        }
    },
 
    /**
     * Open the editor
     * 
     * @param object cell
     * @return void
     */
    openEditor : function(cell, empty) {
        // Id
        var id = $(this).prop('id');
 
        // Main
        var main = $(this);
 
        // Options
        var options = $.fn.jexcel.defaults[id];
 
        // Get cell position
        var position = $(cell).prop('id').split('-');
 
        // Readonly
        if ($(cell).hasClass('readonly') == true) {
            // Do nothing
        } else {
            // Holder
            $.fn.jexcel.edition = $(cell).html();
 
            // Start recording undo/redo history
            $(this).jexcel('startNewHistoryRecord');
 
            // If there is a custom editor for it
            if (options.columns[position[0]].editor) {
                // Keep the current value
                $(cell).addClass('edition');
 
                // Custom editors
                options.columns[position[0]].editor.openEditor(cell);
            } else {
                // Native functions
                if (options.columns[position[0]].type == 'checkbox' || options.columns[position[0]].type == 'hidden') {
                    // Do nothing for checkboxes or hidden columns
                } else if (options.columns[position[0]].type == 'dropdown') {
                    // Keep the current value
                    $(cell).addClass('edition');
 
                    // Create dropdown
                    var source = options.columns[position[0]].source;
 
                    var html = '<select>';
                    for (i = 0; i < source.length; i++) {
                        if (typeof(source[i]) == 'object') {
                            k = source[i].id;
                            v = source[i].name;
                        } else {
                            k = source[i];
                            v = source[i];
                        }
                        html += '<option value="' + k + '">' + v + '</option>';
                    }
                    html += '</select>';
 
                    // Get current value
                    var value = $(cell).find('input').val();
 
                    // Open editor
                    $(cell).html(html);
 
                    // Editor configuration
                    var editor = $(cell).find('select');
                    $(editor).change(function () {
                        $(main).jexcel('closeEditor', $(this).parent(), true);
                    });
                    $(editor).blur(function () {
                        $(main).jexcel('closeEditor', $(this).parent(), true);
                    });
                    
                    $(editor).focus();
                    if (value) {
                        $(editor).val(value);
                    }
                } else if (options.columns[position[0]].type == 'calendar') {
                    $(cell).addClass('edition');
 
                    // Get content
                    var value = $(cell).find('input').val();
 
                    // Basic editor
                    var editor = document.createElement('input');
                    $(editor).prop('class', 'editor');
                    $(editor).css('width', $(cell).width());
                    $(editor).val($(cell).text());
                    $(cell).html(editor);
                    $(cell).find('');
                    $(cell).focus();
 
                    options.columns[position[0]].options.onclose = function () {
                        $(main).jexcel('closeEditor', $(cell), true);
                    }
 
                    // Current value
                    $(editor).jcalendar(options.columns[position[0]].options);
                    $(editor).jcalendar('open', value);
                } else if (options.columns[position[0]].type == 'autocomplete') {
                    // Keep the current value
                    $(cell).addClass('edition');
 
                    // Get content
                    var html = $(cell).text();
                    var value = $(cell).find('input').val();
 
                    // Basic editor
                    var editor = document.createElement('input');
                    $(editor).prop('class', 'editor');
                    $(editor).css('width', $(cell).width());
 
                    // Results
                    var result = document.createElement('div');
                    $(result).prop('class', 'results');
                    if (html) {
                       $(result).html('<li id="' + value + '">' + html + '</li>');
                    } else {
                       $(result).css('display', 'none');
                    }
 
                    // Search
                    var timeout = null;
                    $(editor).on('keyup', function () {
                        // String
                        var str = $(this).val();
 
                        // Timeout
                        if (timeout) {
                            clearTimeout(timeout)
                        }
 
                        // Delay search
                        timeout = setTimeout(function () { 
                            // Object
                            $(result).html('');
                            // List result
                            showResult = function(data, str) {
                                // Create options
                                $.each(data, function(k, v) {
                                    if (typeof(v) == 'object') {
                                        name = v.name;
                                        id = v.id;
                                    } else {
                                        name = v;
                                        id = v;
                                    }
 
                                    if (name.toLowerCase().indexOf(str.toLowerCase()) != -1) {
                                        li = document.createElement('li');
                                        $(li).prop('id', id)
                                        $(li).html(name);
                                        $(li).mousedown(function (e) {
                                            // TODO: avoid other selection in this handler.
                                            $(cell).html(this);
                                            $(main).jexcel('closeEditor', $(cell), true);
                                        });
                                        $(result).append(li);
                                    }
                                });
 
                                if (! $(result).html()) {
                                    $(result).html('<div style="padding:6px;">No result found</div>');
                                }
                                $(result).css('display', '');
                            }
 
                            // Search
                            if (options.columns[position[0]].url) {
                                $.getJSON (options.columns[position[0]].url + '?q=' + str + '&r=' + $(main).jexcel('getRowData', position[1]), function (data) {
                                    showResult(data, str);
                                });
                            } else if (options.columns[position[0]].source) {
                                showResult(options.columns[position[0]].source, str);
                            }
                        }, 500);
                    });
                    $(cell).html(editor);
                    $(cell).append(result);
 
                    // Current value
                    $(editor).focus();
                    $(editor).val('');
 
                    // Close editor handler
                    $(editor).blur(function () {
                        $(main).jexcel('closeEditor', $(cell), false);
                    });
                } else {
                    // Keep the current value
                    $(cell).addClass('edition');
 
                    var input = $(cell).find('input');
 
                    // Get content
                    if ($(input).length) {
                        var html = $(input).val();
                    } else {
                        var html = $(cell).html();
                    }
 
                    // Basic editor
                    var editor = document.createElement('input');
                    $(editor).prop('class', 'editor');
                    $(editor).css('width', $(cell).width());
                    $(cell).html(editor);
 
                    // Bind mask
                    if (options.columns[position[0]].mask) {
                        if (! $.fn.masked) {
                            console.error('Jexcel: it was not possible to load the mask plugin.');
                        } else {
                            $(editor).mask(options.columns[position[0]].mask, options.columns[position[0]].options)
                        }
                    }
 
                    // Current value
                    $(editor).focus();
                    if (! empty) {
                        $(editor).val(html);
                    }
 
                    // Close editor handler
                    $(editor).blur(function () {
                        $(main).jexcel('closeEditor', $(this).parent(), true);
                    });
                }
            }
        }
    },
 
    /**
     * Close the editor and save the information
     * 
     * @param object cell
     * @param boolean save
     * @return void
     */
    closeEditor : function(cell, save) {
        // Remove edition mode mark
        $(cell).removeClass('edition');
 
        // Id
        var id = $(this).prop('id');
 
        // Options
        var options = $.fn.jexcel.defaults[id];
 
        // Cell identification
        var position = $(cell).prop('id').split('-');
 
        // Get cell properties
        if (save == true) {
            // Before change
            if (typeof(options.columns[position[0]].onbeforechange) == 'function') {
                options.columns[position[0]].onbeforechange($(this), $(cell));
            }
 
            // If custom editor
            if (options.columns[position[0]].editor) {
                // Custom editor
                options.columns[position[0]].editor.closeEditor(cell, save);
            } else {
                // Native functions
                if (options.columns[position[0]].type == 'checkbox' || options.columns[position[0]].type == 'hidden') {
                    // Do nothing
                } else if (options.columns[position[0]].type == 'dropdown') {
                    // Get value
                    var value = $(cell).find('select').val();
                    var text = $(cell).find('select').find('option:selected').text();
                    // Set value
                    $(cell).html('<input type="hidden" value="' + value + '">' + text);
                } else if (options.columns[position[0]].type == 'autocomplete') {
                    // Set value
                    var obj = $(cell).find('li');
                    if (obj.length > 0) {
                        var value = $(cell).find('li').prop('id');
                        var text = $(cell).find('li').html();
                        $(cell).html('<input type="hidden" value="' + value + '">' + text);
                    } else {
                        $(cell).html('');
                    }
                } else if (options.columns[position[0]].type == 'calendar') {
                    var value = $(cell).find('.jcalendar_value').val();
                    var text = $(cell).find('.jcalendar_input').val();
                    $(cell).html('<input type="hidden" value="' + value + '">' + text);
                } else {
                    // Get content
                    var value = $(cell).find('.editor').val();
                    // For formulas
                    if (value.substr(0,1) == '=') {
                        if ($.fn.jexcel.defaults[id].dynamicColumns.indexOf($(cell).prop('id')) == -1) {
                            $.fn.jexcel.defaults[id].dynamicColumns.push($(cell).prop('id'));
                        }
                    }
                    $(cell).html(value);
                }
            }
 
            // Get value from column and set the default
            $.fn.jexcel.defaults[id].data[position[1]][position[0]] = $(this).jexcel('getValue', $(cell));
 
            // Change
            if (typeof(options.onchange) == 'function') {
                options.onchange($(this), $(cell), value);
            }
 
            // After changes
            $(this).jexcel('afterChange');
 
            // Save history for undo/redo
            $(this).jexcel('storeCellChange', cell, value, $.fn.jexcel.edition);
 
            // Sparerows and sparecols configuration
            if (options.minSpareCols > 0) {
                if (position[0] == $.fn.jexcel.defaults[id].data[0].length - 1) {
                    $('#' + $.fn.jexcel.current).jexcel('insertColumn', options.minSpareCols);
                }
            }
            if (options.minSpareRows > 0) {
                if (position[1] == $.fn.jexcel.defaults[id].data.length - 1) {
                    $('#' + $.fn.jexcel.current).jexcel('insertRow', options.minSpareRows);
                }
            }
        } else {
            if (options.columns[position[0]].type == 'calendar') {
                // Do nothing - calendar will be closed without keeping the current value
            } else {
                // Restore value
                $(cell).html($.fn.jexcel.edition);
 
                // Finish temporary edition
                $.fn.jexcel.edition = null;
            }
 
            // Discard undo/redo record
            $(this).jexcel('discardCurrentHistoryRecord');
        }
    },
 
    /**
     * Get the value from a cell
     * 
     * @param object cell
     * @return string value
     */
    getValue : function(cell) {
        var value = null;
 
        // If is a string get the cell object
        if (typeof(cell) != 'object') {
            // Convert in case name is excel liked ex. A10, BB92
            cell = $(this).jexcel('getIdFromColumnName', cell);
            // Get object based on a string ex. 12-1, 13-3
            cell = $(this).find('[id=' + cell +']');
        }
 
        // If column exists
        if ($(cell).length) {
            // Id
            var id = $(this).prop('id');
 
            // Global options
            var options = $.fn.jexcel.defaults[id];
 
            // Configuration
            var position = $(cell).prop('id').split('-');
 
            // Get value based on the type
            if (options.columns[position[0]].editor) {
                // Custom editor
                value = options.columns[position[0]].editor.getValue(cell);
            } else {
                // Native functions
                if (options.columns[position[0]].type == 'checkbox') {
                    // Get checkbox value
                    value = $(cell).find('input').is(':checked') ? '1' : '0';
                } else if (options.columns[position[0]].type == 'dropdown' || options.columns[position[0]].type == 'autocomplete' || options.columns[position[0]].type == 'calendar') {
                    // Get value
                    value = $(cell).find('input').val();
                } else if (options.columns[position[0]].type == 'currency') {
                    value = $(cell).html().replace( /\D/g, '');
                } else {
                    // Get default value
                    value = $(cell).find('input');
                    if ($(value).length) {
                        value = $(value).val(); 
                    } else {
                        value = $(cell).html();
                    }
                }
            }
        }
 
        return value;
    },
 
    /**
     * Set a cell value
     * 
     * @param object cell destination cell
     * @param object value value
     * @return void
     */
    setValue : function(cell, value, ignoreEvents) {
        // If is a string get the cell object
        if (typeof(cell) !== 'object') {
            // Convert in case name is excel liked ex. A10, BB92
            cell = $(this).jexcel('getIdFromColumnName', cell);
            // Get object based on a string ex. 12-1, 13-3
            cell = $(this).find('[id=' + cell +']');
        }
 
        // If column exists
        if ($(cell).length) {
            // Id
            var id = $(this).prop('id');
 
            // Main object
            var main = $(this);
 
            // Global options
            var options = $.fn.jexcel.defaults[id];
 
            // Go throw all cells
            $.each(cell, function(k, v) {
                // Cell identification
                var position = $(v).prop('id').split('-');
 
                // Before Change
                if (! ignoreEvents) {
                    if (typeof(options.columns[position[0]].onbeforechange) == 'function') {
                        options.columns[position[0]].onbeforechange($(this), $(v));
                    }
                }
 
                if (options.columns[position[0]].editor) {
                    // Custom editor
                    options.columns[position[0]].editor.setValue(v, value);
                } else if (options.columns[position[0]].readOnly == true) {
                    // Do nothing
                    value = null;
                } else {
                    // Native functions
                    if (options.columns[position[0]].type == 'checkbox') {
                        if (value == 1 || value == true) {
                            $(v).find('input').prop('checked', true);
                        } else {
                            $(v).find('input').prop('checked', false);
                        }
                    } else if (options.columns[position[0]].type == 'dropdown' || options.columns[position[0]].type == 'autocomplete') {
                        // Dropdown and autocompletes
                        key = '';
                        val = '';
                        if (value) {
                            if (options.columns[position[0]].combo[value]) {
                                key = value;
                                val = options.columns[position[0]].combo[value];
                            } else {
                                value = null;
                            }
                        }
 
                        $(v).html('<input type="hidden" value="' +  key + '">' + val);
                    } else if (options.columns[position[0]].type == 'calendar') {
                        val = '';
                        if (value != 'undefined') {
                            val = $.fn.jcalendar('label', value);
                        } else {
                            val = '';
                        }
                        $(v).html('<input type="hidden" value="' + value + '">' + val);
                    } else {
                        if (value) {
                            if (value.substr(0,1) == '=') {
                                if ($.fn.jexcel.defaults[id].dynamicColumns.indexOf($(cell).prop('id')) == -1) {
                                    $.fn.jexcel.defaults[id].dynamicColumns.push($(cell).prop('id'));
                                }
                            }
                        }
 
                        $(v).html(value);
                    }
                }
 
                // Get value from column and set the default
                $.fn.jexcel.defaults[id].data[position[1]][position[0]] = value;
 
                // Change
                if (! ignoreEvents) {
                    if (typeof(options.onchange) == 'function') {
                        options.onchange($(this), $(v), value);
                    }
                }
            });
 
            // After changes
            if (! ignoreEvents) {
                $(this).jexcel('afterChange');
            }
 
            return true;
        } else {
            return false;
        }
    },
 
    /**
     * Update the cells selection
     * 
     * @param object o cell origin
     * @param object d cell destination
     * @return void
     */
    updateSelection : function(o, d) {
        // Main table
        var main = $(this);
 
        // Cells
        var cells = $(this).find('tbody td');
        var header = $(this).find('thead td');
 
        // Remove highlight
        $(cells).removeClass('highlight');
        $(cells).removeClass('highlight-left');
        $(cells).removeClass('highlight-right');
        $(cells).removeClass('highlight-top');
        $(cells).removeClass('highlight-bottom');
 
        // Update selected column
        $(header).removeClass('selected');
        $(cells).removeClass('selected');
        $(o).addClass('selected');
 
        // Define coordinates
        o = $(o).prop('id').split('-');
        d = $(d).prop('id').split('-');
 
        if (parseInt(o[0]) < parseInt(d[0])) {
            px = parseInt(o[0]);
            ux = parseInt(d[0]);
        } else {
            px = parseInt(d[0]);
            ux = parseInt(o[0]);
        }
 
        if (parseInt(o[1]) < parseInt(d[1])) {
            py = parseInt(o[1]);
            uy = parseInt(d[1]);
        } else {
            py = parseInt(d[1]);
            uy = parseInt(o[1]);
        }
 
        // Redefining styles
        for (i = px; i <= ux; i++) {
            for (j = py; j <= uy; j++) {
                $(this).find('#' + i + '-' + j).addClass('highlight');
                $(this).find('#' + px + '-' + j).addClass('highlight-left');
                $(this).find('#' + ux + '-' + j).addClass('highlight-right');
                $(this).find('#' + i + '-' + py).addClass('highlight-top');
                $(this).find('#' + i + '-' + uy).addClass('highlight-bottom');
 
                // Row and column headers
                $(main).find('#col-' + i).addClass('selected');
                $(main).find('#row-' + j).addClass('selected');
            }
        }
 
        // Find corner cell
        $(this).jexcel('updateCornerPosition');
    },
 
    /**
     * Update the cells move data TODO: copy multi columns - TODO!
     *
     * @param object o cell origin
     * @param object d cell destination
     * @return void
     */
    updateCornerSelection : function(current) {
        // Main table
        var main = $(this);
 
        // Remove selection
        var cells = $(this).find('tbody td');
        $(cells).removeClass('selection');
        $(cells).removeClass('selection-left');
        $(cells).removeClass('selection-right');
        $(cells).removeClass('selection-top');
        $(cells).removeClass('selection-bottom');
 
        // Get selection
        var selection = $(this).find('tbody td.highlight');
 
        // Get elements first and last
        var s = $(selection[0]).prop('id').split('-');
        var d = $(selection[selection.length - 1]).prop('id').split('-');
 
        // Get current
        var c = $(current).prop('id').split('-');
 
        // Vertical copy
        if (c[1] > d[1] || c[1] < s[1]) {
            // Vertical
            var px = parseInt(s[0]);
            var ux = parseInt(d[0]);
            if (parseInt(c[1]) > parseInt(d[1])) {
                var py = parseInt(d[1]) + 1;
                var uy = parseInt(c[1]);
            } else {
                var py = parseInt(c[1]);
                var uy = parseInt(s[1]) - 1;
            }
        } else if (c[0] > d[0] || c[0] < s[0]) {
            // Horizontal copy
            var py = parseInt(s[1]);
            var uy = parseInt(d[1]);
            if (parseInt(c[0]) > parseInt(d[0])) {
                var px = parseInt(d[0]) + 1;
                var ux = parseInt(c[0]);
            } else {
                var px = parseInt(c[0]);
                var ux = parseInt(s[0]) - 1;
            }
        }
 
        for (j = py; j <= uy; j++) {
            for (i = px; i <= ux; i++) {
                $(this).find('#' + i + '-' + j).addClass('selection');
                $(this).find('#' + i + '-' + py).addClass('selection-top');
                $(this).find('#' + i + '-' + uy).addClass('selection-bottom');
                $(this).find('#' + px + '-' + j).addClass('selection-left');
                $(this).find('#' + ux + '-' + j).addClass('selection-right');
            }
        }
 
        //$(this).jexcel('updateCornerPosition');
    },
 
    /**
     * Update corner position
     * 
     * @return void
     */
    updateCornerPosition : function() {
        var cells = $(this).find('.highlight');
        if ($(cells).length) { 
            corner = $(cells).last();
 
            // Get the position of the corner helper
            var t = parseInt($(corner).offset().top) + $(corner).height() + 5;
            var l = parseInt($(corner).offset().left) + $(corner).width() + 5;
 
            // Place the corner in the correct place
            $('.jexcel_corner').css('top', t);
            $('.jexcel_corner').css('left', l);
        }
    },
 
    /**
     * Get the data from a row
     * 
     * @param integer row number
     * @return string value
     */
    getRowData : function(row) {
       // Get row
       row = $(this).find('#row-' + row).parent().find('td').not(':first');
 
       // String
       var str = '';
 
       // Search all tds in a row
       if (row.length > 0) {
          for (i = 0; i < row.length; i++) {
             str += $(this).jexcel('getValue', $(row)[i]) + ',';
          }
       }
 
       return str;
    },
 
    /**
     * Get the whole table data
     * 
     * @param integer row number
     * @return string value
     */
    getData : function(highlighted) {
        // Control vars
        var dataset = [];
        var px = 0;
        var py = 0;
 
        // Column and row length
        var x = $(this).find('thead tr td').not(':first').length;
        var y = $(this).find('tbody tr').length;
 
        // Go through the columns to get the data
        for (j = 0; j < y; j++) {
            px = 0;
            for (i = 0; i < x; i++) {
                // Cell
                cell = $(this).find('#' + i + '-' + j);
 
                // Cell selected or fullset
                if (! highlighted || $(cell).hasClass('highlight')) {
                    // Get value
                    if (! dataset[py]) {
                        dataset[py] = [];
                    }
                    dataset[py][px] = $(this).jexcel('getValue', $(cell));
                    px++;
                }
            }
            if (px > 0) {
                py++;
            }
        }
 
       return dataset;
    },
 
    /**
     * Copy method
     * 
     * @param bool highlighted - Get only highlighted cells
     * @param delimiter - \t default to keep compatibility with excel
     * @return string value
     */
    copy : function(highlighted, delimiter, returnData) {
        if (! delimiter) {
            delimiter = "\t";
        }
 
        var str = '';
        var row = '';
        var val = '';
        var pc = false;
        var pr = false;
 
        // Column and row length
        var x = $(this).find('thead tr td').not(':first').length;
        var y = $(this).find('tbody tr').length;
 
        // Go through the columns to get the data
        for (j = 0; j < y; j++) {
            row = '';
            pc = false;
            for (i = 0; i < x; i++) {
                // Get cell
                cell = $(this).find('#' + i + '-' + j);
 
                // If cell is highlighted
                if (! highlighted || $(cell).hasClass('highlight')) {
                    if (pc) {
                        row += delimiter;
                    }
                    // Get value
                    val = $(this).jexcel('getValue', $(cell));
                    if (val.match(/,/g)) {
                        val = '"' + val + '"'; 
                    }
                    row += val;
                    pc = true;
                }
            }
            if (row) {
                if (pr) {
                    str += "\n";
                }
                str += row;
                pr = true;
            }
        }
 
        // Create a hidden textarea to copy the values
        if (! returnData) {
            txt = $('.jexcel_textarea');
            $(txt).val(str);
            $(txt).select();
            document.execCommand("copy");
        }
 
        return str;
    },
 
    cut : function () {
        var main = $(this);
 
        // Copy data
        main.jexcel('copy', true);
        var cells = $(this).find('.highlight');
 
        // Start a new history record
        main.jexcel('startNewHistoryRecord');
        $.each(cells, function (index, cell) {
            // Store history for undo/redo
            main.jexcel('storeCellChange', $(cell), '')
        });
 
        // Remove current data
        main.jexcel('setValue', cells, '');
    },
 
    /**
     * Paste method TODO: if the clipboard is larger than the table create automatically columns/rows?
     * 
     * @param integer row number
     * @return string value
     */
    paste : function(cell, data) {
        // Id
        var id = $(this).prop('id');
 
        // Data
        data = data.split("\r\n");
 
        // Initial position
        var position = $(cell).prop('id');
        if (position) {
            position = position.split('-');
            var x = parseInt(position[0]);
            var y = parseInt(position[1]);
 
            // Automatic adding new rows when the copied data is larger then the table
            if (y + data.length > $.fn.jexcel.defaults[id].data.length) {
                $(this).jexcel('insertRow', y + data.length - $.fn.jexcel.defaults[id].data.length);
            }
            // Automatic adding new columns when the copied data is larger then the table
            if (data[0]) {
                row = data[0].split("\t");
                if (x + row.length > $.fn.jexcel.defaults[id].data[y].length) {
                    $(this).jexcel('insertColumn', x + row.length - $.fn.jexcel.defaults[id].data[y].length);
                }
            }
 
            $(this).jexcel('startNewHistoryRecord');
 
            // Go through the columns to get the data
            for (j = 0; j < data.length; j++) {
                // Explode column values
                row = data[j].split("\t");
                for (i = 0; i < row.length; i++) {
                    // Get cell
                    cell = $(this).find('#' + (parseInt(i) + parseInt(x))  + '-' + (parseInt(j) + parseInt(y)));
    
                    // If cell exists
                    if ($(cell).length > 0) {
                        $(this).jexcel('storeCellChange', $(cell), row[i]);
                        $(this).jexcel('setValue', $(cell), row[i]);
                    }
                }
            }
        }
    },
 
    /**
     * Insert a new column
     * 
     * @param  object properties - column properties
     * @param  int numColumns - number of columns to be created
     * @return void
     */
    insertColumn : function (numColumns, properties) {
        var main = $(this);
 
        // Id
        var id = $(this).prop('id');
 
        // Number of columns to be created
        if (! numColumns) {
            numColumns = 1;
        }
 
        // Minimal default properties
        var defaults = {
            column: { type:'text' },
            width:'50',
            align:'center'
        };
        properties = $.extend(defaults, properties);
 
        // Get the main object configuration
        var options = $.fn.jexcel.defaults[id];
 
        // Current column number
        var num = options.colHeaders.length;
 
        // Create columns
        for (i = num; i < (num + numColumns); i++) {
            // Adding the column properties to the main property holder
            options.colHeaders[i] = properties.header || $.fn.jexcel('getColumnName', i);
            options.colWidths[i] = properties.width;
            options.colAlignments[i] = properties.align;
            options.columns[i] = properties.column;
 
            if (! options.columns[i].source) {
                $.fn.jexcel.defaults[id].columns[i].source = [];
            }
            if (! options.columns[i].options) {
                $.fn.jexcel.defaults[id].columns[i].options = [];
            }
 
            // Default header cell properties
            width = options.colWidths[i];
            align = options.colAlignments[i];
            header = options.colHeaders[i];
 
            // Create header html
            var td =  '<td id="col-' + i + '" width="' + width + '" align="' + align + '">' + header + '</td>';
 
            // Add element to the table
            var tr = $(this).find('thead.label tr')[0];
            $(tr).append(td);
 
            // Add columns to the content rows
            tr = $(this).find('table > tbody > tr');
            $.each(tr, function (k, v) {
                // Update data array
                options.data[k][i] = '';
                // HTML cell
                td = $(main).jexcel('createCell', i, k);
                // Append cell to the tbody
                $(v).append(td);
            });
        }
    },
 
    /**
     * Insert a new row
     * 
     * @param object numLines - how many lines to be included
     * @return void
     */
    insertRow : function(numLines) {
        // Id
        var id = $(this).prop('id');
 
        // Main configuration
        var options = $.fn.jexcel.defaults[id];
 
        // Num lines
        if (! numLines) {
            // Add one line is the default
            numLines = 1;
        } 
 
        j = parseInt($.fn.jexcel.defaults[id].data.length);
 
        // Adding lines
        for (row = 0; row < numLines; row++) {
            // New row
            var tr = '<td id="row-' + j + '" class="label">' + (j + 1) + '</td>';
 
            // New data
            $.fn.jexcel.defaults[id].data[j] = [];
 
            for (i = 0; i < $.fn.jexcel.defaults[id].colHeaders.length; i++) {
                // New Data
                $.fn.jexcel.defaults[id].data[j][i] = '';
 
                // Aligment
                align = $.fn.jexcel.defaults[id].colAlignments[i] || 'left';
 
                // Hidden column
                if ($.fn.jexcel.defaults[id].columns[i].type == 'hidden') {
                    tr += '<td id="' + i + '-' + j + '" style="display:none;"></td>';
                } else {
                    // Native options
                    if ($.fn.jexcel.defaults[id].columns[i].type == 'checkbox') {
                        contentCell = '<input type="checkbox">';
                    } else if ($.fn.jexcel.defaults[id].columns[i].type == 'dropdown' || $.fn.jexcel.defaults[id].columns[i].type == 'autocomplete' || $.fn.jexcel.defaults[id].columns[i].type == 'calendar') {
                        contentCell = '<input type="hidden" value="">';
                    } else {
                        contentCell = '';
                    }
 
                    tr += '<td id="' + i + '-' + j + '" align="' + align +'">' + contentCell + '</td>';
                }
            }
 
            tr = '<tr>' + tr + '</tr>';
 
            $(this).find('tbody').append(tr);
 
            j++;
        }
    },
 
    /**
     * Set the column width
     * @param column - column number (first column is: 0)
     * @param width - new column width
     */
    setWidth : function (column, width) {
        if (width > 0) {
            var col = $(this).find('thead #col-' + column);
            if (col.length) {
                $(col).prop('width', width);
            }
        }
    },
 
    /**
     * Get the column width
     * @param column - column number (first column is: 0)
     * @return width - current column width
     */
    getWidth : function (column) {
        var col = $(this).find('thead #col-' + column);
 
        if (col.length) {
            return $(col).prop('width');
        }
    },
 
    /**
     * Set the column title
     * @param column - column number (first column is: 0)
     * @param title - new column title
     */
    setHeader : function (column, title) {
        if (title) {
            var col = $(this).find('thead #col-' + column);
            if (col.length) {
                $(col).html(title);
            }
        }
    },
 
    /**
     * Update column source for dropboxes
     */
    setSource : function (column, source) {
        // In case the column is an object
        if (typeof(column) == 'object') {
            column = $(column).prop('id').split('-');
            column = column[0];
        }
 
        // Id
        var id = $(this).prop('id');
 
        // Update defaults
        $.fn.jexcel.defaults[id].columns[column].source = source;
        $.fn.jexcel.defaults[id].columns[column].combo = $(this).jexcel('createCombo', source);
    },
 
    /**
     * After change
     */
    afterChange : function() {
        // Id
        var id = $(this).prop('id');
 
        // Dynamic updates
        if ($.fn.jexcel.defaults[id].dynamicColumns.length > 0) {
            $(this).jexcel('formula');
        }
 
        // After Changes
        if (typeof($.fn.jexcel.defaults[id].onafterchange) == 'function') {
            $.fn.jexcel.defaults[id].onafterchange($(this));
        }
 
        // Update settings
        $(this).jexcel('updateSettings');
    },
 
    /**
     * Helper function to copy data using the corner icon
     */
    copyData : function(o, d) {
        var data = $(this).jexcel('getData', true);
 
        $(this).jexcel('startNewHistoryRecord');
 
        // Cells
        var px = parseInt(o[0]);
        var ux = parseInt(d[0]);
        var py = parseInt(o[1]);
        var uy = parseInt(d[1]);
 
        // Copy data procedure
        var posx = 0;
        var posy = 0;
        for (j = py; j <= uy; j++) {
            // Controls
            if (data[posy] == undefined) {
                posy = 0;
            }
            posx = 0;
 
            // Data columns
            for (i = px; i <= ux; i++) {
                // Column
                if (data[posy] == undefined) {
                    posx = 0;
                } else if (data[posy][posx] == undefined) {
                    posx = 0;
                }
 
                // Get cell
                cell = $(this).find('#' + i + '-' + j);
 
                // Update non-readonly
                if (! $(cell).hasClass('readonly')) {
                    $(this).jexcel('storeCellChange', cell, data[posy][posx]);
                    $(this).jexcel('setValue', cell, data[posy][posx]);
                }
                posx++;
            }
            posy++;
        }
    },
 
    /**
     * Sort data and reload table
     */
    orderBy :  function(column, order) {
        // Id
        var id = $(this).prop('id');
        var options = $.fn.jexcel.defaults[id];
 
        Array.prototype.sortBy = function(p, o) {
            return this.slice(0).sort(function(a, b) {
              if (! o) {
                  return (a[p] > b[p]) ? 1 : (a[p] < b[p]) ? -1 : 0;
              } else {
                  return (a[p] > b[p]) ? -1 : (a[p] < b[p]) ? 1 : 0;
              }
            });
        }
 
        var data = options.data.sortBy(column, order);
 
        $(this).jexcel('setData', data);
    },
 
    /**
     * Apply formula to all columns in the table
     */
    formula : function() {
        // Keep instannce of this object
        var main = $(this);
 
        // Id
        var id = $(this).prop('id');
 
        // Custom formulas
        if ($.fn.jexcel.defaults[id].formulas) {
            var formulas = $.fn.jexcel.defaults[id].formulas;
            // Set instance
            $.fn.jexcel.defaults[id].formulas.instance = this;
        }
 
        // Dynamic columns
        var columns = $.fn.jexcel.defaults[id].dynamicColumns;
 
        // Define global variables
        var varibles = $(this).find('.jexcel tbody td').not('.label');
        $.each(varibles, function (k, v) {
            i = $(main).jexcel('getColumnNameFromId', $(v).prop('id'));
            v = $(main).jexcel('getValue', $(v));
            if (v == parseInt(v)) {
                window[i] = parseInt(v);
            } else {
                window[i] = v;
            }
        })
 
        if (typeof excelFormulaUtilities == 'object') {
            // Process columns
            $.each(columns, function (k, column) {
                // Get value from the column
                formula = $(main).jexcel('getValue', column);
                // Column value is a formula
                if (formula) {
                    if (formula.substr(0,1) == '=') {
                        // Convert formula to javascript
                        value = excelFormulaUtilities.formula2JavaScript(formula);
                        value = eval(value);
                        // Set value
                        if (value === null || isNaN(value)) {
                            $(main).find('#' + column).addClass('error');
                            value = '<input type="hidden" value="' + formula + '">#ERROR';
                            // Update cell content
                            $(main).find('#' + column).html(value);
                        } else {
                            $(main).find('#' + column).removeClass('error');
                            value = '<input type="hidden" value="' + formula + '">' + value;
                            // Update cell content
                            $(main).find('#' + column).html(value);
                        }
                    } else {
                        // Remove any existing calculation error
                        $(main).find('#' + column).removeClass('error');
                        // No longer dynamic
                        columns.splice(k, 1);
                    }
                } else {
                    // Remove any existing calculation error
                    $(main).find('#' + column).removeClass('error');
                    // No longer dynamic
                    columns.splice(k, 1);
                }
            });
        } else {
            console.error('excelFormulaUtilities lib not included');
        }
    },
 
    // Combo
    createCombo : function (result) {
        // Creating the mapping
        var combo = [];
        if (result.length > 0) {
            for (var j = 0; j < result.length; j++) {
                if (typeof(result[j]) == 'object') {
                    key = result[j].id
                    val = result[j].name;
                } else {
                    key = result[j];
                    val = result[j];
                }
                combo[key] = val;
            }
        }
 
        return combo;
    },
 
    /**
     * Multi-utility helper
     * 
     * @param object options { action: METHOD_NAME }
     * @return mixed
     */
    helper : function (options) {
        var data = [];
        if (typeof(options) == 'object') {
            // Return a empty bidimensional array
            if (options.action == 'createEmptyData') {
                var x = options.cols || 10;
                var y = options.rows || 100;
                for (j = 0; j < y; j++) {
                    data[j] = [];
                    for (i = 0; i < x; i++) {
                        data[j][i] = '';
                    }
                }
            }
        }
 
        return data;
    },
 
    /**
     * Download CSV table
     * 
     * @return null
     */
    download : function () {
        // Get table id
        var id = $(this).prop('id');
        // Increment and get the current history index
        var options = $.fn.jexcel.defaults[id];
        // Data
        var data = '';
 
        // Get headers if applicable
        if (options.csvHeaders == true) {
            data = options.colHeaders.join() + "\n";
        }
 
        // Get data
        data += $(this).jexcel('copy', false, ',', true);
 
        // Download elment
        var pom = document.createElement('a');
        var blob = new Blob([data], {type: 'text/csv;charset=utf-8;'});
        var url = URL.createObjectURL(blob);
        pom.href = url;
        pom.setAttribute('download', 'jexcelTable.csv');
        pom.click();
    },
 
    /**
     * Initializes a new history record for undo/redo
     *
     * @return null
     */
    startNewHistoryRecord : function() {
        var id = $(this).prop('id');
 
        // Increment and get the current history index
        var index = ++$.fn.jexcel.defaults[id].historyIndex;
 
        // Slice the array to discard undone changes
        var history = ($.fn.jexcel.defaults[id].history = $.fn.jexcel.defaults[id].history.slice(0, index + 1));
 
        // Get selection
        var selection = $(this).find('tbody td.highlight');
 
        history[index] = {
            firstSelected: selection[0],
            lastSelected: selection[selection.length - 1],
            cellChanges: []
        };
    },
 
    discardCurrentHistoryRecord : function () {
        var id = $(this).prop('id');
 
        // Get and decrement the current history index
        var index = $.fn.jexcel.defaults[id].historyIndex--;
 
        // Slice the array to discard changes
        $.fn.jexcel.defaults[id].history = $.fn.jexcel.defaults[id].history.slice(0, index);
    },
 
    /**
     * Store a change on an individual cell for undo redo
     *
     * @param object cell changed cell
     * @param string newValue new cell value
     * @param string oldValue old cell vaule [optional]
     */
    storeCellChange : function(cell, newValue, oldValue) {
        var id = $(this).prop('id');
 
        if (oldValue == undefined) {
            oldValue = $(this).jexcel('getValue', cell);
        }
 
        // Store the cell change details
        $.fn.jexcel.defaults[id].history[$.fn.jexcel.defaults[id].historyIndex].cellChanges.push({
            cell: cell,
            newValue: newValue,
            oldValue: oldValue
        });
    },
 
    /**
     * Undo last action
     */
    undo : function () {
        var id = $(this).prop('id');
 
        if ($.fn.jexcel.defaults[id].historyIndex >= 0) {
            var historyRecord = $.fn.jexcel.defaults[id].history[$.fn.jexcel.defaults[id].historyIndex--];
            for (var i = 0; i < historyRecord.cellChanges.length; i++) {
                $(this).jexcel('setValue', historyRecord.cellChanges[i].cell, historyRecord.cellChanges[i].oldValue);
            }
 
            $(this).jexcel('updateSelection', historyRecord.firstSelected, historyRecord.lastSelected);
        }
    },
 
    /**
     * Redo previously undone action
     */
    redo : function () {
        var id = $(this).prop('id');
 
        if ($.fn.jexcel.defaults[id].historyIndex < $.fn.jexcel.defaults[id].history.length - 1) {
            var historyRecord = $.fn.jexcel.defaults[id].history[++$.fn.jexcel.defaults[id].historyIndex];
            for (var i = 0; i < historyRecord.cellChanges.length; i++) {
                $(this).jexcel('setValue', historyRecord.cellChanges[i].cell, historyRecord.cellChanges[i].newValue);
            }
 
            $(this).jexcel('updateSelection', historyRecord.firstSelected, historyRecord.lastSelected);
        }
    },
 
    /**
     * Create cell
     */
    createCell : function(i, j) {
        // Get object identification
        var id = $(this).prop('id');
 
        // Main configuration
        var options = $.fn.jexcel.defaults[id];
 
        // Line properties
        align = options.colAlignments[i];
        width = options.colWidths[i];
 
        // Create cell and properties
        td = document.createElement('td');
        $(td).prop('width', width);
        $(td).prop('align', align);
        $(td).prop('id', i + '-' +j);
 
        // Readonly
        if (options.columns[i].readOnly == true) {
            $(td).prop('readonly', 'readonly');
        }
        // Hidden column
        if (options.columns[i].type == 'hidden') {
            $(td).css('display', 'none');
        } else {
            $(td).html('<input type="checkbox">');
        }
 
        // Set column value
        $(this).jexcel('setValue', $(td), '' + options.data[j][i], true);
 
        return $(td);
    },
 
    /**
     * Get header letter when no name is specified
     */
    getColumnName : function(i) {
        var letter = '';
        if (i > 701) {
            letter += String.fromCharCode(64 + parseInt(i / 676));
            letter += String.fromCharCode(64 + parseInt((i % 676) / 26));
        } else if (i > 25) {
            letter += String.fromCharCode(64 + parseInt(i / 26));
        }
        letter += String.fromCharCode(65 + (i % 26));
 
        return letter;
    },
 
    /**
     * Convert excel like column to jexcel id
     * 
     * @param string id
     * @return string id
     */
    getIdFromColumnName : function (id) {
        var t = /^[a-zA-Z]+/.exec(id);
        if (t) {
            var code = 0;
            for (var i = 0; i < t[0].length; i++) {
                code += parseInt(t[0].charCodeAt(i) - 65);
            }
            id = code + '-' + (parseInt(/[0-9]+$/.exec(id)) - 1);
        }
        return id;
    },
 
    /**
     * Convert jexcel id to excel like column name
     * 
     * @param string id
     * @return string id
     */
    getColumnNameFromId : function (id) {
        var name = id.split('-');
        return $.fn.jexcel('getColumnName', name[0])  + (parseInt(name[1]) + 1);
    }
};
 
$.fn.jexcel = function( method ) {
    if ( methods[method] ) {
        return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
    } else if ( typeof method === 'object' || ! method ) {
        return methods.init.apply( this, arguments );
    } else {
        $.error( 'Method ' +  method + ' does not exist on jQuery.tooltip' );
    }
};
 
})( jQuery );