/moongirl

To get this branch, use:
bzr branch http://9ix.org/moongirl
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
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
/*!
 * MelonJS Game Engine
 * Copyright (C) 2011, Olivier BIOT
 * http://www.melonjs.org
 * 
 * melonJS is licensed under the MIT License.
 * http://www.opensource.org/licenses/mit-license.php
 *
 * @author Olivier Biot 2011
 *
 */
(function($, undefined) {
	// Use the correct document accordingly to window argument
	var document = $.document;

	/**
	 * (<b>m</b>)elon (<b>e</b>)ngine : All melonJS functions are defined inside of this namespace.<p>
	 * You generally should not add new properties to this namespace as it may be overwritten in future versions. 
	 * @namespace
	 */
	me = {
		// settings & configuration
		// library name & version
		mod : "melonJS",
		nocache : '',

		// Public Object (To be completed)
		audio : null,
		video : null,
		timer : null,
		input : null,
		state : null,
		game : null,
		entityPool : null,
		levelDirector : null,
		// System Object (instances)
		XMLParser : null,
		loadingScreen : null,
		// TMX Stuff
		TMXTileMap : null

	};

	/**
	 * debug stuff.
	 * @namespace
	 */
	me.debug = {
		/**
		 * this flag is automatically set <br>
		 * upon detection of a "framecounter" element <br>
		 * in the HTML file holding the cancas.
		 * @memberOf me.debug 
		 */
		displayFPS : false,
		/**
		 * render object Rectangle & Collision Box<br>
		 * default value : false
		 * @type {Boolean}
		 * @memberOf me.debug 
		 */
		renderHitBox : false,

		/**
		 * render dirty region/rectangle<br>
		 * default value : false<br>
		 * (feature must be enabled through the me.sys.dirtyRegion flag)
		 * @type {Boolean}
		 * @memberOf me.debug 
		 */
		renderDirty : false

	};

	/**
	 * global system settings and browser capabilities
	 * @namespace
	 */
	me.sys = {
		// Browser capabilities
		/** 
		 * Browser User Agent (read-only)
		 * @type {Boolean}
		 * @memberOf me.sys
		 */
		ua : navigator.userAgent.toLowerCase(),
		/** 
		 * Browser Audio capabilities (read-only) <br>
		 * @type {Boolean}
		 * @memberOf me.sys
		 */
		sound : false,
		/** 
		 * Browser Local Storage capabilities (read-only) <br>
		 * @type {Boolean}
		 * @memberOf me.sys
		 */
		localStorage : (typeof($.localStorage) == 'object'),
		/** 
		 * Browser Gyroscopic Motion Event capabilities (read-only) <br>
		 * @type {Boolean}
		 * @memberOf me.sys
		 */
		gyro : ($.DeviceMotionEvent !== undefined),
		
		/** 
		 * Browser Base64 decoding capability (read-only) <br>
		 * @type {Boolean}
		 * @memberOf me.sys
		 */
		nativeBase64 : (typeof($.atob) == 'function'),

		// Global settings
		/** 
		 * Game FPS (default 60)
		 * @type {Int}
		 * @memberOf me.sys
		 */
		fps : 60,

		/** 
		 * enable/disable frame interpolation (default disable)<br>
		 * @type {Boolean}
		 * @memberOf me.sys
		 */
		interpolation : false,

		/** 
		 * Global scaling factor(default 1.0)
		 * @type {int}
		 * @memberOf me.sys
		 */
		scale : 1.0,

		/** 
		 * Use native "requestAnimFrame" function if supported <br>
		 * fallback to clearInterval if not supported by the browser<br>
		 * @type {Boolean}
		 * @memberOf me.sys
		 */
		useNativeAnimFrame : false,

		/**
		 * cache Image using a Canvas element, instead of directly using the Image Object<br>
		 * using this, performances are lower on OSX desktop (others, including mobile untested)<br>
		 * default value : false
		 * @type {Boolean}
		 * @memberOf me.sys 
		 */
		cacheImage : false,

		/** 
		 * Enable dirtyRegion Feature <br>
		 * default value : false<br>
		 * (!) not fully implemented/supported (!)
		 * @type {Boolean}
		 * @memberOf me.sys
		 */
		dirtyRegion : false,

		/** 
		 * Experimental WebGl support <br>
		 * https://github.com/corbanbrook/webgl-2d<br>
		 * Be sure to also load the WebGL library (webgl-2d.js) before melonJS<br>
		 * default value : false
		 * @type {Boolean}
		 * @memberOf me.sys
		 */
		enableWebGL : false,
		
		/**
		 * Specify either to stop on audio loading error or not<br>
		 * if me.debug.stopOnAudioLoad is true, melonJS will throw an exception and stop loading<br>
		 * if me.debug.stopOnAudioLoad is false, melonJS will disable sounds and output a warning message in the console <br>
		 * default value : true<br>
		 * @type {Boolean}
		 * @memberOf me.sys 
		 */
		stopOnAudioError : true
	};

	// add me to the global window variable
	$.me = me;

	// a flag to know if melonJS
	// is initialized
	var me_initialized = false;

	/*---
	 	
		DOM loading stuff
		
				---*/

	var readyBound = false, isReady = false, readyList = [];

	// Handle when the DOM is ready
	function domReady() {
		// Make sure that the DOM is not already loaded
		if (!isReady) {
			// be sure document.body is there
			if (!document.body) {
				return setTimeout(domReady, 13);
			}

			// clean up loading event
			if (document.removeEventListener)
				document.removeEventListener("DOMContentLoaded", domReady, false);
			else
				$.removeEventListener("load", domReady, false);

			// Remember that the DOM is ready
			isReady = true;

			// execute the defined callback
			for ( var fn = 0; fn < readyList.length; fn++) {
				readyList[fn].call($, []);
			}
			readyList = [];
		}
	}
	;

	// bind ready
	function bindReady() {
		if (readyBound) {
			return;
		}
		readyBound = true;

		// directly call domReady if document is already "ready"
		if (document.readyState === "complete") {
			return util.domReady();
		} else {
			if (document.addEventListener) {
				// Use the handy event callback
				document.addEventListener("DOMContentLoaded", domReady, false);
			}
			// A fallback to window.onload, that will always work
			$.addEventListener("load", domReady, false);
		}
	}
	;

	/**
	 * Specify a function to execute when the DOM is fully loaded
	 * @param {Function} handler A function to execute after the DOM is ready.
	 * @example
	 * // small main skeleton
	 * var jsApp	= 
	 * {	
	 *    // Initialize the jsApp
	 *    // called by the window.onReady function
	 *    onload: function()
	 *    {
	 *       // init video
	 *       if (!me.video.init('jsapp', 640, 480))
	 *       {
	 *          alert("Sorry but your browser does not support html 5 canvas. ");
	 *          return;
	 *       }
	 *
	 *       // initialize the "audio"
	 *       me.audio.init("mp3,ogg");
	 *
	 *       // set callback for ressources loaded event
	 *       me.loader.onload = this.loaded.bind(this);
	 *
	 *       // set all ressources to be loaded
	 *       me.loader.preload(g_ressources);
	 *
	 *       // load everything & display a loading screen
	 *       me.state.change(me.state.LOADING);
	 *    },
	 *
	 *    // callback when everything is loaded
	 *    loaded: function ()
	 *    {
	 *       // define stuff
	 *       // ....
	 *       
	 *       // change to the menu screen
	 *       me.state.change(me.state.MENU);
	 *    }
	 * }; // jsApp
	 *
	 * // "bootstrap"
	 * window.onReady(function() 
	 * {
	 *    jsApp.onload();
	 * });
	 */
	onReady = function(fn) {
		// Attach the listeners
		bindReady();

		// If the DOM is already ready
		if (isReady) {
			// Execute the function immediately
			fn.call($, []);
		} else {
			// Add the function to the wait list
			readyList.push(function() {
				return fn.call($, []);
			});
		}
		return this;
	};

	// call the library init function when ready
	$.onReady(function() {
		_init_ME();
	});

	/************************************************************************************/

	/*---
	
	 	some "Javascript API" patch & enhancement
	
						---*/

	var initializing = false, 
       fnTest = /xyz/.test(function() {xyz;}) ? /\bparent\b/ : /.*/;

	/**
	 * JavaScript Inheritance Helper <br>
	 * Based on <a href="http://ejohn.org/">John Resig</a> Simple Inheritance<br>
	 * MIT Licensed.<br>
	 * Inspired by <a href="http://code.google.com/p/base2/">base2</a> and <a href="http://www.prototypejs.org/">Prototype</a><br>
	 * @param {Object} object Object (or Properties) to inherit from
	 * @example
	 * var Person = Object.extend(
	 * {
	 *    init: function(isDancing)
	 *    {
	 *       this.dancing = isDancing;
	 *    },
	 *    dance: function()
	 *    {
	 *       return this.dancing;
	 *    }
	 * });
	 *  
	 * var Ninja = Person.extend(
	 * {
	 *    init: function()
	 *    {
	 *       this.parent( false );
	 *    },
	 *    
	 *    dance: function()
	 *    {
	 *       // Call the inherited version of dance()
	 *       return this.parent();
	 *    },
	 *    
	 *    swingSword: function()
	 *    {
	 *       return true;
	 *    }
	 * });
	 *
	 * var p = new Person(true);
	 * p.dance(); // => true
	 *
	 * var n = new Ninja();
	 * n.dance(); // => false
	 * n.swingSword(); // => true
	 *
	 * // Should all be true
	 * p instanceof Person && p instanceof Class &&
	 * n instanceof Ninja && n instanceof Person && n instanceof Class
	 */
	Object.extend = function(prop) {
		// _super rename to parent to ease code reading
		var parent = this.prototype;

		// Instantiate a base class (but only create the instance,
		// don't run the init constructor)
		initializing = true;
		var proto = new this();
		initializing = false;

		// Copy the properties over onto the new prototype
		for ( var name in prop) {
			// Check if we're overwriting an existing function
			proto[name] = typeof prop[name] == "function"
					&& typeof parent[name] == "function"
					&& fnTest.test(prop[name]) ? (function(name, fn) {
				return function() {
					var tmp = this.parent;

					// Add a new ._super() method that is the same method
					// but on the super-class
					this.parent = parent[name];

					// The method only need to be bound temporarily, so we
					// remove it when we're done executing
					var ret = fn.apply(this, arguments);
					this.parent = tmp;

					return ret;
				};
			})(name, prop[name]) : prop[name];
		}

		// The dummy class constructor
		function Class() {
			if (!initializing && this.init) {
				this.init.apply(this, arguments);
			}
			//return this;
		}
		// Populate our constructed prototype object
		Class.prototype = proto;
		// Enforce the constructor to be what we expect
		Class.constructor = Class;
		// And make this class extendable
		Class.extend = arguments.callee;

		return Class;
	};

	if (typeof Object.create !== 'function') {
		/**
		 * Prototypal Inheritance Create Helper
		 * @param {Object} Object
		 * @example
		 * // declare oldObject
		 * oldObject = new Object();
		 * // make some crazy stuff with oldObject (adding functions, etc...)
		 * ...
		 * ...
		 *
		 * // make newObject inherits from oldObject
		 * newObject = Object.create(oldObject);
		 */
		Object.create = function(o) {
			function _fn() {};
			_fn.prototype = o;
			return new _fn();
		};
	};

	if (!Function.bind) {
		/**
		 * ensure bind is properly supported<br>
		 * (c) <a href="http://www.prototypejs.org/">Prototype.js</a><p>
		 * Binds this function to the given context by wrapping it in another function and returning the wrapper.<p>
		 * Whenever the resulting "bound" function is called, it will call the original ensuring that this is set to context. <p>
		 * Also optionally curries arguments for the function.
		 * @param {Object} context the object to bind to.
		 * @param {Array.<string>} [args] Optional additional arguments to curry for the function.
		 * @example
		 * // A typical use of Function bind is to ensure that a callback
		 * // (event handler, etc.) that is an object method gets called with 
		 * // the correct object as its context (this value):
		 *
		 * // -> WRONG
		 * myObject.onComplete(this.callback);
		 *
		 * // -> RIGHT 
		 * myObject.onComplete(this.callback.bind(this));
		 */
		/*
		Function.prototype.bind = function(scope) 
		{
			var _function = this; 
			return function() 
			{
				return _function.apply(scope, arguments);
			}
		};
		 */

		Function.prototype.bind = function() {
			var fn = this, args = Array.prototype.slice.call(arguments), object = args.shift();
			return function() {
				return fn.apply(object, args.concat(Array.prototype.slice.call(arguments)));
			};
		};

	};
   

	/**
	 * Executes a function as soon as the interpreter is idle (stack empty).
	 * @returns id that can be used to clear the deferred function using clearTimeout
	 * @example
	 *
	 *   // execute myFunc() when the stack is empty, with 'myArgument' as parameter
	 *   myFunc.defer('myArgument');
	 *
	 */
	Function.prototype.defer = function() {
		var fn = this, args = Array.prototype.slice.call(arguments);
		return window.setTimeout(function() {
			return fn.apply(fn, args);
		}, 0.01);
	};
   
	if (!Object.defineProperty) {
		/**
		 * simple defineProperty function definition (if not supported by the browser)<br>
		 * if defineProperty is redefined, internally use __defineGetter__/__defineSetter__ as fallback
		 * @param {Object} obj The object on which to define the property.
		 * @param {String} prop The name of the property to be defined or modified.
		 * @param {Object} desc The descriptor for the property being defined or modified.
		 */
		Object.defineProperty = function(obj, prop, desc) {
			// check if Object support __defineGetter function
			if (obj.__defineGetter__) {
				if (desc.get) {
					obj.__defineGetter__(prop, desc.get);
				}
				if (desc.set) {
					obj.__defineSetter__(prop, desc.set);
				}
			} else {
				// we should never reach this point....
				throw "melonJS: Object.defineProperty not supported";
			}
		}
	};

	/** 
	 * add trim fn to the string object 
	 * @extends String
	 * @return {String} trimmed string
	 */
	String.prototype.trim = function() {
		return (this.replace(/^\s+/, '')).replace(/\s+$/, '');
	};

	/**
	 * add isNumeric fn to the string object 
	 * @extends String
	 * @return {Boolean} true if string contains only digits
	 */
	String.prototype.isNumeric = function() {
		return (this != null && !isNaN(this) && this.trim() != "");
	};

	/**
	 * add a isBoolean fn to the string object 
	 * @extends String
	 * @return {Boolean} true if the string is either true or false
	 */
	String.prototype.isBoolean = function() {
		return (this != null && ("true" == this.trim() || "false" == this
				.trim()));
	};

	/**
	 * add a contains fn to the string object
	 * @extends String
	 * @return {Boolean} 
	 */
	String.prototype.contains = function(word) {
		return this.indexOf(word) > -1;
	};
	
   /**
	 * convert the string to hex value
	 * @extends String
	 * @return {String} 
	 */
	String.prototype.toHex = function() {
      var res = "", c = 0;
      while(c<this.length){
         res += this.charCodeAt(c++).toString(16);
      }
      return res;
	};


	/**
	 * add a clamp fn to the Number object
	 * @extends Number
	 * @return {Number} clamped value
	 */
	Number.prototype.clamp = function(low, high) {
		return this < low ? low : this > high ? high : this;
	};

	/**
	 * return a random between min, max
	 * @param {Number} min minimum value.
	 * @param {Number} max maximum value.
	 * @extends Number
	 * @return {Number} random value
	 */
	Number.prototype.random = function(min, max) {
		return (~~(Math.random() * (max - min + 1)) + min);
	};

	/**
	 * round a value to the specified number of digit
	 * @param {Number} [num="Object value"] value to be rounded.
	 * @param {Number} dec number of decimal digit to be rounded to.
	 * @extends Number
	 * @return {Number} rounded value
	 * @example
	 * // round a specific value to 2 digits
	 * Number.prototype.round (10.33333, 2); // return 10.33
	 * // round a float value to 4 digits
	 * num = 10.3333333
	 * num.round(4); // return 10.3333
	 */
	Number.prototype.round = function() {
		// if only one argument use the object value
		var num = (arguments.length == 1) ? this : arguments[0];
		var powres = Math.pow(10, arguments[1] || arguments[0]);
		return (Math.round(num * powres) / powres);
	};

	/**
	 * a quick toHex function<br>
	 * given number <b>must</b> be an int, with a value between 0 and 255
	 * @extends Number
	 * @return {String} converted hexadecimal value
	 */
	Number.prototype.toHex = function() {
		return "0123456789ABCDEF".charAt((this - this % 16) >> 4)
				+ "0123456789ABCDEF".charAt(this % 16);
	};
	
	/**
	 * Returns a value indicating the sign of a number<br>
	 * @extends Number
	 * @return {Number} sign of a the number
	 */
	Number.prototype.sign = function() {
		return this < 0 ? -1 : (this > 0 ? 1 : 0);  
	}

	/************************************************************************************/

	/**
	 * @class
	 * @constructor
	 * @ignore
	 *	a basic XML Parser
	 *
	 **/
	function _TinyXMLParser() {
		var parserObj = {
			xmlDoc : null,
			parser : null,

			// parse a xml from a string (xmlhttpObj.responseText)
			parseFromString : function(textxml) {
				// get a reference to the requested corresponding xml file 
				if ($.DOMParser) {
					this.parser = new DOMParser();
					this.xmlDoc = this.parser.parseFromString(textxml, "text/xml");
				} else // Internet Explorer (untested!)
				{
					this.xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
					this.xmlDoc.async = "false";
					this.xmlDoc.loadXML(textxml);
				}
				if (this.xmlDoc == null) {
					console.log("xml " + this.xmlDoc + " not found!");
				}
			},

			getFirstElementByTagName : function(name) {
				return this.xmlDoc ? this.xmlDoc.getElementsByTagName(name)[0] : null;
			},

			getAllTagElements : function() {
				return this.xmlDoc ? this.xmlDoc.getElementsByTagName('*') : null;
			},

			getStringAttribute : function(elt, str, val) {
				var ret = elt.getAttribute(str);
				return ret ? ret.trim().toLowerCase() : val;
			},

			getIntAttribute : function(elt, str, val) {
				var ret = this.getStringAttribute(elt, str, val);
				return ret ? parseInt(ret) : val;
			},

			getFloatAttribute : function(elt, str, val) {
				var ret = this.getStringAttribute(elt, str, val);
				return ret ? parseFloat(ret) : val;
			},

			getBooleanAttribute : function(elt, str, val) {
				var ret = this.getStringAttribute(elt, str, val);
				return ret ? (ret == "true") : val;
			},

			// free the allocated parser
			free : function() {
				this.xmlDoc = null;
				this.parser = null;
			}
		}
		return parserObj;
	}
	;
	/************************************************************************************/

	/************************************************************************************/

	/*---
	 	ME init stuff
						---*/

	function _init_ME() {
		// don't do anything if already initialized (should not happen anyway)
		if (me_initialized)
			return;

		// init some audio variables		
		var a = document.createElement('audio');

		// enable/disable the cache
		me.utils.setNocache(document.location.href.match(/\?nocache/));

		if (a.canPlayType) {
			me.audio.capabilities.mp3 = ("no" != a.canPlayType("audio/mpeg"))
					&& ("" != a.canPlayType("audio/mpeg"));

			me.audio.capabilities.ogg = ("no" != a.canPlayType('audio/ogg; codecs="vorbis"'))
					&& ("" != a.canPlayType('audio/ogg; codecs="vorbis"'));

			me.audio.capabilities.wav = ("no" != a.canPlayType('audio/wav; codecs="1"'))
					&& ("" != a.canPlayType('audio/wav; codecs="1"'));

			// enable sound if any of the audio format is supported
			me.sys.sound = me.audio.capabilities.mp3 || 
                        me.audio.capabilities.ogg || 
                        me.audio.capabilities.wav;

		}
		// hack, check for specific platform
		if ((me.sys.ua.search("iphone") > -1)
				|| (me.sys.ua.search("ipod") > -1)
				|| (me.sys.ua.search("ipad") > -1)
				|| (me.sys.ua.search("android") > -1)) {
			//if on mobile device, disable sound for now 
			me.sys.sound = false;
		}
		
		// init the FPS counter if needed
		me.timer.init();

		// create an instance of the XML parser
		me.XMLParser = new _TinyXMLParser();

		// create a default loading screen
		me.loadingScreen = new me.DefaultLoadingScreen();

		// init the App Manager
		me.state.init();

		// init the Entity Pool
		me.entityPool.init();

		// init the level Director
		me.levelDirector.reset();

		me_initialized = true;

	};

	/******************************************/
	/*		OBJECT DRAWING MANAGEMENT           */
	/*		hold & manage app/game objects		*/
	/******************************************/

	/**
	 * a object drawing manager
	 * only used by the game manager
	 * @ignore
	 */
	var drawManager = (function() {
		// hold public stuff in our singletong
		var api = {};

		// list of region to redraw
		// valid for any updated object
		var dirtyRects = [];

		// cache the full screen area rect
		var fullscreen_rect;

		// list of object to redraw
		// only valid for visible and update object
		var dirtyObjects = [];

		// a flag indicating if we need a redraw
		api.isDirty = false;

		/**
		 * init function
		 */
		api.reset = function() {
			// make sure it's empty
			dirtyRects = [];
			dirtyObjects = [];

			// set our cached rect to the actual screen size
			fullscreen_rect = me.game.viewport.getRect();

			// make everything dirty
			api.makeAllDirty();
		};

		/**
		 * add a dirty object
		 * I should find a cleaner way to manage old/new object rect
		 */
		api.makeDirty = function(obj, updated, oldRect) {
			// object updated ?
			if (updated) {
				// yeah some drawing job to do !
				api.isDirty = true;

				// add a dirty rect if feature enable
				if (me.sys.dirtyRegion) {
					// some stuff to optimiwze the amount
					// of dirty rect would be nice here
					// instead of adding everything :)
					// this is for later I guess !
					if (oldRect) {
						// merge both rect, and add it to the list
						// directly pass object, since anyway it inherits from rect
						dirtyRects.push(oldRect.union(obj));
					} else if (obj.getRect) {
						dirtyRects.push(obj.getRect());
					}
				}
			}

			// if obj is visible add it to the list of obj to draw
			if (obj.visible) {
				// add obj at index 0, so that we can keep
				// our inverted loop later
				dirtyObjects.splice(0, 0, obj);
			}
		};

		/**
		 * make all object dirty
		 */
		api.makeAllDirty = function() {
			//empty the dirty rect list
			dirtyRects = [];
			//and add a dirty region with the screen area size
			dirtyRects.push(fullscreen_rect);
			// make sure it's dirty
			api.isDirty = true;
			// they are maybe too much call to this function
			// to be checked later...
			//console.log("making everything dirty!");
		};

		/**
		 * remove an object
		 */
		api.remove = function(obj) {
            // remove the object from the list of obj to draw
            dirtyObjects.splice(dirtyObjects.indexOf(obj), 1);
            // save the visible state of the object
            var wasVisible = obj.visible;
            // mark the object as not visible
            // so it won't be added (again) in the list object to be draw
            obj.visible = false;
            // and flag the area as dirty
            api.makeDirty(obj, true);
            // restore visible state, this is needed for "persistent" object like screenObject
            obj.visible = wasVisible;
 		};

		/**
		 * draw all dirty objects/regions
		 */
		api.draw = function(context) {
			// if feature disable, we only have one dirty rect (the viewport area)
			for ( var r = dirtyRects.length, rect; r--, rect = dirtyRects[r];) {
				// parse all objects 
				for ( var o = dirtyObjects.length, obj; o--,
						obj = dirtyObjects[o];) {
					// if dirty region enabled, make sure the object is in the area to be refreshed
					if (me.sys.dirtyRegion && obj.isEntity
							&& !obj.overlaps(rect)) {
						continue;
					}
					// draw the object using the dirty area to be updated
					obj.draw(context, rect);
				}
				// some debug stuff
				if (me.debug.renderDirty) {
					rect.draw(context, "white");
				}
			}
		};

		/**
		 * flush all rect
		 */
		api.flush = function() {
			// only empty dirty area list if dirtyRec feature is enable
			// allows to keep the viewport area as a default dirty rect
			if (me.sys.dirtyRegion) {
				dirtyRects = [];
			}
			// empty the dirty object list
			dirtyObjects = [];

			// clear the flag
			api.isDirty = false;
		};

		return api;

	})();

	/**
	 * me.game represents your current game, it contains all the objects, tilemap layers,<br>
	 * HUD information, current viewport, collision map, etc..<br>
	 * me.game is also responsible for updating (each frame) the object status and draw them<br>
	 * There is no constructor function for me.game.
	 * @final
	 * @memberOf me
	 * @constructor Should not be called by the user.
	 */
	me.game = (function() {
		// hold public stuff in our singletong
		var api = {};

		/*---------------------------------------------
			
			PRIVATE STUFF
				
			---------------------------------------------*/

		// ref to the "system" context
		var frameBuffer = null;

		// hold all the objects							
		var gameObjects = [];

		// hold number of object in the array
		var objCount = 0;

		// flag to redraw the sprites 
		var initialized = false;

		// to handle mouse event
		var registeredMouseEventObj = [];
      
		// to keep track of deferred stuff
		var pendingDefer = null;
      
		/*---------------------------------------------
			
			PUBLIC STUFF

			---------------------------------------------*/
		/**
		 * a reference to the game viewport.
		 * @public
		 * @type me.ViewportEntity
		 * @name me.game#viewport
		 */
		api.viewport = null;
		/**
		 * a reference to the game HUD (if defined).
		 * @public
		 * @type me.HUD_Object
		 * @name me.game#HUD
		 */
		api.HUD = null;
		/**
		 * a reference to the game collision Map
		 * @public
		 * @type me.TiledLayer
		 * @name me.game#collisionMap
		 */
		api.collisionMap = null;
		/**
		 * a reference to the game current level
		 * @public
		 * @type me.TMXTileMap
		 * @name me.game#currentLevel
		 */
		api.currentLevel = null;

		// FIX ME : put this somewhere else
		api.NO_OBJECT = 0;

		/**
		 * Default object type constant.<br>
		 * See type property of the returned collision vector.
		 * @constant
		 * @name me.game#ENEMY_OBJECT
		 */
		api.ENEMY_OBJECT = 1;

		/**
		 * Default object type constant.<br>
		 * See type property of the returned collision vector.
		 * @constant
		 * @name me.game#COLLECTABLE_OBJECT
		 */
		api.COLLECTABLE_OBJECT = 2;

		/**
		 * Default object type constant.<br>
		 * See type property of the returned collision vector.
		 * @constant
		 * @name me.game#ACTION_OBJECT
		 */
		api.ACTION_OBJECT = 3; // door, etc...

		/**
		 * Initialize the game manager
		 * @name me.game#init
		 * @private
		 * @function
		 * @param {int} [width="full size of the created canvas"] width of the canvas
		 * @param {int} [height="full size of the created canvas"] width of the canvas
		 * init function.
		 */
		api.init = function(width, height) {
			if (!initialized) {
				// if no parameter specified use the system size
				var width = width || me.video.getWidth();
				var height = height || me.video.getHeight();

				// create a defaut viewport of the same size
				api.viewport = new me.Viewport(0, 0, width, height);

				// get a ref to the screen buffer
				frameBuffer = me.video.getScreenFrameBuffer();

				initialized = true;
			}
		};

		/**
		 * reset the game Object manager<p>
		 * destroy all current object except the HUD
		 * @see me.game#disableHUD
		 * @name me.game#reset
		 * @public
		 * @function
		 */
		api.reset = function() {
			
			//cancel any pending task
			if (pendingDefer)
			{
				clearTimeout(pendingDefer);
			}
			pendingDefer = null;
         
			// initialized the object if not yet done
			if (!initialized)
				api.init();

			// remove all objects
			api.removeAll();

			// reset the viewport to zero ?
			if (api.viewport)
				api.viewport.reset();

			// re-add the HUD if defined
			if (api.HUD != null) {
				api.add(api.HUD);
			}

			// also reset the draw manager
			drawManager.reset();

		};

		/**
		 * Load a TMX level
		 * @name me.game#loadTMXLevel
		 * @private
		 * @function
		 */

		api.loadTMXLevel = function(level) {
			// load our map
			api.currentLevel = level;

			// get the collision map
			api.collisionMap = api.currentLevel.getLayerByName("collision");
			if (!api.collisionMap || !api.collisionMap.isCollisionMap) {
				alert("WARNING : no collision map detected");
			}

			// add ou tile map object to the game mngr
			api.currentLevel.addTo(me.game);

			// change the viewport limit
			api.viewport.setBounds(api.currentLevel.realwidth,
					api.currentLevel.realheight);

			// load all game entities
			var objectGroups = api.currentLevel.getObjectGroups();
			for ( var group = 0; group < objectGroups.length; group++) {
				for ( var entity = 0; entity < objectGroups[group].objects.length; entity++) {
					api.addEntity(objectGroups[group].objects[entity],
							objectGroups[group].z);
				}
			}

			// sort all our stuff !!
			api.sort();

		};

		/**
		 * Manually add object to the game manager
		 * @name me.game#add
		 * @param {me.ObjectEntity} obj Object to be added
		 * @param {int} [z="obj.z"] z index
		 * @public
		 * @function
		 * @example
		 * // create a new object
		 * var obj = new MyObject(x, y)
		 * // add the object and give the z index of the current object
		 * me.game.add(obj, this.z);
		 * // sort the object list (to ensure the object is properly displayed)
		 * me.game.sort();
		 */
		api.add = function(object, zOrder) {
			object.z = (zOrder) ? zOrder : object.z;

			// add the object in the game obj list
			gameObjects.push(object);

			// TO BE REMOVED
			if (object.mouseEvent) {
				// also add a reference in the object even list
				registeredMouseEventObj.push(object);
			}

			// cache the number of object
			objCount = gameObjects.length;

		};

		/**
		 * add an entity to the game manager
		 * @name me.game#addEntity
		 * @private
		 * @function
		 */
		api.addEntity = function(entityType, zOrder) {
			api.add(me.entityPool.newIstanceOf(entityType), zOrder);
		};
		
		/**
		 * returns the list of entities with the specified name<br>
		 * note : avoid calling this function every frame since
		 * it parses the whole object list each time
		 * @name me.game#getEntityByName
		 * @public
		 * @function
		 * @param {String} entityName entity name
		 * @return {me.ObjectEntity[]} Array of object entities
		 */
		api.getEntityByName = function(entityName)
		{
			var objList = [];
			for (var i = objCount, obj; i--, obj = gameObjects[i];) {
				if(obj.name == entityName) {
					objList.push(obj);
				}
			}
			return objList;
		};
		
		/**
		 * return the entity corresponding to the specified GUID<br>
		 * note : avoid calling this function every frame since
		 * it parses the whole object list each time
		 * @name me.game#getEntityByGUID
		 * @public
		 * @function
		 * @param {String} GUID entity GUID
		 * @return {me.ObjectEntity} Object Entity (or null if not found)
		 */
		api.getEntityByGUID = function(guid)
		{
			for (var i = objCount, obj; i--, obj = gameObjects[i];) {
				if(obj.isEntity && obj.GUID == guid) {
					return obj;
				}
			}
			return null;
		};
		
		/**
		 * add a HUD obj to the game manager
		 * @name me.game#addHUD
		 * @public
		 * @function
		 * @param {int} x x position of the HUD
		 * @param {int} y y position of the HUD
		 * @param {int} w width of the HUD
		 * @param {int} h height of the HUD
		 * @param {String} [bg="none"] a CSS string specifying the background color (e.g. "#0000ff" or "rgb(0,0,255)")
		 */
		api.addHUD = function(x, y, w, h, bg) {
			// if no HUD existing
			if (api.HUD == null) {
				// create a new default HUD object
				api.HUD = new me.HUD_Object(x, y, w, h, bg);
				api.add(api.HUD);
			}
		};

		/**
		 * disable the current HUD
		 * @name me.game#disableHUD
		 * @public
		 * @function
		 */
		api.disableHUD = function() {

			// if no HUD existing
			if (api.HUD != null) {
				// remove the HUD object
				api.remove(api.HUD);
				// nullify it
				api.HUD = null;

			}
		};

		/**- 
		 * propagate mouse event to objects
		 * @private
		 */
		api.mouseEvent = function(x, y) {
			for ( var i = registeredMouseEventObj.length; i--;) {
				if (registeredMouseEventObj[i].mouseEvent(x, y)) {
					// stop propagating the event
					// if the object return true
					break;
				}
			}
		};

		/**
		 * update all objects of the game manager
		 * @name me.game#update
		 * @private
		 * @function
		 */
		api.update = function() {
			// update the Frame counter
			me.timer.update();
			// previous rect (if any)
			var oldRect = null;
			// loop through our objects
			for ( var i = objCount, obj; i--, obj = gameObjects[i];) {
				// check for previous rect before position change
				oldRect = (me.sys.dirtyRegion && obj.isEntity) ? obj.getRect() : null;
            
				// update our object
				var updated = obj.update();

				// check if object is visible
				if (obj.isEntity) {
					obj.visible = api.viewport.isVisible(obj.collisionBox);
				}

				// add it to the draw manager
				drawManager.makeDirty(obj, updated, updated ? oldRect : null);
			}
			// update the camera/viewport
			if (api.viewport.update(drawManager.isDirty)) {
				drawManager.makeAllDirty();
			}
		};

		/**
		 * remove an object
		 * @name me.game#remove
		 * @public
		 * @function
		 * @param {me.ObjectEntity} obj Object to be removed
		 */
		api.remove = function(obj) {
			// check if object can be destroy
			if (!obj.destroy || obj.destroy()) {
				// make it invisible (this is bad...)
				obj.visible = false
				// ensure it won't be turn back to visible later
				// PS: may be use obj.alive instead ?
				obj.isEntity = false;
				
				// remove the object from the object to draw
				drawManager.remove(obj);

				if (obj.mouseEvent) {
				   // remove object from the mouse event list
				   registeredMouseEventObj.splice(registeredMouseEventObj.indexOf(obj), 1);
				}
				
				// remove the object from the object list
				/** @private */
				pendingDefer = (function (obj) 
				{
				   var idx = gameObjects.indexOf(obj);
				   if (idx!=-1) {
					  gameObjects.splice(idx, 1);
					  // update the number of object
					  objCount = gameObjects.length;
				   }
				   pendingDefer = null;
				}).defer(obj);
			}
      };

		/**
		 * remove all objects
		 * @name me.game#removeAll
		 * @public
		 * @function
		 */

		api.removeAll = function() {
			//empty everything
			objCount = 0;
			gameObjects = [];
			registeredMouseEventObj = [];

			// make sure it's empty there as well
			drawManager.flush();

		};

		/**
		 * <p>Sort all objects (using object z property value).</p>
		 * <p>Normally all objects loaded through the LevelDirector are automatically sorted.
		 * this function is however usefull if you create and add object during the game.</p>
		 * @name me.game#sort
		 * @public
		 * @function
		 */

		api.sort = function() {
			// sort order is inverted, 
			// since we use a reverse loop for the display 
			gameObjects.sort(function(a, b) {
				return (b.z - a.z);
			});
			
			// also sort the clickable items per z order
			registeredMouseEventObj.sort(function(a, b) {
				return (a.z - b.z);
			});

			// make sure we redraw everything
			api.repaint();
		};

		/**
		 * check for collision between objects
		 * @name me.game#collide
		 * @public
		 * @function
		 * @param {me.ObjectEntity} obj Object to be tested for collision
		 * @return {me.Vector2d} collision vector {@link me.Rect#collideVsAABB}
		 * @example
		 * // update player movement
		 * this.updateMovement();
		 *
		 * // check for collision with other objects
		 * res = me.game.collide(this);
		 *
		 * // check if we collide with an enemy :
		 * if (res && (res.obj.type == me.game.ENEMY_OBJECT))
		 * { 	
		 *   if (res.x != 0)
		 *   {
		 *      // x axis
		 *      if (res.x<0)
		 *         console.log("x axis : left side !");
		 *      else
		 *         console.log("x axis : right side !");
		 *   }
		 *   else
		 *   {
		 *      // y axis
		 *      if (res.y<0)
		 *         console.log("y axis : top side !");
		 *      else
		 *         console.log("y axis : bottom side !");			
		 *   }
		 * }

		 */
		api.collide = function(objB) {
			var result = null;

			// this should be replace by a list of the 4 adjacent cell around the object requesting collision
			for ( var i = objCount, obj; i--, obj = gameObjects[i];)//for (var i = objlist.length; i-- ;)
			{
				if (obj.visible && obj.collidable && obj.isEntity && (obj!=objB))
				{
					// if return value != null, we have a collision
					if (result = obj.checkCollision(objB))
						// stop the loop return the value
						break;
				}
			}
			return result;

		};

		/**
		 * force the redraw (not update) of all objects
		 * @name me.game#repaint
		 * @public
		 * @function
		 */

		api.repaint = function() {
			drawManager.makeAllDirty();
		};

		/**
		 * draw all existing objects
		 * @name me.game#draw
		 * @private
		 * @function
		 */

		api.draw = function() {
			if (drawManager.isDirty) {
				// draw our objects
				drawManager.draw(frameBuffer);

				// call the viewport draw function (for effects)
				api.viewport.draw(frameBuffer)
			}
			// clean everything for next frame
			drawManager.flush();
		};

		// return our object
		return api;

	})();

	/************************************************************************************/
	/*      Screen Object Type                                                          */
	/*      Used by the App Manager                                                     */
	/************************************************************************************/

	/* -----

		Screen object object
			
		------	*/
	/**
	 * A class skeleton for "Screen" Object <br>
	 * every "screen" object (title screen, credits, ingame, etc...) to be managed <br>
	 * through the state manager must inherit from this base class.
	 * @class
	 * @extends Object
	 * @memberOf me
	 * @constructor
	 * @see me.state
	 * @example
	 * // create a custom loading screen
	 * var CustomLoadingScreen = me.ScreenObject.extend(
	 * {
	 *    // constructor
	 *    init: function()
	 *    {
	 *       // pass true to the parent constructor
	 *       // as we draw our progress bar in the draw function
	 *       this.parent(true);
	 *       // a font logo
	 *       this.logo = new me.Font('century gothic', 32, 'white');
	 *       // flag to know if we need to refresh the display
	 *       this.invalidate = false;
	 *       // load progress in percent
	 *       this.loadPercent = 0;
	 *       // setup a callback
	 *       me.loader.onProgress = this.onProgressUpdate.bind(this);
	 *
	 *    },
	 *
	 *    // will be fired by the loader each time a resource is loaded
	 *    onProgressUpdate: function(progress)
	 *    {
	 *       this.loadPercent = progress;
	 *       this.invalidate = true;
	 *    },
	 * 
	 *   
	 *    // make sure the screen is only refreshed on load progress 
	 *    update: function()
	 *    {
	 *       if (this.invalidate===true)
	 *       {
	 *          // clear the flag
	 *          this.invalidate = false;
	 *          // and return true
	 *          return true;
	 *       }
	 *       // else return false
	 *       return false;
	 *    },
	 * 
	 *    // on destroy event
	 *    onDestroyEvent : function ()
	 *    {
	 *       // "nullify" all fonts
	 *       this.logo = null;
	 *    },
	 *
	 *    //	draw function
	 *    draw : function(context)
	 *    {
	 *       // clear the screen
	 *       me.video.clearSurface (context, "black");
	 *
	 *       // measure the logo size
	 *       logo_width = this.logo.measureText(context,"awesome loading screen").width;
	 *
	 *       // draw our text somewhere in the middle
	 *       this.logo.draw(context, 
	 *                      "awesome loading screen", 
	 *                      ((context.canvas.width - logo_width) / 2), 
	 *                      (context.canvas.height + 60) / 2);
	 *   
	 *       // display a progressive loading bar
	 *       var width = Math.floor(this.loadPercent * context.canvas.width);
	 *     
	 *       // draw the progress bar
	 *       context.strokeStyle = "silver";
	 *       context.strokeRect(0, (context.canvas.height / 2) + 40, context.canvas.width, 6);
	 *       context.fillStyle = "#89b002";
	 *       context.fillRect(2, (context.canvas.height / 2) + 42, width-4, 2);
	 *    },
	 * });
	 *
	 */
	me.ScreenObject = Object.extend(
	/** @scope me.ScreenObject.prototype */
	{

		visible : true,
		addAsObject : false,
		

		rect : null,

		/**
		 *	initialization function
		 * @param {Boolean} [addAsObjet] add the object in the game manager object pool<br> 
		 * allowing to override the update & draw function to add specific treatment.
		 */

		init : function(addAsObject) {
			this.addAsObject = addAsObject;
			this.visible = (addAsObject === true) || false;
			this.rect = new me.Rect(new me.Vector2d(0, 0), 0, 0);
		},

		/** 
		 *	Object reset function
		 * @private
		 */
		reset : function() {

			// reset the game manager
			me.game.reset();

			// add our object to the GameObject Manager
			// allowing to benefit from the keyboard event stuff
			if (this.addAsObject) {
				// make sure it's visible
				this.visible = true;
				// update the rect size if added as an object
				this.rect = me.game.viewport.getRect();
				// add ourself !
				me.game.add(this, 999);
			}
			// call the onReset Function
			this.onResetEvent.apply(this, arguments);

			// sort the object pool
			me.game.sort();

		},

		/**
		 * getRect function
		 * @private
		 */
		getRect : function() {
			return this.rect;
		},

		/**
		 * destroy function
		 * @private
		 */
		destroy : function() {
			// notify the object
			this.onDestroyEvent.apply(this, arguments);
			// object can be destroyed
			return true;
		},

		/**
		 * update function<br>
		 * optional empty function<br>
		 * only used by the engine if the object has been initialized using addAsObject parameter set to true<br>
		 * @example
		 * // define a Title Screen 
		 * var TitleScreen = me.ScreenObject.extend(
		 * {
		 *    // override the default constructor
		 *    init : function()
		 *    {
		 *       //call the parent constructor giving true
		 *       //as parameter, so that we use the update & draw functions
		 *       this.parent(true);
		 *       ...
		 *       ...
		 *     },
		 *     ...
		 * });
		 */
		update : function() {
			return false;
		},

		/**
		 *	frame update function function
		 * @private
		 */
		onUpdateFrame : function() {
			// update the game object
			me.game.update();

			// draw the game objects
			me.game.draw();

			// blit our frame
			me.video.blitSurface();
		},

		/**
		 *	draw function<br>
		 * optional empty function<br>
		 * only used by the engine if the object has been initialized using addAsObject parameter set to true<br>
		 * @example
		 * // define a Title Screen 
		 * var TitleScreen = me.ScreenObject.extend(
		 * {
		 *    // override the default constructor
		 *    init : function()
		 *    {
		 *       //call the parent constructor giving true
		 *       //as parameter, so that we use the update & draw functions
		 *       this.parent(true);
		 *       ...
		 *       ...
		 *     },
		 *     ...
		 * });
		 */
		draw : function() {
			// to be extended
		},

		/**
		 *	onResetEvent function<br>
		 * called by the state manager when reseting the object<br>
		 * this is typically where you will load a level, etc...
		 * to be extended
		 *	@param {String[]} [arguments] optional arguments passed when switching state
		 */
		onResetEvent : function() {
			// to be extended
		},

		/**
		 *	onDestroyEvent function<br>
		 * called by the state manager before switching to another state<br>
		 */
		onDestroyEvent : function() {
			// to be extended
		}

	});
	

	/************************************************************************************/
	/*      Game App Manager                                                            */
	/*      Manage the basic logic of a game/app                                        */
	/************************************************************************************/

	/*---
	
	 	cross browser requestAnimationFrame/cancelRequestAnimFrame.

		---*/
	window.requestAnimFrame = (function() {
		return window.requestAnimationFrame
				|| window.webkitRequestAnimationFrame
				|| window.mozRequestAnimationFrame
				|| window.oRequestAnimationFrame
				|| window.msRequestAnimationFrame || function() {
					return -1;
				} // return -1 if unsupported
	})();

	window.cancelRequestAnimFrame = (function() {
		return window.cancelAnimationFrame
				|| window.webkitCancelRequestAnimationFrame
				|| window.mozCancelRequestAnimationFrame
				|| window.oCancelRequestAnimationFrame
				|| window.msCancelRequestAnimationFrame || function() {
					return -1;
				} // return -1 if unsupported
	})();

	/* -----

		the game State Manager (state machine)
			
		------	*/
	/**
	 * a State Manager (state machine)<p>
	 * There is no constructor function for me.state.
	 * @final
	 * @memberOf me
	 * @constructor Should not be called by the user.
	 */

	me.state = (function() {
		// hold public stuff in our singleton
		var obj = {};

		/*---------------------------------------------
			
			PRIVATE STUFF
				
			---------------------------------------------*/

		// current state
		var _state = -1;
		// SetInterval Id
		var _intervalId = -1;
		// requestAnimeFrame Id
		var _animFrameId = -1;

		// list of screenObject
		var _screenObject = {};

		// fading transition parameters between screen
		var _fade = {
			color : "",
			duration : 0
		};

		// callback when state switch is done
		/** @private */
		var _onSwitchComplete = null;

		// just to keep track of possible extra arguments
		var _extraArgs = null;

		// cache reference to the active screen update frame
		var _activeUpdateFrame = null;

		// cache reference to the active screen update frame
		var _fps = null;

		/**
		 * @ignore
		 */
		function _startRunLoop() {
			// ensure nothing is running first
			if ((_intervalId == -1) && (_animFrameId == -1)) {

				// reset the timer
				me.timer.reset();

				// start the main loop
				if (me.sys.useNativeAnimFrame) {
					// attempt to setup the game loop using requestAnimationFrame
					_animFrameId = window.requestAnimFrame(_renderFrame);

					if (_animFrameId != -1) {
						return;
					}
					// else feature not supported !

					// disable use of requestAnimationFrame (since unsupported)
					me.sys.useNativeAnimFrame = false;
					//console.log("using setInterval as fallback ("+_animFrameId+")");
				}

				// setup the game loop using setInterval
				_intervalId = setInterval(_activeUpdateFrame, _fps);
			}
		}
		;

		/**
		 * @ignore
		 * this is only called when using requestAnimFrame stuff
		 */
		function _renderFrame() {
			_activeUpdateFrame();
			// we already checked it was supported earlier
			// so no need to do it again here
			window.requestAnimFrame(_renderFrame);
		}
		;

		/**
		 * stop the SO main loop
		 * @ignore
		 */
		function _stopRunLoop() {
			// cancel any previous setInterval
			if (_intervalId != -1) {
				clearInterval(_intervalId);
				_intervalId = -1;
			}
			// cancel any previous animationRequestFrame
			if (_animFrameId != -1) {
				cancelRequestAnimFrame(_animFrameId);
				_animFrameId = -1;
			}

		}
		;

		/**
		 * start the SO main loop
		 * @ignore
		 */
		function _switchState(state) {
			// clear previous interval if any
			_stopRunLoop();

			// call the screen object destroy method
			if (_screenObject[_state]) {
				if (_screenObject[_state].screen.visible)
					me.game.remove(_screenObject[_state].screen);
				else
					_screenObject[_state].screen.destroy();
			}
			
			
			// set the global variable
			_state = state;
			
			// call the reset function with _extraArgs as arguments
			_screenObject[_state].screen.reset.apply(_screenObject[_state].screen, _extraArgs);

			// cache the new screen object update function
			_activeUpdateFrame = _screenObject[_state].screen.onUpdateFrame.bind(_screenObject[_state].screen);

			// and start the main loop of the 
			// new requested state
			_startRunLoop();

			// execute callback if defined
			if (_onSwitchComplete) {
				_onSwitchComplete();
			}
			
			// force repaint
			me.game.repaint();
		};

		/*---------------------------------------------
			
			PUBLIC STUFF
				
			---------------------------------------------*/
		/**
		 * default state value for Loading Screen
		 * @constant
		 * @name me.state#LOADING
		 */
		obj.LOADING = 0;
		/**
		 * default state value for Menu Screen
		 * @constant
		 * @name me.state#MENU
		 */
		obj.MENU = 1;
		/**
		 * default state value for "Ready" Screen
		 * @constant
		 * @name me.state#READY
		 */
		obj.READY = 2;
		/**
		 * default state value for Play Screen
		 * @constant
		 * @name me.state#PLAY
		 */
		obj.PLAY = 3;
		/**
		 * default state value for Game Over Screen
		 * @constant
		 * @name me.state#GAMEOVER
		 */
		obj.GAMEOVER = 4;
		/**
		 * default state value for Game End Screen
		 * @constant
		 * @name me.state#GAME_END
		 */
		obj.GAME_END = 5;
		/**
		 * default state value for High Score Screen
		 * @constant
		 * @name me.state#SCORE
		 */
		obj.SCORE = 6;
		/**
		 * default state value for Credits Screen
		 * @constant
		 * @name me.state#CREDITS
		 */
		obj.CREDITS = 7;
		/**
		 * default state value for Settings Screen
		 * @constant
		 * @name me.state#SETTINGS
		 */
		obj.SETTINGS = 8;

		/**
		 * onPause callback
		 * @type function
		 * @name me.state#onPause
		 */
		obj.onPause = null;

		/**
		 * onResume callback
		 * @type function
		 * @name me.state#onResume
		 */
		obj.onResume = null;

		/**
		 * @ignore
		 */
		obj.init = function() {
			// set the embedded loading screen
			obj.set(obj.LOADING, me.loadingScreen);

			// set pause action on losing focus
			$.addEventListener("blur", function() {
				// only in case we are not loading stuff
				if (_state != obj.LOADING) {
					obj.pause(true);

					// callback?
					if (obj.onPause)
						obj.onPause();

				}
			}, false);
			// set play action on gaining focus
			$.addEventListener("focus", function() {
				// only in case we are not loading stuff
				if (_state != obj.LOADING) {
					obj.resume(true);

					// callback?
					if (obj.onResume)
						obj.onResume();

					// force repaint
					me.game.repaint();

				}
			}, false);

			// cache the FPS information
			_fps = ~~(1000 / me.sys.fps);
		};

		/**
		 * pause the current screen object
		 * @name me.state#pause
		 * @public
		 * @function
		 * @param {Boolean} pauseTrack pause current track on screen pause
		 */
		obj.pause = function(music) {
			// stop the main loop
			_stopRunLoop();
			// current music stop
			if (music)
				me.audio.pauseTrack();

		};

		/**
		 * resume the resume screen object
		 * @name me.state#resume
		 * @public
		 * @function
		 * @param {Boolean} resumeTrack resume current track on screen resume
		 */
		obj.resume = function(music) {
			// start the main loop
			_startRunLoop(_state);
			// current music stop
			if (music)
				me.audio.resumeTrack();
		};

		/**
		 * return the running state of the state manager
		 * @name me.state#isRunning
		 * @public
		 * @function
		 * @param {Boolean} true if a "process is running"
		 */
		obj.isRunning = function() {
			return ((_intervalId != -1) || (_animFrameId != -1))
		};

		/**
		 * associate the specified state with a screen object
		 * @name me.state#set
		 * @public
		 * @function
		 * @param {Int} state @see me.state#Constant
		 * @param {me.ScreenObject} so
		 */
		obj.set = function(state, so) {
			_screenObject[state] = {};
			_screenObject[state].screen = so;
			_screenObject[state].transition = true;
		};

		/**
		 * return a reference to the current screen object<br>
		 * useful to call a object specific method
		 * @name me.state#current
		 * @public
		 * @function
		 * @return {me.ScreenObject} so
		 */
		obj.current = function() {
			return _screenObject[_state].screen;
		};

		/**
		 * specify a global transition effect
		 * @name me.state#transition
		 * @public
		 * @function
		 * @param {String} effect (only "fade" is supported for now)
		 * @param {String} color in RGB format (e.g. "#000000")
		 * @param {Int} [duration="1000"] in ms
		 */
		obj.transition = function(effect, color, duration) {
			if (effect == "fade") {
				_fade.color = color;
				_fade.duration = duration;
			}
		};

		/**
		 * enable/disable transition for a specific state (by default enabled for all)
		 * @name me.state#setTransition
		 * @public
		 * @function
		 */

		obj.setTransition = function(state, enable) {
			_screenObject[state].transition = enable;
		};

		/**
		 * change the game/app state
		 * @name me.state#change
		 * @public
		 * @function
		 * @param {Int} state @see me.state#Constant
		 * @param {Arguments} [args] extra arguments to be passed to the reset functions
		 */

		obj.change = function(state) {
			switch (state) {
				default: {
					_extraArgs = null;
					if (arguments.length > 1) {
						// store extra arguments if any
						_extraArgs = Array.prototype.slice.call(arguments, 1);
					}
					// if fading effect
					if (_fade.duration && _screenObject[state].transition) {
						/** @private */
						_onSwitchComplete = function() {
							me.game.viewport.fadeOut(_fade.color, _fade.duration);
						};
						me.game.viewport.fadeIn(_fade.color, _fade.duration,
								function() {
									_switchState(state);
								});

					}
					// else just switch without any effects
					else {
						// wait for the last frame to be
						// "finished" before switching
						_switchState.defer(state);
						
					}
					break;
				}
			}

		};

		/**
		 * return true if the specified state is the current one
		 * @name me.state#isCurrent
		 * @public
		 * @function
		 * @param {Int} state @see me.state#Constant
		 */
		obj.isCurrent = function(state) {
			return _state == state;
		};

		// return our object
		return obj;

	})();


	/*---------------------------------------------------------*/
	// END END END
	/*---------------------------------------------------------*/
})(window);
/*
 * MelonJS Game Engine
 * Copyright (C) 2011, Olivier BIOT
 * http://www.melonjs.org
 *
 *
 */

(function($, undefined) {

	/**
	 * a default loading screen
	 * @memberOf me
	 * @private
	 * @constructor
	 */
	me.DefaultLoadingScreen = me.ScreenObject.extend({
		/*---
		
			constructor
			
			---*/
		init : function() {
			this.parent(true);
			// melonJS logo
			this.logo1 = new me.Font('century gothic', 32, 'white');
			this.logo2 = new me.Font('century gothic', 32, '#89b002');
			this.logo2.bold();

			// flag to know if we need to refresh the display
			this.invalidate = false;

			// load progress in percent
			this.loadPercent = 0;

			// setup a callback
			me.loader.onProgress = this.onProgressUpdate.bind(this);

		},

		// destroy object at end of loading
		onDestroyEvent : function() {
			// "nullify" all fonts
			this.logo1 = this.logo2 = null;
		},

		// make sure the screen is refreshed every frame 
		onProgressUpdate : function(progress) {
			this.loadPercent = progress;
			this.invalidate = true;
		},

		// make sure the screen is refreshed every frame 
		update : function() {
			if (this.invalidate === true) {
				// clear the flag
				this.invalidate = false;
				// and return true
				return true;
			}
			// else return false
			return false;
		},

		/*---
		
			draw function
		  ---*/

		draw : function(context) {
			
			// measure the logo size
			var y = context.canvas.height / 2;
			var logo1_width = this.logo1.measureText(context, "melon").width;
			var logo_width = logo1_width + this.logo2.measureText(context, "JS").width;
			
			// clear surface
			me.video.clearSurface(context, "black");
			
			// draw the melonJS logo
			this.logo1.draw(context, 'melon',
					((context.canvas.width - logo_width) / 2),
					(context.canvas.height + 60) / 2);
			this.logo2.draw(context, 'JS',
					((context.canvas.width - logo_width) / 2) + logo1_width,
					(context.canvas.height + 60) / 2);
			// add the height of the logo
			y += 40;

			// display a progressive loading bar
			var width = Math.floor(this.loadPercent * context.canvas.width);

			// draw the progress bar
			context.strokeStyle = "silver";
			context.strokeRect(0, y, context.canvas.width, 6);
			context.fillStyle = "#89b002";
			context.fillRect(2, y + 2, width - 4, 2);
		},

	});

	/************************************************************************************/
	/*			PRELOADER SINGLETON																			*/
	/************************************************************************************/

	/**
	 * a small class to manage loading of stuff and manage resources
	 * There is no constructor function for me.input.
	 * @final
	 * @memberOf me
	 * @constructor Should not be called by the user.
	 */

	me.loader = (function() {
		// hold public stuff in our singletong
		var obj = {};

		// contains all the images loaded
		var imgList = [];
		// contains all the xml loaded
		var xmlList = {};
		// flag to check loading status
		var resourceCount = 0;
		var loadCount = 0;
		var timerId = 0;
		// keep track of how much TMX file we are loading
		var tmxCount = 0;

		/* ---
		
			check the loading status
			
			---										*/
		function checkLoadStatus() {
			// remove tmxCount from the total resource to be loaded
			// as we will after load each TMX into the level director
			if (loadCount == (resourceCount - tmxCount)) {

				// add all TMX level into the level Director
				for ( var xmlObj in xmlList) {
					if (xmlList[xmlObj].isTMX) {
						//console.log("un TMX!", xmlObj);
						me.levelDirector.addTMXLevel(xmlObj);

						//progress notification
						obj.onResourceLoaded();
					}
				}

				// wait 1/2s and execute callback (cheap workaround to ensure everything is loaded)
				if (obj.onload) {
					timerId = setTimeout(obj.onload, 300);
				} else
					alert("no load callback defined");
			} else {
				timerId = setTimeout(checkLoadStatus, 100);
			}
		};

		/* ---
		
			some callback for image loading	
			 error	
			---										*/
		function onImageError(e) {
			// retry mechanism with image loading ???
			throw "melonJS: Failed loading image resource";
		};

		/* ---
		
			load Images
			
			call example : 
			
			preloadImages(
						 [{name: 'image1', src: 'images/image1.png'},
						  {name: 'image2', src: 'images/image2.png'},
						  {name: 'image3', src: 'images/image3.png'},
						  {name: 'image4', src: 'images/image4.png'}]);
			
			---										*/

		function preloadImage(img, onload, onerror) {
			// create new Image object and add to array
			imgList.push(img.name);

			imgList[img.name] = new Image();
			imgList[img.name].onload = onload || obj.onResourceLoaded.bind(obj);
			imgList[img.name].onerror = onerror || onImageError.bind(this);
			imgList[img.name].src = img.src + me.nocache;
		};

		/* ---
		
			preload XML files
			---									*/

		function preloadXML(xmlData, isTMX) {
			if ($.XMLHttpRequest) {
				// code for IE7+, Firefox, Chrome, Opera, Safari
				var xmlhttp = new XMLHttpRequest();
				// to ensure our document is treated as a XML file
				if (xmlhttp.overrideMimeType)
					xmlhttp.overrideMimeType('text/xml');
			} else {
				// code for IE6, IE5
				xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
				// I actually don't give a **** about IE5/IE6...
			}
			// load our XML
			xmlhttp.open("GET", xmlData.src + me.nocache, false);
			xmlhttp.onload = obj.onResourceLoaded.bind(obj);
			xmlhttp.send();

			// set the xmldoc in the array
			xmlList[xmlData.name] = {};
			xmlList[xmlData.name].xml = xmlhttp.responseText;
			xmlList[xmlData.name].isTMX = isTMX || false;
			// in case we have a TMX file :
			if (xmlList[xmlData.name].isTMX) {
				// increase the resourceCount by 1
				// allowing to add the loading of level in the 
				// levelDirector as part of the loading progress
				resourceCount += 1;
				tmxCount += 1;
			}
		};

		/* ---
			
			PUBLIC STUFF
				
			---										*/

		/* ---
		
			onload callback : to be initialized
			
			---*/
		/**
		 * onload callback
		 * @public
		 * @type Function
		 * @name me.loader#onload
		 * @example
		 *
		 * // set a callback when everything is loaded
		 * me.loader.onload = this.loaded.bind(this);
		 */
		obj.onload = undefined;

		/**
		 * onProgress callback<br>
		 * each time a resource is loaded, the loader will fire the specified function,
		 * giving the actual progress [0 ... 1], as argument.
		 * @public
		 * @type Function
		 * @name me.loader#onProgress
		 * @example
		 *
		 * // set a callback for progress notification
		 * me.loader.onProgress = this.updateProgress.bind(this);
		 */
		obj.onProgress = undefined;

		/**
		 *	just increment the number of already loaded resources
		 * @private
		 */

		obj.onResourceLoaded = function(e) {

			// increment the loading counter
			loadCount++;

			// callback ?
			if (obj.onProgress) {
				// pass the load progress in percent, as parameter
				obj.onProgress(obj.getLoadProgress());
			}
		};

		/**
		 * set all the specified game resources to be preloaded.<br>
		 * each resource item must contain the following fields :<br>
		 * - name    : internal name of the resource<br>
		 * - type    : "image", "tmx", "audio"<br>
		 * - src     : path and file name of the resource<br>
		 * (!) for audio :<br>
		 * - src     : path (only) where resources are located<br>
		 * - channel : number of channels to be created<br>
		 * <br>
		 * @name me.loader#preload
		 * @public
		 * @function
		 * @param {Array.<string>} resources
		 * @example
		 * var g_resources = [ {name: "tileset-platformer",  type:"image",  src: "data/map/tileset-platformer.png"},
		 *                     {name: "map1",                type: "tmx",   src: "data/map/map1_slopes.tmx"},
		 *                     {name: "cling",               type: "audio", src: "data/audio/",	channel : 2}
		 *                    ]; 
		 * ...
		 *
		 * // set all resources to be loaded
		 * me.loader.preload(g_resources);
		 */

		obj.preload = function(res) {
			// set the callback for audio stuff
			me.audio.setLoadCallback(obj.onResourceLoaded.bind(obj));

			// parse the resources
			for ( var i = 0; i < res.length; i++) {
				switch (res[i].type) {
				case "image":
					preloadImage(res[i]);
					resourceCount += 1;
					break;

				case "audio":
					// only load is sound is enable
					if (me.audio.isAudioEnable()) {
						me.audio.load(res[i]);
						resourceCount += 1;
					}
					break;

				case "tmx":
					preloadXML(res[i], true);
					resourceCount += 1;
					break;

				default:
					throw "melonJS: me.loader.preload : unknow resource type : %s"
							+ res[i].type;
					break;
				}
			}
			;

			// check load status
			checkLoadStatus();
		};

		/**
		 * Load a single resource (to be used if you need to load additional resource during the game)<br>
		 * Given parmeter must contain the following fields :<br>
		 * - name    : internal name of the resource<br>
		 * - type    : only "image" supported <br>
		 * - src     : path and file name of the resource<br>
		 * @name me.loader#load
		 * @public
		 * @function
		 * @param {Object} resource
		 * @param {Function} onload function to be called when the resource is loaded
		 * @param {Function} onerror function to be called in case of error
		 * @example
		 * // load a image asset
		 * me.loader.load({name: "avatar",  type:"image",  src: "data/avatar.png"}, this.onload.bind(this), this.onerror.bind(this));
		 */

		obj.load = function(res, onload, onerror) {
			// check ressource type
			switch (res.type) {
				case "image":
					// reuse the preloadImage fn
					preloadImage(res, onload, onerror);
					break;

				default:
					throw "melonJS: me.loader.load : unknow or invalide resource type : %s"	+ res.type;
					break;
			};
		};


		/**
		 * return the specified XML object
		 * @name me.loader#getXML
		 * @public
		 * @function
		 * @param {String} xmlfile name of the xml element ("map1");
		 * @return {Xml} 
		 */
		obj.getXML = function(elt) {
			if (xmlList != null)
				return xmlList[elt].xml;
			else {
				//console.log ("warning %s resource not yet loaded!",name);
				return null;
			}

		};

		/**
		 * return the specified Image Object
		 * @name me.loader#getImage
		 * @public
		 * @function
		 * @param {String} Image name of the Image element ("tileset-platformer");
		 * @return {Image} 
		 */

		obj.getImage = function(elt) {
			if (imgList[elt] != null) {
				if (me.sys.cacheImage === true) {
					// build a new canvas
					var tempCanvas = me.video.createCanvasSurface(
							imgList[elt].width, imgList[elt].height);
					// draw the image into the canvas context
					tempCanvas.drawImage(imgList[elt], 0, 0);
					// return our canvas
					return tempCanvas.canvas;
				} else {
					// return the corresponding Image object
					return imgList[elt];
				}
			} else {
				//console.log ("warning %s resource not yet loaded!",name);
				return null;
			}

		};

		/**
		 * Return the loading progress in percent
		 * @name me.loader#getLoadProgress
		 * @public
		 * @function
		 * @deprecated use callback instead
		 * @return {Number} 
		 */

		obj.getLoadProgress = function() {
			return loadCount / resourceCount;
		};

		// return our object
		return obj;

	})();

	/*---------------------------------------------------------*/
	// END END END
	/*---------------------------------------------------------*/
})(window);
/*
 * MelonJS Game Engine
 * Copyright (C) 2011, Olivier BIOT
 * http://www.melonjs.org
 *
 *
 */

(function($, undefined) {

	/************************************************************************************/
	/*                                                                                  */
	/*      a vector2D Object                                                           */
	/*                                                                                  */
	/************************************************************************************/
	/**
	 * a 2D Vector Object
	 * @class
	 * @extends Object
	 * @memberOf me
	 * @constructor
	 * @param {int} x x position of the vector
	 * @param {int} y y position of the vector
	 */
	me.Vector2d = Object.extend(
	/** @scope me.Vector2d.prototype */
	{
		/**
		 * x value of the vector
		 * @public
		 * @type Number
		 * @name me.Vector2d#x
		 */
		x : 0,
		/**
		 * y value of the vector
		 * @public
		 * @type Number
		 * @name me.Vector2d#y
		 */
		y : 0,

		/** @private */
		init : function(/**Int*/
		x, /**Int*/
		y) {
			this.x = x || 0;
			this.y = y || 0;
		},

		set : function(/**Int*/
		x, /**Int*/
		y) {
			this.x = x;
			this.y = y;
		},

		setZero : function() {
			this.set(0, 0);

		},

		setV : function(/**me.Vector2d*/
		v) {
			this.x = v.x;
			this.y = v.y;
		},

		add : function(/**me.Vector2d*/
		v) {
			this.x += v.x;
			this.y += v.y;
		},

		sub : function(/**me.Vector2d*/
		v) {
			this.x -= v.x;
			this.y -= v.y;
		},

		scale : function(/**me.Vector2d*/
		v) {
			this.x *= v.x;
			this.y *= v.y;
		},

		div : function(/**Int*/
		n) {
			this.x /= n;
			this.y /= n;
		},

		abs : function() {
			if (this.x < 0)
				this.x = -this.x;
			if (this.y < 0)
				this.y = -this.y;
		},

		/** @return {me.Vector2D} */
		clamp : function(low, high) {
			return new me.Vector2d(this.x.clamp(low, high), this.y
					.clamp(low, high));
		},

		minV : function(/**me.Vector2d*/ v) {
			this.x = this.x < v.x ? this.x : v.x;
			this.y = this.y < v.y ? this.y : v.y;
		},

		maxV : function(/**me.Vector2d*/ v) {
			this.x = this.x > v.x ? this.x : v.x;
			this.y = this.y > v.y ? this.y : v.y;
		},

		/** @return {me.Vector2D} */
		negate : function() {
			return new me.Vector2d(-this.x, -this.y);
		},

		negateSelf : function() {
			this.x = -this.x;
			this.y = -this.y;
		},

		//copy() copies the x,y values of another instance to this
		copy : function(/**me.Vector2d*/ v) {
			this.x = v.x;
			this.y = v.y;
		},

		/** @return {int} */
		length : function() {
			return Math.sqrt(this.x * this.x + this.y * this.y);
		},

		normalize : function() {
			var len = this.length();
			// some limit test
			if (len < Number.MIN_VALUE) {
				return 0.0;
			}
			var invL = 1.0 / len;
			this.x *= invL;
			this.y *= invL;
			return len;
		},

		/** @return {int} */
		dotProduct : function(/**me.Vector2d*/ v) {
			return this.x * v.x + this.y * v.y;
		},

		/** @return {int} */
		distance : function(/**me.Vector2d*/ v) {
			return Math.sqrt((this.x - v.x) * (this.x - v.x) + (this.y - v.y) * (this.y - v.y));
		},

		/** @return {me.Vector2d} */
		clone : function() {
			return new me.Vector2d(this.x, this.y);
		},

		/** @return {String} */
		toString : function() {
			return 'x:' + this.x + 'y:' + this.y;
		},

	});
	/************************************************************************************/
	/*                                                                                  */
	/*      a rectangle Class Object                                                    */
	/*                                                                                  */
	/************************************************************************************/
	/**
	 * a rectangle Object
	 * @class
	 * @extends Object
	 * @memberOf me
	 * @constructor
	 * @param {me.Vector2d} v x,y position of the rectange
	 * @param {int} w width of the rectangle
	 * @param {int} h height of the rectangle
	 */
	me.Rect = Object
			.extend(
			/** @scope me.Rect.prototype */
			{
				/**
				 * position of the Rectange
				 * @public
				 * @type me.Vector2d
				 * @name me.Rect#pos
				 */
				pos : null,

				/**
				 * allow to reduce the collision box size<p>
				 * while keeping the original position vector (pos)<p>
				 * corresponding to the entity<p>
				 * colPos is a relative offset to pos
				 * @private
				 * @type me.Vector2d
				 * @name me.Rect#colPos
				 * @see me.Rect#adjustSize
				 */
				colPos : null,

				/**
				 * left coordinate of the Rectange<br>
				 * takes in account the adjusted size of the rectangle (if set)
				 * @public
				 * @type Int
				 * @name me.Rect#left
				 */
				left : null,

				/**
				 * right coordinate of the Rectange<br>
				 * takes in account the adjusted size of the rectangle (if set)
				 * @public
				 * @type Int
				 * @name me.Rect#right
				 */
				right : null,

				/**
				 * top coordinate of the Rectange<br>
				 * takes in account the adjusted size of the rectangle (if set)
				 * @public
				 * @type Int
				 * @name me.Rect#top
				 */
				top : null,

				/**
				 * bottom coordinate of the Rectange<br>
				 * takes in account the adjusted size of the rectangle (if set)
				 * @public
				 * @type Int
				 * @name me.Rect#bottom
				 */
				bottom : null,

				/**
				 * width of the Rectange
				 * @public
				 * @type Int
				 * @name me.Rect#width
				 */
				width : 0,
				/**
				 * height of the Rectange
				 * @public
				 * @type Int
				 * @name me.Rect#height
				 */
				height : 0,

				// half width/height
				hWidth : 0,
				hHeight : 0,
				
				// flags to check if we
				// already redefined properties
				hProp : false,
				vProp : false,

				
				/** @private */
				init : function(v, w, h) {
					// reference to the initial position
					// we don't copy it, so we can use it later
					this.pos = v;

					// allow to reduce the hitbox size
					// while on keeping the original pos vector
					// corresponding to the entity
					this.colPos = new me.Vector2d();

					this.width = w;
					this.height = h;

					// half width/height
					this.hWidth = ~~(w / 2);
					this.hHeight = ~~(h / 2);

					
					// some properties to ease my life when getting the rectangle coordinates /**
					Object.defineProperty(this, "left", {
						get : function() {
							return this.pos.x;
						},
						configurable : true
					});
					Object.defineProperty(this, "right", {
						get : function() {
							return this.pos.x + this.width;
						},
						configurable : true
					});
					Object.defineProperty(this, "top", {
						get : function() {
							return this.pos.y;
						},
						configurable : true
					});
					Object.defineProperty(this, "bottom", {
						get : function() {
							return this.pos.y + this.height;
						},
						configurable : true
					});

				},

				/**
				 * set new value to the rectangle
				 * @param {me.Vector2d} v x,y position for the rectangle
				 * @param {int} w width of the rectangle
				 * @param {int} h height of the rectangle	 
				 */
				set : function(v, w, h) {
					this.pos = v; // Vector2d - top left corner

					this.width = w;
					this.height = h;
					
					this.hWidth = ~~(w / 2);
					this.hHeight = ~~(h / 2);
				},

				/**
				 * return a new Rect with this rectangle coordinates
				 * @return {me.Rect} new rectangle	
				 */
				getRect : function() {
					return new me.Rect(this.pos.clone(), this.width,
							this.height);
				},

				/**
				 * merge this rectangle with another one
				 * @param {me.Rect} rect other rectangle to union with
				 * @return {me.Rect} the union(ed) rectangle	 
				 */
				union : function(/** {me.Rect} */ r) {
					var x1 = Math.min(this.pos.x, r.pos.x);
					var y1 = Math.min(this.pos.y, r.pos.y);

					this.width = Math.ceil(Math.max(this.pos.x + this.width,
							r.pos.x + r.width)
							- x1);
					this.height = Math.ceil(Math.max(this.pos.y + this.height,
							r.pos.y + r.height)
							- y1);
					this.pos.x = ~~x1;
					this.pos.y = ~~y1;

					return this;
				},

				/**
				 * update the size of the collision rectangle<br>
				 * the colPos Vector is then set as a relative offset to the initial position (pos)<br>
				 * <img src="me.Rect.colpos.png"/>
				 * @private
				 * @param {int} x x offset (specify -1 to not change the width)
				 * @param {int} w width of the hit box
				 * @param {int} y y offset (specify -1 to not change the height)
				 * @param {int} h height of the hit box
				 */
				adjustSize : function(x, w, y, h) {
					if (x != -1) {
						this.colPos.x = x;
						this.width = w;
						this.hWidth = ~~(this.width / 2);
						
						// avoid Property definition if not necessary
						if (!this.hProp) {
							// redefine our properties taking colPos into account
							Object.defineProperty(this, "left", {
								get : function() {
									return this.pos.x + this.colPos.x;
								},
								configurable : true
							});
							Object.defineProperty(this, "right", {
								get : function() {
									return this.pos.x + this.colPos.x + this.width;
								},
								configurable : true
							});
							this.hProp = true;
						}
					}
					if (y != -1) {
						this.colPos.y = y;
						this.height = h;
						this.hHeight = ~~(this.height / 2);
						
						// avoid Property definition if not necessary
						if (!this.vProp) {
							// redefine our properties taking colPos into account
							Object.defineProperty(this, "top", {
								get : function() {
									return this.pos.y + this.colPos.y;
								},
								configurable : true
							});
							Object.defineProperty(this, "bottom", {
								get : function() {
									return this.pos.y + this.colPos.y + this.height;
								},
								configurable : true
							});
							this.vProp = true;
						}
					}
				},

				/**
				 *	
				 * flip on X axis
				 * usefull when used as collision box, in a non symetric way
				 * @private
				 * @param sw the sprite width
				 */
				flipX : function(sw) {
					this.colPos.x = sw - this.width - this.colPos.x;
					this.hWidth = ~~(this.width / 2);
				},

				/**
				 *	
				 * flip on Y axis
				 * usefull when used as collision box, in a non symetric way
				 * @private
				 * @param sh the height width
				 */
				flipY : function(sh) {
					this.colPos.y = sh - this.height - this.colPos.y;
					this.hHeight = ~~(this.height / 2);
				},

				/**
				 * check if this rectangle is intersecting with the specified one
				 * @param  {me.Rect} rect
				 * @return {boolean} true if overlaps
				 */
				overlaps : function(r)	{
					return (this.left < r.right && 
							r.left < this.right && 
							this.top < r.bottom &&
							r.top < this.bottom);
				},
				
				/**
				 * check if this rectangle is within the specified one
				 * @param  {me.Rect} rect
				 * @return {boolean} true if within
				 */
				within: function(r) {
					return (r.left <= this.left && 
						    r.right >= this.right &&
						    r.top <= this.top && 
							r.bottom >= this.bottom);
                },
				
				/**
				 * check if this rectangle contains the specified one
				 * @param  {me.Rect} rect
				 * @return {boolean} true if contains
				 */
				contains: function(r) {
					return (r.left >= this.left && 
							r.right <= this.right &&
							r.top >= this.top && 
							r.bottom <= this.bottom);
                },

				/**
				 * AABB vs AABB collission dectection<p>
				 * If there was a collision, the return vector will contains the following values: 
				 * @example
				 * if (v.x != 0 || v.y != 0)
				 * { 	
				 *   if (v.x != 0)
				 *   {
				 *      // x axis
				 *      if (v.x<0)
				 *         console.log("x axis : left side !");
				 *      else
				 *         console.log("x axis : right side !");
				 *   }
				 *   else
				 *   {
				 *      // y axis
				 *      if (v.y<0)
				 *         console.log("y axis : top side !");
				 *      else
				 *         console.log("y axis : bottom side !");			
				 *   }
				 *		
				 * }
				 * @private
				 * @param {me.Rect} rect
				 * @return {me.Vector2d} 
				 */
				collideVsAABB : function(/** {me.Rect} */ rect) {
					// response vector
					var p = new me.Vector2d(0, 0);

					// check if both box are overlaping
					if (this.overlaps(rect)) {
						// compute delta between this & rect
						var dx = this.left + this.hWidth  - rect.left - rect.hWidth;
						var dy = this.top  + this.hHeight - rect.top  - rect.hHeight;

						// compute penetration depth for both axis
						p.x = (rect.hWidth + this.hWidth) - (dx < 0 ? -dx : dx); // - Math.abs(dx);
						p.y = (rect.hHeight + this.hHeight)
								- (dy < 0 ? -dy : dy); // - Math.abs(dy);

						// check and "normalize" axis
						if (p.x < p.y) {
							p.y = 0;
							p.x = dx < 0 ? -p.x : p.x;
						} else {
							p.x = 0;
							p.y = dy < 0 ? -p.y : p.y;
						}
					}
					return p;
				},

				/**
				 * @private
				 * debug purpose
				 */
				draw : function(context, color) {
					// draw the rectangle
					context.strokeStyle = color || "red";
					context.strokeRect(this.left - me.game.viewport.pos.x,
							this.top - me.game.viewport.pos.y, this.width,
							this.height);

				}
	});

	/*---------------------------------------------------------*/
	// END END END
	/*---------------------------------------------------------*/
})(window);
/*
 * MelonJS Game Engine
 * Copyright (C) 2011, Olivier BIOT
 * http://www.melonjs.org
 *
 */

(function($, undefined) {
	// some ref shortcut
	var MIN = Math.min, MAX = Math.max;

	/************************************************************************************/
	/*		a viewport/camera entity																		*/
	/************************************************************************************/
	/**
	 * a camera/viewport Object
	 * @class
	 * @extends me.Rect
	 * @memberOf me
	 * @constructor
	 * @param {int} minX start x offset
	 * @param {int} minY start y offset
	 * @param {int} maxX end x offset
	 * @param {int} maxY end y offset
	 * @param {int} [realw] real world width limit
	 * @param {int} [realh] real world height limit
	 */
	me.Viewport = me.Rect
			.extend(
			/** @scope me.Viewport.prototype */
			{

				/**
				 *	Axis constant
				 * @public
				 * type enum
				 */
				AXIS : {
					NONE : 0,
					HORIZONTAL : 1,
					VERTICAL : 2,
					BOTH : 3
				},

				// world limit
				limits : null,

				// target to follow
				target : null,

				// axis to follow
				follow_axis : 0,

				// shake parameters
				_shake : null,
				// fade parameters
				_fadeIn : null,
				_fadeOut : null,

				// cache some values
				_deadwidth : 0,
				_deadheight : 0,
				_limitwidth : 0,
				_limitheight : 0,

				/** @private */
				init : function(minX, minY, maxX, maxY, realw, realh) {
					// viewport coordinates
					this.parent(new me.Vector2d(minX, minY), maxX - minX, maxY - minY);

					// keep track of camera update
					this.last = new me.Vector2d(-1, -1);

					// real worl limits
					this.limits = new me.Vector2d(realw||this.width, realh||this.height);

					// target to follow
					this.target = null;

					// default value follow 
					this.follow_axis = this.AXIS.NONE;

					// shake variables
					this._shake = {
						intensity : 0,
						duration : 0,
						axis : this.AXIS.BOTH,
						onComplete : null
					};
					// flash variables
					this._fadeOut = {
						color : 0,
						alpha : 0.0,
						duration : 0,
						tween : null
					};
					// fade variables
					this._fadeIn = {
						color : 0,
						alpha : 1.0,
						duration : 0,
						tween : null
					};

					// set a default deadzone
					this.setDeadzone(this.width / 6, this.height / 6);
				},

				// -- some private function ---

				/** @private */
				_followH : function(target) {
					if ((target.x - this.pos.x) > (this._deadwidth))
						this.pos.x = ~~MIN((target.x) - (this._deadwidth),
								this._limitwidth);
					else if ((target.x - this.pos.x) < (this.deadzone.x))
						this.pos.x = ~~MAX((target.x) - this.deadzone.x, 0);
				},

				/** @private */
				_followV : function(target) {
					if ((target.y - this.pos.y) > (this._deadheight))
						this.pos.y = ~~MIN((target.y) - (this._deadheight),
								this._limitheight);
					else if ((target.y - this.pos.y) < (this.deadzone.y))
						this.pos.y = ~~MAX((target.y) - this.deadzone.y, 0);
				},

				// -- public function ---

				/**
				 * reset the viewport to specified coordinates
				 * @param {int} x
				 * @param {int} y
				 */
				reset : function(x, y) {
					// reset the initial viewport position to 0,0
					this.pos.x = x || 0;
					this.pos.y = y || 0;

					// reset our position "tracker"
					this.last.set(-1, -1);

					// reset the target
					this.target = null;

					// reset default axis value for follow 
					this.follow_axis = null;

				},

				/**
				 * Change the deadzone settings
				 * @param {int} w deadzone width
				 * @param {int} h deadzone height
				 */
				setDeadzone : function(w, h) {
					this.deadzone = new me.Vector2d(~~((this.width - w) / 2),
							~~((this.height - h) / 2 - h * 0.25));
					// cache some value
					this._deadwidth = this.width - this.deadzone.x;
					this._deadheight = this.height - this.deadzone.y;

					// force a camera update
					this.update(true);

				},

				/**
				 * set the viewport bound (real world limit)
				 * @param {int} w real world width
				 * @param {int} h real world height
				 */
				setBounds : function(w, h) {
					this.limits.set(w, h);
					// cache some value
					this._limitwidth = this.limits.x - this.width;
					this._limitheight = this.limits.y - this.height;

				},

				/**
				 * set the viewport to follow the specified entity
				 * @param {Object} Object ObjectEntity or Position Vector to follow
				 * @param {axis} [axis="AXIS.BOTH"] AXIS.HORIZONTAL, AXIS.VERTICAL, AXIS.BOTH
				 */

				follow : function(target, axis) {
					if (target instanceof me.ObjectEntity)
						this.target = target.pos;
					else if (target instanceof me.Vector2d)
						this.target = target;
					else
						throw "melonJS: invalid target for viewport.follow";
					// if axis is null, camera is moved on target center
					this.follow_axis = axis || this.AXIS.BOTH;
					
					// force a camera update
					this.update(true);
				},

				/**
				 *	move the viewport to the specified coordinates
				 * @param {int} x
				 * @param {int} y
				 */

				move : function(x, y) {
					var newx = ~~(this.pos.x + x);
					var newy = ~~(this.pos.y + y);

					if ((newx >= 0) && (newx <= this._limitwidth))
						this.pos.x = newx;

					if ((newy >= 0) && (newy <= this._limitheight))
						this.pos.y = newy;
				},

				/** @private */
				update : function(updateTarget) {
					if (this.target && updateTarget) {
						switch (this.follow_axis) {
						case this.AXIS.NONE:
							//this.focusOn(this.target);
							break;

						case this.AXIS.HORIZONTAL:
							this._followH(this.target,
									(this._shake.duration > 0));
							break;

						case this.AXIS.VERTICAL:
							this._followV(this.target,
									(this._shake.duration > 0));
							break;

						case this.AXIS.BOTH:
							this._followH(this.target,
									(this._shake.duration > 0));
							this._followV(this.target,
									(this._shake.duration > 0));
							break;

						default:
							break;
						}
						// check if the viewport position has changed (scrolling level)
						updateTarget = (this.last.x != this.pos.x)
								|| (this.last.y != this.pos.y)
						// and keep track of last position for the next update
						this.last.copy(this.pos);
					}

					if (this._shake.duration > 0) {
						this._shake.duration -= me.timer.tick;
						if (this._shake.duration < 0) {
							if (this._shake.onComplete)
								this._shake.onComplete();
						} else {
							if ((this._shake.axis == this.AXIS.BOTH)
									|| (this._shake.axis == this.AXIS.HORIZONTAL)) {
								var shakex = (Math.random() * this._shake.intensity);

								if (this.pos.x + this.width + shakex < this.limits.x)
									this.pos.x += ~~shakex;
								else
									this.pos.x -= ~~shakex;
							}
							if ((this._shake.axis == this.AXIS.BOTH)
									|| (this._shake.axis == this.AXIS.VERTICAL)) {
								var shakey = (Math.random() * this._shake.intensity);

								if (this.pos.y + this.height + shakey < this.limits.y)
									this.pos.y += ~~shakey;
								else
									this.pos.y -= ~~shakey;

							}
							// updated!
							updateTarget = true;
						}
					}

					// check for fade/flash effect
					if ((this._fadeIn.tween!=null) || (this._fadeOut.tween!=null)) {
						updateTarget = true;
					}

					// return same value that the one given
					// so that we only force it to true
					// if we used any effect (e.g. shake, fading, etc...)
					return updateTarget;
				},

				/**
				 *	shake the camera 
				 * @param {int} intensity maximum offset that the screen can be moved while shaking
				 * @param {int} duration expressed in frame
				 * @param {axis} axis specify on which axis you want the shake effect (AXIS.HORIZONTAL, AXIS.VERTICAL, AXIS.BOTH)
				 * @param {function} [onComplete] callback once shaking effect is over
				 * @example
				 * // shake it baby !
				 * me.game.viewport.shake(10, 30, me.game.viewport.AXIS.BOTH);
				 */

				shake : function(intensity, duration, axis, onComplete) {
					// make sure we have a default value for axis
					axis = axis || this.AXIS.BOTH;

					// some limit test
					if (axis == this.AXIS.BOTH) {
						if (this.width == this.limits.x)
							axis = this.AXIS.VERTICAL;
						else if (this.height == this.limits.y)
							axis = this.AXIS.HORIZONTAL;
					}
					if ((axis == this.AXIS.HORIZONTAL)
							&& (this.width == this.limits.x))
						return;

					if ((axis == this.AXIS.VERTICAL)
							&& (this.height == this.limits.y))
						return;

					this._shake.intensity = intensity;
					this._shake.duration = duration;
					this._shake.axis = axis;
					this._shake.onComplete = onComplete || null;
				},

				/**
				 * fadeOut(flash) effect<p>
				 * screen is filled with the specified color and slowy goes back to normal
				 * @param {string} color in #rrggbb format
				 * @param {Int} [duration="1000"] in ms
				 * @param {function} [onComplete] callback once effect is over
				 */

				fadeOut : function(color, duration, onComplete) {
					this._fadeOut.color = color;
					this._fadeOut.duration = duration || 1000; // convert to ms
					this._fadeOut.alpha = 1.0;
					this._fadeOut.tween = new me.Tween(this._fadeOut).to({alpha: 0.0}, this._fadeOut.duration ).onComplete(onComplete||null);
					this._fadeOut.tween.start();
				},

				/**
				 * fadeIn effect <p>
				 * fade to the specified color
				 * @param {string} color in #rrggbb format
				 * @param {int} [duration="1000"] in ms
				 * @param {function} [onComplete] callback once effect is over
				 */

				fadeIn : function(color, duration, onComplete) {
					this._fadeIn.color = color;
					this._fadeIn.duration = duration || 1000; //convert to ms
					this._fadeIn.alpha = 0.0;
					this._fadeIn.tween = new me.Tween(this._fadeIn).to({alpha: 1.0}, this._fadeIn.duration ).onComplete(onComplete||null);
					this._fadeIn.tween.start();
				},

				/**
				 *	return the viewport width
				 * @return {int}
				 */
				getWidth : function() {
					return this.width;
				},

				/**
				 *	return the viewport height
				 * @return {int}
				 */
				getHeight : function() {
					return this.height;
				},

				/**
				 *	set the viewport around the specified entity<p>
				 * <b>BROKEN !!!!</b>
				 * @private
				 * @param {Object} 
				 */
				focusOn : function(target) {
					// BROKEN !! target x and y should be the center point
					this.pos.x = target.x - this.width * 0.5;
					this.pos.y = target.y - this.height * 0.5;
				},

				/**
				 *	check if the specified rectange is in the viewport
				 * @param {me.Rect} rect
				 * @return {boolean}
				 */
				isVisible : function(rect) {
					return rect.overlaps(this);
				},

				/**
				 * @private
				 *	render the camera effects
				 */
				draw : function(context) {
					
					// fading effect
					if (this._fadeIn.tween) {
						if (me.sys.enableWebGL) {
							// don't use global alpha with webgl
							me.video.clearSurface(context, me.utils.HexToRGB(this._fadeIn.color, this._fadeIn.alpha));
						} else {
							context.globalAlpha = this._fadeIn.alpha;
							me.video.clearSurface(context, me.utils.HexToRGB(this._fadeIn.color));
							// set back full opacity
							context.globalAlpha = 1.0;
						}
						// remove the tween if over
						if (this._fadeIn.alpha==1.0)
							this._fadeIn.tween = null;
					}
					
					// flashing effect
					if (this._fadeOut.tween) {
						if (me.sys.enableWebGL) {
							// don't use global alpha with webgl
							me.video.clearSurface(context, me.utils.HexToRGB(this._fadeOut.color, this._fadeOut.alpha));
						} else {
							context.globalAlpha = this._fadeOut.alpha;
							me.video.clearSurface(context, me.utils.HexToRGB(this._fadeOut.color));
							// set back full opacity
							context.globalAlpha = 1.0;
						}
						// remove the tween if over
						if (this._fadeOut.alpha==0.0)
							this._fadeOut.tween = null;
					}
				}

			});

	/*---------------------------------------------------------*/
	// END END END
	/*---------------------------------------------------------*/
})(window);
 /*
 * MelonJS Game Engine
 * Copyright (C) 2011, Olivier BIOT
 * http://www.melonjs.org
 *
 *
 * Entity Objects
 *
 * BIG WORK IN PROGRESS :):):)
 *
 */

(function($, undefined) {
	// some ref shortcut
	var MIN = Math.min;

	/**
	 * me.ObjectSettings contains the object attributes defined in Tiled<br>
	 * and is created by the engine and passed as parameter to the corresponding object when loading a level<br>
	 * the field marked Mandatory are to be defined either in Tiled, or in the before calling the parent constructor
	 * <img src="object_properties.png"/><br>
	 * @final
	 * @memberOf me
	 * @constructor Should not be called by the user.
	 */
	me.ObjectSettings = {
		/**
		 * object entity name<br>
		 * as defined in the Tiled Object Properties
		 * @public
		 * @type {String}
		 * @name me.ObjectSettings#name
		 */
		name : null,

		/**
		 * image ressource name to be loaded<br>
		 * MANDATORY<br>
		 * (in case of TiledObject, this field is automatically set)
		 * @public
		 * @type {String}
		 * @name me.ObjectSettings#image
		 */
		image : null,
		
		/**
		 * specify a transparent color for the image in rgb format (rrggb or #rrggb)<br>
		 * OPTIONAL<br>
		 * (using this option will imply processing time on the image)
		 * @public
		 * @type {String}
		 * @name me.ObjectSettings#transparent_color
		 */
		transparent_color : null,
		
		/**
		 * width of a single sprite in the spritesheet<br>
		 * MANDATORY<br>
		 * (in case of TiledObject, this field is automatically set)
		 * @public
		 * @type {Int}
		 * @name me.ObjectSettings#spritewidth
		 */
		spritewidth : null,
		
		/**
		 * height of a single sprite in the spritesheet<br>
		 * OPTIONAL<br>
		 * if not specified the value will be set to the corresponding image height<br>
		 * (in case of TiledObject, this field is automatically set)
		 * @public
		 * @type {Int}
		 * @name me.ObjectSettings#spriteheight
		 */
		spriteheight : null,


		/**
		 * custom type for collision detection<br>
		 * OPTIONAL
		 * @public
		 * @type {String}
		 * @name me.ObjectSettings#type
		 */
		type : 0,

		/**
		 * Enable collision detection for this object<br>
		 * OPTIONAL
		 * @public
		 * @type {Boolean}
		 * @name me.ObjectSettings#collidable
		 */
		collidable : false
	};


	/************************************************************************************/
	/*		a pool of entity																					*/
	/*    allowing to add new entity at runtime														*/
	/************************************************************************************/
	/**
	 * a pool of object entity <br>
	 * this object is used by the engine to instanciate object defined in the map<br>
	 * which means, that on level loading the engine will try to instanciate every object<br>
	 * found in the map, based on the user defined name in each Object Properties<br>
	 * <img src="object_properties.png"/><br>
	 * There is no constructor function for me.entityPool, this is a static object
	 * @final
	 * @memberOf me
	 * @constructor Should not be called by the user.
	 */
	me.entityPool = (function() {
		// hold public stuff in our singletong
		var obj = {};

		/*---------------------------------------------
			
			PRIVATE STUFF
				
		---------------------------------------------*/
		var entityClass = {};

		/*---------------------------------------------
			
			PUBLIC STUFF
				
		---------------------------------------------*/

		/*---
		
			init
			
			---*/

		obj.init = function() {
			// add default entity object 
			obj.add("me.LevelEntity", me.LevelEntity);
			obj.add("me.ObjectEntity", me.ObjectEntity);
			obj.add("me.CollectableEntity", me.CollectableEntity);
			obj.add("me.InvisibleEntity", me.InvisibleEntity);
		};

		/**
		 * add an object to the pool
		 * @name me.entityPool#add
		 * @public
		 * @function
		 * @param {String} className as defined in the Name fied of the Object Properties (in Tiled)
		 * @param {Object} object corresponding Object to be instanciated
		 * @example
		 * // add our users defined entities in the entity pool
		 * me.entityPool.add("playerspawnpoint", PlayerEntity);
		 * me.entityPool.add("cherryentity", CherryEntity);
		 * me.entityPool.add("heartentity", HeartEntity);
		 * me.entityPool.add("starentity", StarEntity);
		 */
		obj.add = function(className, entityObj) {
			entityClass[className.toLowerCase()] = entityObj;
		};

		/**
		 *	return a new instance of the requested object
		 * @private	
		 */

		obj.newIstanceOf = function(prop) {
			if (!entityClass[prop.name]) {
				alert("cannot instance entity of type '" + prop.name
						+ "': Class not found!");
				return null;
			}
			// i should pass the entity ownProperty instead of the object itself
			return new entityClass[prop.name](prop.x, prop.y, prop);
		};

		// return our object
		return obj;

	})();


	/************************************************************************/
	/*      a parallax layer object entity                                  */
	/************************************************************************/
	/**
	 * @ignore
	 */
	var ParallaxLayer = me.Rect.extend({
		/**
		 * @ignore 
		 */
		init : function(imagesrc, speed, zOrder) {
			// image..
			this.image = me.loader.getImage(imagesrc);

			// call the parent constructor
			this.parent(new me.Vector2d(0, 0), this.image.width,
					this.image.height);

			// base x offset within the image 
			this.baseOffset = 0;

			// z Index
			this.z = zOrder || 0;

			// layer scroll speed
			this.scrollspeed = speed;

			// link to the gameviewport width
			this.vp_width = me.game.viewport.width;
		},

		/*--
		
		   draw the layer
		   x coordinate is the current base offset in the texture
		 
		--*/
		draw : function(context, x, y) {
			// all this part should redone !
			var xpos = 0;
			var new_width = MIN(this.width - x, this.vp_width);
			do {
				context.drawImage(this.image, x, 0, new_width, this.height,
						xpos, y, new_width, this.height);

				xpos += new_width;
				x = 0; // x_offset
				new_width = MIN(this.width, this.vp_width - xpos);
			} while ((xpos < this.vp_width));
		}

	});
	/************************************************************************************/
	/*      a very basic & cheap parallax object entity                                 */
	/*      to be rewritten, this code is not optimized at all                          */
	/************************************************************************************/
	/**
	 * @constructor
	 * @memberOf me
	 *	@param {int} [z="0"] z order value for the parallax background
	 */
	me.ParallaxBackgroundEntity = me.Rect
			.extend({
				/**
				 * @ignore 
				 */
				init : function(z) {
					// call the parent constructor
					this.parent(new me.Vector2d(0, 0), 0, 0);

					// to identify the layer in the tilemap system
					this.name = "parallaxBackgroundEntity";

					this.visible = true;

					// z Index
					this.z = z || 0;

					// link to the gameviewport
					this.vp = me.game.viewport.pos;

					// hold the last x position (to track viewport change)
					this.lastx = this.vp.x;

					// hold all defined animation
					this.parallaxLayers = [];

					// keep track of background update (scroll)
					this.updated = true;
				},

				/**
				 * add a layer to the parallax
				 */
				addLayer : function(imagesrc, speed, zOrder) {
					var idx = this.parallaxLayers.length;
					// create the new layer
					this.parallaxLayers.push(new ParallaxLayer(imagesrc, speed,
							zOrder));

					// check if new layer is bigger than the current rect size
					if (this.parallaxLayers[idx].width > this.width) {
						// and adjust rect size if necessary
						this.width = this.parallaxLayers[idx].width;
					}
					if (this.parallaxLayers[idx].height > this.height) {
						// and adjust rect size if necessary
						this.height = this.parallaxLayers[idx].height;
					}
				},

				/**
				 * @private
				 */
				clearTile : function(x, y) {
					;// do nothing !
				},

				/**
				 * this method is called by the @see me.game object
				 * @protected
				 */
				update : function() {
					return this.updated;
				},

				/**
				 * override the default me.Rect get Rectangle definition
				 * since the layer if a scrolling object
				 * (is this correct?)
				 * @return {me.Rect} new rectangle	
				 */

				getRect : function() {
					return new me.Rect(this.vp.clone(), this.width, this.height);
				},

				/**
				 * draw the parallax object on the specified context
				 * @param {context} context 2D Context
				 * @protected
				 */
				draw : function(context) {
					// last x pos of the viewport
					var x = this.vp.x;

					if (x > this.lastx) {
						// going right
						for ( var i = 0, layer; layer = this.parallaxLayers[i++];) {
							// calculate the new basoffset
							layer.baseOffset = (layer.baseOffset + layer.scrollspeed
									* me.timer.tick)
									% layer.width;
							// draw the layer
							layer.draw(context, ~~layer.baseOffset, 0);
							// save the last x pos
							this.lastx = x;
							// flag as updated
							this.updated = true;
						}
						return;
					} else if (x < this.lastx) {
						// going left
						for ( var i = 0, layer; layer = this.parallaxLayers[i++];) {
							// calculate the new basoffset
							layer.baseOffset = (layer.width + (layer.baseOffset - layer.scrollspeed
									* me.timer.tick))
									% layer.width;
							// draw the layer
							layer.draw(context, ~~layer.baseOffset, 0);
							// save the last x pos
							this.lastx = x;
							// flag as updated
							this.updated = true;
						}
						return;

					}

					// else nothing changes
					for ( var i = 0, layer; layer = this.parallaxLayers[i++];) {
						// draw the layer
						layer.draw(context, ~~layer.baseOffset, 0);
						// save the last x pos
						this.lastx = x;
						// flag as not updated
						this.updated = false;
					}
				}

			});


	/**
	 * A Simple object to display a sprite on screen.
	 * @class
	 * @extends me.Rect
	 * @memberOf me
	 * @constructor
	 * @param {int} x the x coordinates of the sprite object
	 * @param {int} y the y coordinates of the sprite object
	 * @param {me.loader#getImage} image reference to the Sprite Image
	 * @param {int} [spritewidth] sprite width
	 * @param {int} [spriteheigth] sprite height
	 * @example
	 * // create a static Sprite Object
	 * mySprite = new SpriteObject (100, 100, me.loader.getImage("mySpriteImage"));
	 */
	me.SpriteObject = me.Rect
			.extend(
			/** @scope me.SpriteObject.prototype */
			{
				// default scale ratio of the object
				scale	   : null,

				// if true, image flipping/scaling is needed
				scaleFlag : false,

				// just to keep track of when we flip
				lastflipX : false,
				lastflipY : false,

				// z position (for ordering display)
				z : 0,

				// image offset
				offset : null,

				/**
				 * a flag that can prevent the object to be destroyed<br>
				 * if set to false, the objet won't be destroy when calling me.game.remove(obj)<br>
				 * default value : true
				 * @public
				 * @type Boolean
				 * @name me.SpriteObject#autodestroy
				 */
				autodestroy : true,

				/**
				 * the visible state of the object<br>
				 * default value : true
				 * @public
				 * @type Boolean
				 * @name me.SpriteObject#visible
				 */
				visible : true,

				// image reference
				image : null,

				// create a a default collision rectangle
				// this object is useless here, but low level
				// function like flipX need to take this in account
				collisionBox : null,
				
				// to manage the flickering effect
				flickering : false,
				flickerTimer : -1,
				flickercb : null,
				flickerState : false,


				// a reference to the game vp 
				vp : null,

				/**
				 * @ignore 
				 */
				init : function(x, y, image, spritewidth, spriteheight) {

					// call the parent constructor
					this.parent(new me.Vector2d(x, y), 
								spritewidth  || image.width, 
								spriteheight || image.height);

					// cache image reference
					this.image = image;

					// scale factor of the object
					this.scale = new me.Vector2d(1.0, 1.0);

					// create a a default collision rectangle
					this.collisionBox = new me.Rect(this.pos, this.width, this.height);

					// get a reference to the current viewport
					this.vp = me.game.viewport;

					// set the default sprite index & offset
					this.offset = new me.Vector2d(0, 0);
			
				},
				
				/**
				 *	specify a transparent color
				 *	@param {String} color color key in rgb format (rrggb or #rrggb)
				 */
				setTransparency : function(col) {
					// remove the # if present
					col = (col.charAt(0) == "#") ? col.substring(1, 7) : col;
					// applyRGB Filter (return a context object)
					this.image = me.video.applyRGBFilter(this.image, "transparent", col.toUpperCase()).canvas;
				},
				
				/**
				 * return the flickering state of the object
				 * @return Boolean
				 */
				isFlickering : function() {
					return this.flickering;
				},

				
				/**
				 * make the object flicker
				 * @param {Int} duration
				 * @param {Function} callback
				 * @example
				 * // make the object flicker for 60 frame
				 * // and then remove it
				 * this.flicker(60, function()
				 * {
				 *    me.game.remove(this);
				 * });
				 */
				flicker : function(duration, callback) {
					this.flickerTimer = duration;
					if (this.flickerTimer < 0) {
						this.flickering = false;
						this.flickercb = null;
					} else if (!this.flickering) {
						this.flickercb = callback;
						this.flickering = true;
					}
				},

				
				/**
				 *	Flip object on horizontal axis
				 *	@param {Boolean} flip enable/disable flip
				 */
				flipX : function(flip) {
					if (flip != this.lastflipX) {
						this.lastflipX = flip;

						// invert the scale.x value
						this.scale.x = -this.scale.x;

						// set the scaleFlag
						this.scaleFlag = ((this.scale.x != 1.0) || (this.scale.y != 1.0))

						// flip the collision box
						this.collisionBox.flipX(this.width);
					}
				},

				/**
				 *	Flip object on vertical axis
				 *	@param {Boolean} flip enable/disable flip
				 */
				flipY : function(flip) {
					if (flip != this.lastflipY) {
						this.lastflipY = flip;

						// invert the scale.x value
						this.scale.y = -this.scale.y;

						// set the scaleFlag
						this.scaleFlag = ((this.scale.x != 1.0) || (this.scale.y != 1.0))

						// flip the collision box
						this.collisionBox.flipY(this.height);

					}
				},

				/**
				 *	Resize the object around his center<br>
				 *  Note : This won't resize the corresponding collision box
				 *	@param {Boolean} ratio scaling ratio
				 */
				resize : function(ratio)
				{	
					if (ratio > 0) {
						this.scale.x = this.scale.x < 0.0 ? -ratio : ratio;
						this.scale.y = this.scale.y < 0.0 ? -ratio : ratio;
						// set the scaleFlag
						this.scaleFlag = ((this.scale.x!= 1.0)  || (this.scale.y!= 1.0))
					}
				},

				/**
				 * sprite update<br>
				 * not to be called by the end user<br>
				 * called by the game manager on each game loop
				 * @protected
				 * @return false
				 **/
				update : function() {
					//update the "flickering" state if necessary
					if (this.flickering) {
						this.flickerTimer -= me.timer.tick;
						if (this.flickerTimer < 0) {
							if (this.flickercb)
								this.flickercb();
							this.flicker(-1);
						}
						return true;
					}
					return false;
				},

				/**
				 * object draw<br>
				 * not to be called by the end user<br>
				 * called by the game manager on each game loop
				 * @protected
				 * @param {Context2d} context 2d Context on which draw our object
				 **/
				draw : function(context) {
					
					// do nothing if we are flickering
					if (this.flickering) {
						this.flickerState = !this.flickerState;
						if (!this.flickerState) return;
					}
					
					var xpos = ~~(this.pos.x - this.vp.pos.x), ypos = ~~(this.pos.y - this.vp.pos.y);

					if (this.scaleFlag) {
						// translate to the middle of the sprite
						context.translate(xpos + this.hWidth, ypos + this.hHeight);
						// scale
						context.scale(this.scale.x, this.scale.y);
						// translate back to upper left coordinates
						context.translate(-this.hWidth, -this.hHeight);
						// reset coordinates
						xpos = ypos = 0;
					}
					
					context.drawImage(this.image, 
									this.offset.x, this.offset.y,
									this.width, this.height, 
									xpos, ypos,
									this.width, this.height);

					if (this.scaleFlag) {
						// restore the transform matrix to the normal one
						context.setTransform(1, 0, 0, 1, 0, 0);
					}

					if (me.debug.renderHitBox) {
						// draw the sprite rectangle
						this.parent(context, "blue");
						// draw the collisionBox
						this.collisionBox.draw(context, "red");
					}
				},

				/**
				 * Destroy function<br>
				 * object is only removed if the autodestroy flag is set (to be removed, useless)
				 * @private
				 */
				destroy : function() {
					// if object can be destroyed
					if (this.autodestroy) {
						// call the destroy notification function
						this.onDestroyEvent();
					}
					return this.autodestroy;
				},

				/**
				 * OnDestroy Notification function<br>
				 * Called by engine before deleting the object
				 */
				onDestroyEvent : function() {
					;// to be extended !
				}

			});
	/************************************************************************************/
	/*                                                                                  */
	/*      a generic object entity                                                     */
	/*                                                                                  */
	/************************************************************************************/
	/**
	 * an object to manage animation
	 * @class
	 * @extends me.SpriteObject
	 * @memberOf me
	 * @constructor
	 * @param {int} x the x coordinates of the sprite object
	 * @param {int} y the y coordinates of the sprite object
	 * @param {me.loader#getImage} Image reference of the animation sheet
	 * @param {int} spritewidth width of a single sprite within the spritesheet
	 * @param {int} [spriteheight] height of a single sprite within the spritesheet (value will be set to the image height if not specified)
	 */
	me.AnimationSheet = me.SpriteObject
			.extend(
			/** @scope me.AnimationSheet.prototype */
			{
				// count the fps and manage animation change
				fpscount : 0,

				// animation cyling speed
				animationspeed : 0,

				/** @private */
				init : function(x, y, image, spritewidth, spriteheight) {
					// hold all defined animation
					this.anim = [];

					// a flag to reset animation
					this.resetAnim = null;

					// default animation sequence
					this.current = null;

					// call the constructor
					this.parent(x, y, image, spritewidth, spriteheight);
					
					// #sprite per row  
					this.spritecount = ~~(this.image.width / this.width);
					
					// if one single image, disable animation
					if ((this.image.width == this.width) && (this.image.height == this.height)) {
						// override setCurrrentSprite with an empty function
						this.setCurrentSprite = function() {;};
					} 
					
					// default animation speed
					this.animationspeed = me.sys.fps / 10;

					// create a default animation sequence with all sprites
					this.addAnimation("default", null);
					// set as default
					this.setCurrentAnimation("default");
				},

				/**
				 * add an animation <br>
				 * the index list must follow the logic as per the following example :<br>
				 * <img src="spritesheet_grid.png"/>
				 * @param {String} name animation id
				 * @param {Int[]} index list of sprite index defining the animaton
				 * @example
				 * // walking animatin
				 * this.addAnimation ("walk", [0,1,2,3,4,5]);
				 * // eating animatin
				 * this.addAnimation ("eat", [6,6]);
				 * // rolling animatin
				 * this.addAnimation ("roll", [7,8,9,10]);
				 */
				addAnimation : function(name, frame) {
					this.anim[name] = {
						name : null,
						frame : [],
						idx : 0,
						length : 0
					};

					if (frame == null) {
						// by default create an animation with all sprites from row #0
						for ( var i = 0; i < this.spritecount; i++) {
							// compute and add the offset of each frame
							this.anim[name].frame[i] = new me.Vector2d(i * this.width, 0);
						}

					} else {
						var frameidx = 0;
						for ( var i = 0; i < frame.length; i++) {
							// compute and add the offset of each frame
							this.anim[name].frame[frameidx] = new me.Vector2d(this.width * (frame[i] % this.spritecount), 
																			  this.height * ~~(frame[i] / this.spritecount));
							frameidx++;
						}
					}
					this.anim[name].name = name;
					this.anim[name].length = this.anim[name].frame.length;

					// return the create sequence
					//return this.anim[name];

				},

				/**		
				 * set the current animation
				 * @param {String} name animation id
				 * @param {Object} [onComplete] animation id to switch to when complete, or callback
				 * @example
				 * // set "walk" animation
				 * this.setCurrentAnimation("walk");
				 * // set "eat" animation, and switch to "walk" when complete
				 * this.setCurrentAnimation("eat", "walk");
				 * // set "die" animation, and remove the object when finished
				 * this.setCurrentAnimation("die", function(){me.game.remove(this)});
				 **/

				setCurrentAnimation : function(name, resetAnim) {
					this.current = this.anim[name];
					this.resetAnim = resetAnim || null;
					this.offset = this.current.frame[this.current.idx];
				},

				/**
				 * return true if the specified animation is the current one.
				 * @param {String} name animation id
				 * @example
				 * if (!this.isCurrentAnimation("walk"))
				 * {
				 *    // do something horny...
				 * }
				 */
				isCurrentAnimation : function(name) {
					return (this.current.name == name);
				},

				/**
				 * set the current sprite
				 * @private
				 */

				setCurrentSprite : function(s) {
					this.current.idx = s;
					this.offset = this.current.frame[s];
					
					// switch animation if we reach the end of the strip
					// and a callback is defined
					if ((this.current.idx == 0) && this.resetAnim)  {
						// if string, change to the corresponding animation
						if (typeof(this.resetAnim) == "string")
							this.setCurrentAnimation(this.resetAnim);
						// if function (callback) call it
						else if (typeof(this.resetAnim) == "function")
							this.resetAnim();
					}
				},

				/**
				 * update the animation<br>
				 * this is automatically called by the game manager {@link me.game}
				 * @protected
				 */
				update : function() {
					// call the parent function
					this.parent();
					// update animation if necessary
					if (this.visible && (this.fpscount++ > this.animationspeed)) {
						this.setCurrentSprite(++this.current.idx % this.current.length);
						this.fpscount = 0;
						return true;
					}
					return false;
				}
			});

	/************************************************************************************/
	/*                                                                                  */
	/*      a generic object entity                                                     */
	/*                                                                                  */
	/************************************************************************************/
	/**
	 * a Generic Object Entity<br>
	 * Object Properties (settings) are to be defined in Tiled, <br> 
	 * or when calling the parent constructor
	 * 
	 * @class
	 * @extends me.AnimationSheet
	 * @memberOf me
	 * @constructor
	 * @param {int} x the x coordinates of the sprite object
	 * @param {int} y the y coordinates of the sprite object
	 * @param {me.ObjectSettings} settings Object Properties as defined in Tiled <br> <img src="object_properties.png"/>
	 */
	me.ObjectEntity = me.AnimationSheet
			.extend(
			/** @scope me.ObjectEntity.prototype */
			{
			   /**
				* Entity "Game Unique Identifier"<br>
				* @public
				* @type String
				* @name me.ObjectEntity#GUID
				*/
				GUID : null,
			
				// default type of the object (null)
				type : 0,

				// flag to enable/disable collision detection on this object
				collidable : false,

				/** @private */
				init : function(x, y, settings) {
					this.parent(x, y, 
								(typeof settings.image == "string") ? me.loader.getImage(settings.image) : settings.image, 
								settings.spritewidth, 
								settings.spriteheight);
					
					// check for user defined transparent color
					if (settings.transparent_color) {
						this.setTransparency(settings.transparent_color);
					}
					
					// set the object GUID value
					this.GUID = me.utils.createGUID();
					
					// set the object entity name
					this.name = settings.name;
					
					// adjust initial coordinates (should be bottom left ones when in a tiled world)
					this.pos.set(x, me.game.currentLevel?y + me.game.currentLevel.tileheight - this.height:y);

					/**
					 * entity current velocity<br>
					 * @public
					 * @type me.Vector2d
					 * @name me.ObjectEntity#vel
					 */
					this.vel = new me.Vector2d();

					/**
					 * entity current acceleration<br>
					 * @public
					 * @type me.Vector2d
					 * @name me.ObjectEntity#accel
					 */
					this.accel = new me.Vector2d();
					
					/**
					 * entity current friction<br>
					 * @public
					 * @type me.Vector2d
					 * @name me.ObjectEntity#friction
					 */
					this.friction = new me.Vector2d();
					
					/**
					 * max velocity (to limit entity velocity)<br>
					 * @public
					 * @type me.Vector2d
					 * @name me.ObjectEntity#maxVel
					 */
					this.maxVel = new me.Vector2d(1000,1000);

					// some default contants
					/**
					 * Default gravity value of the entity<br>
					 * default value : 0.98 (earth gravity)<br>
					 * to be set to 0 for RPG, shooter, etc...
					 * @public
					 * @type Number
					 * @name me.ObjectEntity#gravity
					 */
					this.gravity = 0.98;

					// just to identify our object
					this.isEntity = true;

					// dead state :)
					/**
					 * dead/living state of the entity<br>
					 * default value : true
					 * @public
					 * @type Boolean
					 * @name me.ObjectEntity#alive
					 */
					this.alive = true;

					// some usefull variable
					
					/**
					 * falling state of the object<br>
					 * true if the object is falling<br>
					 * false if the object is standing on something<br>
					 * (!) READ ONLY property
					 * @public
					 * @type Boolean
					 * @name me.ObjectEntity#falling
					 */
					this.falling = false;
					/**
					 * jumping state of the object<br>
					 * equal true if the entity is jumping<br>
					 * (!) READ ONLY property
					 * @public
					 * @type Boolean
					 * @name me.ObjectEntity#jumping
					 */
					this.jumping = true;

					// some usefull slope variable
					this.slopeY = 0;
					/**
					 * equal true if the entity is standing on a slope<br>
					 * (!) READ ONLY property
					 * @public
					 * @type Boolean
					 * @name me.ObjectEntity#onslope
					 */
					this.onslope = false;
					/**
					 * equal true if the entity is on a ladder<br>
					 * (!) READ ONLY property
					 * @public
					 * @type Boolean
					 * @name me.ObjectEntity#onladder
					 */
					this.onladder = false;

					// to enable collision detection
					this.collidable = settings.collidable || false;
					//this.collectable = false;

					this.type = settings.type || 0;

					
					// ref to the collision map
					this.collisionMap = me.game.collisionMap;
					
					// to know if our object can break tiles
					/**
					 * Define if an entity can go through breakable tiles<br>
					 * default value : false<br>
					 * @public
					 * @type Boolean
					 * @name me.ObjectEntity#canBreakTile
					 */
					this.canBreakTile = false;
					
					/**
					 * a callback when an entity break a tile<br>
					 * @public
					 * @type Function
					 * @name me.ObjectEntity#onTileBreak
					 */
					this.onTileBreak = null;
				},

				/**
				 * specify the size of the hit box for collision detection<br>
				 * (allow to have a specific size for each object)<br>
				 * e.g. : object with resized collision box :<br>
				 * note : bottom of both rectangle MUST always be aligned !<br>
				 * <img src="me.Rect.colpos.png"/>
				 * @param {int} x x offset (specify -1 to not change the width)
				 * @param {int} w width of the hit box
				 * @param {int} y y offset (specify -1 to not change the height)
				 * @param {int} h height of the hit box
				 */
				updateColRect : function(x, w, y, h) {
					this.collisionBox.adjustSize(x, w, y, h);
				},

				/**
				 * collision detection
				 * @private	 
				 */
				checkCollision : function(obj) {
					var res = this.collisionBox.collideVsAABB(obj.collisionBox);

					if (res.x != 0 || res.y != 0) {
						// notify the object
						this.onCollision(res, obj);
						// return the type (deprecated)
						res.type = this.type;
						// return a reference of the colliding object
						res.obj  = this;
						return res;
					}
					return null;
				},

				/**
				 * onCollision Event function<br>
				 * called by the game manager when the object collide with shtg<br>
				 * by default, if the object type is Collectable, the destroy function is called
				 * @param {me.Vector2d} res collision vector
				 * @param {me.ObjectEntity} obj the other object that hit this object
				 * @protected
				 */
				onCollision : function(res, obj) {
					// destroy the object if collectable
					if (this.collidable
							&& (this.type == me.game.COLLECTABLE_OBJECT))
						me.game.remove(this);
				},

				/**
				 * set the entity default velocity<br>
				 * note : velocity is by default limited to the same value, see setMaxVelocity if needed<br>
				 * @param {Int} x velocity on x axis
				 * @param {Int} y velocity on y axis
				 * @protected
				 */

				setVelocity : function(x, y) {
					this.accel.x = (x != 0) ? x : this.accel.x;
					this.accel.y = (x != 0) ? y : this.accel.y;
					
					// limit by default to the same max value
					this.setMaxVelocity(x,y);
				},
				
				/**
				 * cap the entity velocity to the specified value<br>
				 * (!) this will only cap the y velocity for now(!)
				 * @param {Int} x max velocity on x axis
				 * @param {Int} y max velocity on y axis
				 * @protected
				 */
				setMaxVelocity : function(x, y) {
					this.maxVel.x = x;
					this.maxVel.y = y;
				},

				/**
				 * set the entity default friction<br>
				 * @param {Int} x horizontal friction
				 * @param {Int} y vertical friction
				 * @protected
				 */
				setFriction : function(x, y) {
					this.friction.x = x || 0;
					this.friction.y = y || 0;
				},

				
				/**
				 * helper function for platform games: <br>
				 * make the entity move left of right<br>
				 * @param {Boolean} left will automatically flip horizontally the entity sprite
				 * @protected
				 * @example
				 * if (me.input.isKeyPressed('left'))
				 * {
				 *     this.doWalk(true);
				 * }
				 * else if (me.input.isKeyPressed('right'))
				 * {
				 *     this.doWalk(false);
				 * }
				 */
				doWalk : function(left) {
					this.flipX(left);
					this.vel.x += (left) ? -this.accel.x * me.timer.tick : this.accel.x * me.timer.tick;
				},

				/**
				 * helper function for platform games: <br>
				 * make the entity move up and down<br>
				 * only valid is the player is on a ladder
				 * @param {Boolean} up will automatically flip vertically the entity sprite
				 * @protected
				 * @example
				 * if (me.input.isKeyPressed('up'))
				 * {
				 *     this.doClimb(true);
				 * }
				 * else if (me.input.isKeyPressed('down'))
				 * {
				 *     this.doClimb(false);
				 * }
				 */
				doClimb : function(up) {
					// add the player x acceleration to the y velocity
					if (this.onladder) {
						this.vel.y = (up) ? -this.accel.x * me.timer.tick
								: this.accel.x * me.timer.tick;
						return true;
					}
					return false;
				},
				
								
				/**
				 * helper function for platform games: <br>
				 * make the entity jump<br>
				 * @protected
				 */
				doJump : function() {
					// only jump if standing
					if (!this.jumping && !this.falling) {
						this.vel.y = -this.maxVel.y * me.timer.tick;
						this.jumping = true;
						return true;
					}
					return false;
				},

				/**
				 * helper function for platform games: <br>
				 * force to the entity to jump (for double jump)<br>
				 * @protected
				 */
				forceJump : function() {
					this.jumping = this.falling = false;
					this.doJump();
				},
				
				
				/**
				 * return the distance to the specified entity
				 * @param {me.ObjectEntity} entity Entity 
				 * @return {float} distance
				 */
				distanceTo: function(o) 
				{
					// the Vector object also implements the same function, but
					// we have to use here the center of both object
					var dx = (this.pos.x + (this.width>>1))  - (o.pos.x + (o.width>>1)); 
					var dy = (this.pos.y + (this.height>>1)) - (o.pos.y + (o.height>>1));
					return Math.sqrt(dx*dx+dy*dy);
				},

				
				/** 
				 * handle the player movement on a slope
				 * and update vel value
				 * @private
				 */
				checkSlope : function(tile, left) {
										
					// first make the object stick to the tile
					this.pos.y = tile.pos.y - this.height;
					
					// normally the check should be on the object center point, 
					// but since the collision check is done on corner, we must do the same thing here
					if (left)
						this.slopeY = tile.height - (this.collisionBox.right + this.vel.x - tile.pos.x);
					else
						this.slopeY = (this.collisionBox.left + this.vel.x - tile.pos.x);
					
					// cancel y vel
					this.vel.y = 0;
					// set player position (+ workaround when entering/exiting slopes tile)
					this.pos.y += this.slopeY.clamp(0, tile.height);
					
				},
				
				/**
				 * compute the new velocity value
				 * @private
				 */
				computeVelocity : function(vel) {
				
					// apply gravity (if any)
					if (this.gravity) {
						// apply a constant gravity (if not on a ladder)
						vel.y += !this.onladder?(this.gravity * me.timer.tick):0;

						// check if falling / jumping
						this.falling = (vel.y > 0);
						this.jumping = this.falling?false:this.jumping;
					}
					
					// apply friction
					if (this.friction.x)
						vel.x = me.utils.applyFriction(vel.x,this.friction.x);
					if (this.friction.y)
						vel.y = me.utils.applyFriction(vel.y,this.friction.y);
					
					// cap velocity
					if (vel.y !=0)
						vel.y = vel.y.clamp(-this.maxVel.y,this.maxVel.y);
					if (vel.x !=0)
						vel.x = vel.x.clamp(-this.maxVel.x,this.maxVel.x);
					
					return vel;
				},

				
				
				/**
				 * handle the player movement, "trying" to update his position<br>
				 * @return {me.Vector2d} a collision vector
				 * @example
				 * // make the player move
				 * if (me.input.isKeyPressed('left'))
				 * {
				 *     this.vel.x -= this.accel.x * me.timer.tick;
				 * }
				 * else if (me.input.isKeyPressed('right'))
				 * {
				 *     this.vel.x += this.accel.x * me.timer.tick;
				 * }
				 * // update player position
				 * var res = this.updateMovement();
				 *
				 * // check for collision result with the environment
				 * if (res.x != 0)
				 * {
				 *   // x axis
				 *   if (res.x<0)
				 *      console.log("x axis : left side !");
				 *   else
				 *      console.log("x axis : right side !");
				 * }
				 * else if(res.y != 0)
				 * {
				 *    // y axis
				 *    if (res.y<0)
				 *       console.log("y axis : top side !");
				 *    else
				 *       console.log("y axis : bottom side !");		
				 *		
				 *	  // display the tile type
				 *    console.log(res.yprop.type)
				 * }
				 *
				 * // check player status after collision check
				 * var updated = (this.vel.x!=0 || this.vel.y!=0);
				 */
				updateMovement : function() {

					this.vel = this.computeVelocity(this.vel);
					
					// check for collision
					var collision = this.collisionMap.checkCollision(this.collisionBox, this.vel);

					// update some flags
					this.onladder = collision.xprop.isLadder;
					this.onslope  = collision.yprop.isSlope || collision.xprop.isSlope;

					// y collision
					if (collision.y) {

						// going down,
						// collision with the floor
						if (collision.y > 0) {

							if (collision.yprop.isSolid	|| (collision.yprop.isPlatform && (~~this.pos.y	+ this.height <= collision.ytile.pos.y))) {
								// round pos.y
								this.pos.y = ~~this.pos.y;
								// adjust val to tile pos
								this.vel.y = (this.falling) ? collision.ytile.pos.y	- this.pos.y - this.height : 0;
								this.falling = false;
							} else if (collision.yprop.isSlope && !this.jumping) {
								// we stop falling
								this.checkSlope(collision.ytile, collision.yprop.isLeftSlope);
								this.falling = false;
							} else if (collision.yprop.isBreakable) {
								if (this.canBreakTile) {
									// remove the tile
									me.game.currentLevel.clearTile(collision.ytile.row,	collision.ytile.col);
									if (this.onTileBreak)
										this.onTileBreak();
								} else {
									// cancel vel and adjust to tile pos
									// round pos.y
									this.pos.y = ~~this.pos.y;
									this.vel.y = (this.falling) ? collision.ytile.pos.y	- this.pos.y - this.height : 0;
									this.falling = false;
								}
							}
						}
						// going up
						// collision with ceiling
						else if (collision.y < 0) {
							if (!collision.yprop.isPlatform	&& !collision.yprop.isLadder) {
								this.falling = true;
								// cancel the y velocity
								this.vel.y = 0;
							}
						}
					}

					// x collision
					if (collision.x) {
						if (collision.xprop.isSlope && !this.jumping) {
							this.checkSlope(collision.xtile, collision.xprop.isLeftSlope);
							this.falling = false;
						} else {
							// can walk through the platform & ladder
							if (!collision.xprop.isPlatform && !collision.xprop.isLadder) {
								if (collision.xprop.isBreakable	&& this.canBreakTile) {
									// remove the tile
									me.game.currentLevel.clearTile(collision.xtile.row,	collision.xtile.col);
									if (this.onTileBreak) {
										this.onTileBreak();
									}
								} else {
									this.vel.x = 0;
								}
							}
						}
					}

					// update player position
					this.pos.add(this.vel);
					
					// returns the collision "vector"
					return collision;

				}

	});

	/************************************************************************************/
	/*                                                                                  */
	/*      a Collectable entity                                                        */
	/*                                                                                  */
	/************************************************************************************/
	/**
	 * @class
	 * @extends me.ObjectEntity
	 * @memberOf me
	 * @constructor
	 * @param {int} x the x coordinates of the sprite object
	 * @param {int} y the y coordinates of the sprite object
	 * @param {me.ObjectSettings} settings object settings
	 */
	me.CollectableEntity = me.ObjectEntity.extend(
	/** @scope me.CollectableEntity.prototype */
	{
		/** @private */
		init : function(x, y, settings) {
			// call the parent constructor
			this.parent(x, y, settings);

			// make it collidable
			this.collidable = true;
			this.type = me.game.COLLECTABLE_OBJECT;

		}
	});

	/************************************************************************************/
	/*                                                                                  */
	/*      a non visible entity                                                        */
	/*      NOT FINISHED                                                                */
	/************************************************************************************/
	/**
	 * @class
	 * @extends me.Rect
	 * @memberOf me
	 * @constructor
	 * @param {int} x the x coordinates of the object
	 * @param {int} y the y coordinates of the object
	 * @param {me.ObjectSettings} settings object settings
	 */
	me.InvisibleEntity = me.Rect
			.extend(
			/** @scope me.InvisibleEntity.prototype */
			{
				// for z ordering
				z : 0,
				collisionBox : null,

				/** @private */
				init : function(x, y, settings) {
					// call the parent constructor
					this.parent(new me.Vector2d(x, y), settings.width,
							settings.height);

					// create a a default collision rectangle
					this.collisionBox = new me.Rect(this.pos, settings.width,
							settings.height);

					this.visible = true;

					this.collidable = true;

					// just to identify our object
					this.isEntity = true;

				},

				/**
				 * specify the size of the hit box for collision detection<br>
				 * (allow to have a specific size for each object)<br>
				 * e.g. : object with resized collision box :<br>
				 * note : bottom of both rectangle MUST always be aligned !<br>
				 * <img src="me.Rect.colpos.png"/>
				 * @param {int} x x offset (specify -1 to not change the width)
				 * @param {int} w width of the hit box
				 * @param {int} y y offset (specify -1 to not change the height)
				 * @param {int} h height of the hit box
				 */
				updateColRect : function(x, w, y, h) {
					this.collisionBox.adjustSize(x, w, y, h);
				},

				/**
				 * collision detection
				 * @private	 
				 */
				checkCollision : function(obj) {
					var res = this.collisionBox.collideVsAABB(obj.collisionBox);

					if (res.x != 0 || res.y != 0) {
						// notify the object
						this.onCollision(res, obj);
						// return the type 
						res.type = this.type;
						return res;
					}
					return null;
				},

				/**
				 * onCollision Event function<br>
				 * called by the game manager when the object collide with shtg<br>
				 * by default, if the object type is Collectable, the destroy function is called
				 * @param {me.Vector2d} res collision vector
				 * @param {me.ObjectEntity} obj the other object that hit this object
				 * @protected
				 */
				onCollision : function(res, obj) {
					// destroy the object if collectable
					if (this.collidable
							&& (this.type == me.game.COLLECTABLE_OBJECT))
						me.game.remove(this);
				},

				/**
				 * Destroy function
				 * @private
				 */
				destroy : function() {
					// call the destroy notification function
					this.onDestroyEvent();
					return true;
				},

				/**
				 * OnDestroy Notification function<br>
				 * Called by engine before deleting the object
				 */
				onDestroyEvent : function() {
					;// to be extended !
				},

				/** @private */
				update : function() {
					return false;
				},

				/** @private */
				draw : function(context) {
					if (me.debug.renderHitBox) {
						// draw the sprite rectangle
						context.strokeStyle = "blue";
						context.strokeRect(this.pos.x - me.game.viewport.pos.x,
								this.pos.y - me.game.viewport.pos.y,
								this.width, this.height);

						this.collisionBox.draw(context);
					}

				}
			});

	/************************************************************************************/
	/*                                                                                  */
	/*      a level entity                                                              */
	/*                                                                                  */
	/************************************************************************************/
	/**
	 * @class
	 * @extends me.InvisibleEntity
	 * @memberOf me
	 * @constructor
	 * @param {int} x the x coordinates of the object
	 * @param {int} y the y coordinates of the object
	 * @param {me.ObjectSettings} settings object settings
	 */
	me.LevelEntity = me.InvisibleEntity.extend(
	/** @scope me.LevelEntity.prototype */
	{
		/** @private */
		init : function(x, y, settings) {
			this.parent(x, y, settings);

			this.nextlevel = settings.to;

			this.fade = settings.fade;
			this.duration = settings.duration;
			this.fading = false;

			// a temp variable
			this.gotolevel = settings.to;

		},

		/**
		 * @private
		 */
		onFadeComplete : function() {
			me.levelDirector.loadLevel(this.gotolevel);
			me.game.viewport.fadeOut(this.fade, this.duration);
		},

		/**
		 * go to the specified level
		 * @protected
		 */
		goTo : function(level) {
			this.gotolevel = level || this.nextlevel;
			// load a level
			//console.log("going to : ", to);
			if (this.fade && this.duration) {
				if (!this.fading) {
					this.fading = true;
					me.game.viewport.fadeIn(this.fade, this.duration,
							this.onFadeComplete.bind(this));
				}
			} else {
				me.levelDirector.loadLevel(this.gotolevel);
			}
		},

		/** @private */
		onCollision : function() {
			this.goTo();
		}
	});

	/*---------------------------------------------------------*/
	// END END END
	/*---------------------------------------------------------*/
})(window);
/*
 * MelonJS Game Engine
 * Copyright (C) 2011, Olivier BIOT
 * http://www.melonjs.org
 *
 * Font / Bitmap font
 *
 * ASCII Table
 * http://www.asciitable.com/ 
 * [ !"#$%&'()*+'-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_'abcdefghijklmnopqrstuvwxyz]
 *
 * -> first char " " 32d (0x20);
 */

(function($, undefined) {

	/**
	 * a generic system font object.
	 * @class
	 * @extends Object
	 * @memberOf me
	 * @constructor
	 * @param {String} font
	 * @param {int} size
	 * @param {String} color
	 * @param {String} [align="top"]
	 */
	me.Font = Object.extend(
	/** @scope me.Font.prototype */
	{
		// alignement constants
		ALIGN : {
			LEFT : "left",
			CENTER : "center",
			RIGHT : "right"
		},

		// font properties
		font : null,
		height : null,
		color : null,
		align : null,

		/** @private */
		init : function(font, size, color, align) {

			// font name and type
			this.set(font, size, color, align);
		},

		/**
		 * make the font bold
		 */
		bold : function() {
			this.font = "bold " + this.font;
		},

		/**
		 * make the font italic
		 */
		italic : function() {
			this.font = "italic " + this.font;
		},

		/**
		 * Change the font settings
		 * @param {String} font
		 * @param {int} size
		 * @param {String} color
		 * @param {String} [align="top"]
		 */
		set : function(font, size, color, align) {
			// font name and type
			this.font = "" + size + "px " + font;
			this.height = size;
			this.color = color;
			this.align = align || "top";
		},

		/**
		 * FIX ME !
		 * @private
		 */
		getRect : function() {
			return new me.Rect(new Vector2d(0, 0), 0, 0);
		},

		/**
		 * measure the given test width
		 * @param {Context} context 2D Context
		 * @param {String} text
		 * @return {int} width
		 */
		measureText : function(context, text) {
			// draw the text
			context.font = this.font;
			context.fillStyle = this.color;
			context.textBaseLine = this.align;
			var dim = context.measureText(text);
			dim.height = this.height;

			return dim;
		},

		/**
		 * draw a text at the specified coord
		 * @param {Context} context 2D Context
		 * @param {String} text
		 * @param {int} x
		 * @param {int} y
		 */
		draw : function(context, text, x, y) {
			// draw the text
			context.font = this.font;
			context.fillStyle = this.color;
			context.textBaseLine = this.align;
			context.fillText(text, ~~x, ~~y);
		}
	});

	/**
	 * a bitpmap font object
	 * @class
	 * @extends me.Font
	 * @memberOf me
	 * @constructor
	 * @param {String} font
	 * @param {int/Object} size either an int value, or an object like {x:16,y:16}
	 * @param {int} [scale="1.0"]
	 * @param {String} [firstChar="0x20"]

	 */
	me.BitmapFont = me.Font.extend(
	/** @scope me.BitmapFont.prototype */
	{
		// character size;
		size : null,
		// font scale;
		sSize : null,
		// first char in the ascii table
		firstChar : 0x20,
		
		// #char per row
		charCount : 0,

		/** @private */
		init : function(font, size, scale, firstChar) {
			// font name and type
			this.parent(font, null, null);

			// font characters size;
			this.size = new me.Vector2d();
			
			// font scaled size;
			this.sSize = new me.Vector2d();

			// first char in the ascii table
			this.firstChar = firstChar || 0x20;

			// load the font metrics
			this.loadFontMetrics(font, size);

			// set a default alignement
			this.align = this.ALIGN.RIGHT
			
			// resize if necessary
			if (scale) { 
				this.resize(scale);
			}

		},

		/**
		 * Load the font metrics
		 * @private	
		 */
		loadFontMetrics : function(font, size) {
			this.font = me.loader.getImage(font);

			// some cheap metrics
			this.size.x = size.x || size;
			this.size.y = size.y || this.font.height;
			this.sSize.copy(this.size);
			
			// #char per row  
			this.charCount = ~~(this.font.width / this.size.x);
		},

		/**
		 * change the font settings
		 * @param {String} align ("left", "center", "right")
		 * @param {int} [scale]
		 */
		set : function(align, scale) {
			this.align = align;
			// updated scaled Size
			if (scale) {
				this.resize(scale);
			}
		},
		
		/**
		 * change the font display size
		 * @param {int} scale ratio
		 */
		resize : function(scale) {
			// updated scaled Size
			this.sSize.copy(this.size);
			this.sSize.x *= scale;
			this.sSize.y *= scale;
		},

		/**
		 * measure the given test width
		 * @param {String} text
		 * @return {int} width
		 */
		measureText : function(text) {
			return {
				width : text.length * this.sSize.x,
				height : this.sSize.y
			};
		},

		/**
		 * draw a text at the specified coord
		 * @param {Context} context 2D Context
		 * @param {String} text
		 * @param {int} x
		 * @param {int} y
		 */
		draw : function(context, text, x, y) {
			// make sure it's a text parameter
			if (typeof (text) != 'string')
				text = text.toString();

			// adjust pos if right alig
			if (this.align == this.ALIGN.RIGHT) {
				x -= text.length * this.sSize.x;
			}
			// draw the text
			for ( var i = 0; i < text.length; i++) {
				// calculate the char index
				var idx = text.charCodeAt(i) - this.firstChar;
				// draw it
				context.drawImage(this.font,
						this.size.x * (idx % this.charCount), 
						this.size.y * ~~(idx / this.charCount), 
						this.size.x, this.size.y, 
						~~x, ~~y, 
						this.sSize.x, this.sSize.y);
				x += this.sSize.x;
			}

		}
	});

	/*---------------------------------------------------------*/
	// END END END
	/*---------------------------------------------------------*/
})(window);
/*
 * MelonJS Game Engine
 * Copyright (C) 2011, Olivier BIOT
 * http://www.melonjs.org
 *
 */

(function($, undefined) {
	
	/**
	 * GUI Object<br>
	 * A basic object to manage GUI elements <br>
	 * @deprecated won't survive version 0.9.3
	 * @class
	 * @extends me.SpriteObject
	 * @memberOf me
	 * @example
	 * // Enable Mouse Event Management
	 * // should be ideally in the main at initialization
	 * me.input.enableMouseEvent(true);
	 *
	 * // create a basic GUI Object
	 * var myButton = me.GUI_Object.extend(
	 * {	
	 *    init:function(x, y)
	 *   {
	 *      settings = {}
	 *      settings.image = "button";
	 *      settings.spritewidth = 100;
	 *      settings.spriteheight = 50;
	 *      // parent constructor
	 *      this.parent(x, y, settings);
	 *   },
	 *	
	 *   // output something in the console
	 *   // when the object is clicked
	 *   clicked:function()
	 *   {
	 *      console.log("clicked!");
	 *      // don't propagate the event
	 *		return true;
	 *   }
	 * });
	 * 
	 * // add the object at pos (10,10), z index 4
	 * me.game.add((new myButton(10,10)),4);
	 *
	 */
	me.GUI_Object = me.SpriteObject.extend({
	/** @scope me.GUI_Object.prototype */
	
		/**
		 * object can be clicked or not
		 * @public
		 * @type boolean
		 * @name me.GUI_Object#isClickable
		 */
		isClickable : true,
		
		// object has been updated (clicked,etc..)	
		updated : false,

		/**
		 * @Constructor
		 * @private
		 */
		 init : function(x, y, settings) {
			this.parent(x, y, 
						((typeof settings.image == "string") ? me.loader.getImage(settings.image) : settings.image), 
						settings.spritewidth, 
						settings.spriteheight);
		},

		/**
		 * return true if the object has been clicked
		 * @private
		 */
		update : function() {
			if (this.updated) {
				// clear the flag
				this.updated = false;
				return true;
			}
			return false;
		},

		
		/**
		 * function called when the object is clicked <br>
		 * to be overwritten <br>
		 * return true if we need to stop propagating the event
		 * @public
		 * @function
		 * @deprecated won't survive version 0.9.3
		 */
		clicked : function() {
			// don't propagate mouse event if clicked
			return true;
		},


		/**
		 * mouse event detection
		 * @private
		 */
		mouseEvent : function(x, y) {
			if ((x > this.left) && (x < this.right) && 
			    (y > this.top) && (y < this.bottom)) {
				// notify the object we have been clicked :)
				if (this.isClickable) {
					this.updated = this.clicked();
				}
			}
			return this.updated;
		}
	});

	/*---------------------------------------------------------*/
	// END END END
	/*---------------------------------------------------------*/
})(window);
/*
 * MelonJS Game Engine
 * Copyright (C) 2011, Olivier BIOT
 * http://www.melonjs.org
 *
 *
 */

(function($, undefined) {

	/************************************************************************************/
	/*      HUD FUNCTIONS :                                                             */
	/*      a basic HUD to be extended                                                  */
	/*                                                                                  */
	/************************************************************************************/

	/**
	 * Item skeleton for HUD element 
	 * @class
	 * @extends Object
	 * @memberOf me
	 * @constructor
	 * @param {int} x x position (relative to the HUD position)
	 * @param {int} y y position (relative to the HUD position)
	 * @param {int} [val="0"] default value
	 * @example
	 * // create a "score object" that will use a Bitmap font
	 * // to display the score value
	 * ScoreObject = me.HUD_Item.extend(
	 * {	
	 *    // constructor
	 *    init: function(x, y)
	 *    {
	 *       // call the parent constructor
	 *       this.parent(x, y);
	 *       // create a font
	 *       this.font = new me.BitmapFont("font16px", 16);
	 *    },
	 *    // draw function
	 *    draw : function (context, x, y)
	 *    {
	 *       this.font.draw (context, this.value, this.pos.x +x, this.pos.y +y);
	 *    }
	 * });
	 * 
	 * // add a default HUD to the game mngr (with no background)
	 * me.game.addHUD(0,0,480,100);
	 * // add the "score" HUD item
	 * me.game.HUD.addItem("score", new ScoreObject(470,10));
	 */
	me.HUD_Item = Object.extend(
	/** @scope me.HUD_Item.prototype */
	{
		init : function(x, y, val) {
			/**
			 * position of the item
			 * @public
			 * @type me.Vector2d
			 * @name me.HUD_Item#pos
			 */
			this.pos = new me.Vector2d(x || 0, y || 0);

			// visible or not...	
			this.visible = true;

			this.defaultvalue = val || 0;

			/**
			 * value of the item
			 * @public
			 * @type Int
			 * @name me.HUD_Item#value
			 */

			this.value = val || 0;

			this.updated = true;
		},

		/**
		 * reset the item to the default value
		 */
		reset : function() {
			this.set(this.defaultvalue);
		},
		
		/**
		 * set the item value to the specified one
		 */
		set : function(value) {
			this.value = value;
			this.updated = true;
			return true;
		},

		/**
		 * update the item value
		 * @param {int} value add the specified value
		 */
		update : function(value) {
			return this.set(this.value + value);
		},

		/**
		 * draw the HUD item
		 * @protected
		 * @param {Context2D} context 2D context
		 * @param {x} x
		 * @param {y} y
		 */
		draw : function(context, x, y) {
			;// to be extended
		}
	});
	/*---------------------------------------------------------*/

	/**
	 * HUD Object<br>
	 * There is no constructor function for me.HUD_Object<br>
	 * Object instance is accessible through me.game.HUD if previously initialized using me.game.addHUD(...);
	 * @class
	 * @extends Object
	 * @memberOf me
	 * @example
	 * // create a "score object" that will use a Bitmap font
	 * // to display the score value
	 * ScoreObject = me.HUD_Item.extend(
	 * {	
	 *    // constructor
	 *    init: function(x, y)
	 *    {
	 *       // call the parent constructor
	 *       this.parent(x, y);
	 *       // create a font
	 *       this.font = new me.BitmapFont("font16px", 16);
	 *    },
	 *    // draw function
	 *    draw : function (context, x, y)
	 *    {
	 *       this.font.draw (context, this.value, this.pos.x +x, this.pos.y +y);
	 *    }
	 * });
	 * 
	 * // add a default HUD to the game mngr (with no background)
	 * me.game.addHUD(0,0,480,100);
	 * // add the "score" HUD item
	 * me.game.HUD.addItem("score", new ScoreObject(470,10));
	 */


	me.HUD_Object = me.Rect.extend(
	/** @scope me.HUD_Object.prototype */
	{	
	
		/**
		 * @Constructor
		 * @private
		 */
		init : function(x, y, w, h, bg) {
			// call the parent constructor
			this.parent(new me.Vector2d(x || 0, y || 0), 
						w || me.video.getWidth(), h || me.video.getHeight());

			// default background color (if specified)
			this.bgcolor = bg;

			// hold all the items labels						
			this.HUDItems = {};
			// hold all the items objects
			this.HUDobj = [];
			// Number of items in the HUD
			this.objCount = 0;

			// visible or not...	
			this.visible = true;

			// state of HUD (to trigger redraw);
			this.HUD_invalidated = true;

			// create a canvas where to draw everything
			this.HUDCanvasSurface = me.video.createCanvasSurface(this.width, this.height);
			
			// this is a little hack to ensure the HUD is always the first draw
			this.z = 999;

		},

		/**
		 * add an item to the me.game.HUD Object
		 * @name me.HUD_Object#addItem
		 * @public
		 * @function
		 * @param {String} name name of the item
		 * @param {me.HUD_Item} item HUD Item to be added
		 * @example
		 * // add a "score" HUD item
		 * me.game.HUD.addItem("score", new ScoreObject(470,10));
		 */
		addItem : function(name, item) {
			this.HUDItems[name] = item;
			this.HUDobj.push(this.HUDItems[name]);
			this.objCount++;
			this.HUD_invalidated = true;
		},
		
		/**
		 * set the value of the specified item
		 * @name me.HUD_Object#setItemValue
		 * @public
		 * @function
		 * @param {String} name name of the item
		 * @param {int} val value to be set 
		 * @example
		 * // set the "score" item value to 100
		 * me.game.HUD.setItemValue("score", 100);
		 */
		setItemValue : function(name, value) {
			if (this.HUDItems[name] && (this.HUDItems[name].set(value) == true))
				this.HUD_invalidated = true;				
		},

		
		/**
		 * update (add) the value of the specified item
		 * @name me.HUD_Object#updateItemValue
		 * @public
		 * @function
		 * @param {String} name name of the item
		 * @param {int} val value to be set 
		 * @example
		 * // add 10 to the current "score" item value
		 * me.game.HUD.setItemValue("score", 10);
		 */
		updateItemValue : function(name, value) {
			if (this.HUDItems[name] && (this.HUDItems[name].update(value) == true))
				this.HUD_invalidated = true;
		},

		/**
		 * return the value of the specified item
		 * @name me.HUD_Object#getItemValue
		 * @public
		 * @function
		 * @param {String} name name of the item
		 * @return {int}
		 * @example
		 * // return the value of the "score" item
		 * score = me.game.HUD.getItemValue("score");
		 */
		getItemValue : function(name) {
			return (this.HUDItems[name]) ? this.HUDItems[name].value : 0;
		},
		
		
		/**
		 * return true if the HUD has been updated
		 * @private
		 */
		update : function() {
			return this.HUD_invalidated;
		},

		/**
		 * reset the specified item to default value
		 * @name me.HUD_Object#reset
		 * @public
		 * @function
		 * @param {String} [name="all"] name of the item
		 */		
		reset : function(name) {
			if (name != undefined) {
				// only reset the specified one
				if (this.HUDItems[name])
					this.HUDItems[name].reset();
				this.HUD_invalidated = true;
			} else {
				// reset everything
				this.resetAll();
			}
		},

		/**
		 * reset all items to default value
		 * @private
		 */
		resetAll : function() {
			for ( var i = this.objCount, obj; i--, obj = this.HUDobj[i];) {
				obj.reset();
			}
			this.HUD_invalidated = true;
		},

		/**
		 * override the default me.Rect get Rectangle definition
		 * since the HUD if a flaoting object
		 * (is this correct?)
		 * @private
		 * @return {me.Rect} new rectangle
		 */

		getRect : function() {
			p = this.pos.clone();
			p.add(me.game.viewport.pos);
			return new me.Rect(p, this.width, this.height);
		},

		/**
		 * draw the HUD
		 * @private
		 */
		draw : function(context) {
			if (this.HUD_invalidated) {
				if (this.bgcolor) {
					me.video.clearSurface(this.HUDCanvasSurface, this.bgcolor);
				}
				else {
					this.HUDCanvasSurface.canvas.width = this.HUDCanvasSurface.canvas.width;
				}
				for ( var i = this.objCount, obj; i--, obj = this.HUDobj[i];) {
					if (obj.visible) {
						obj.draw(this.HUDCanvasSurface, 0, 0);
						// clear the updated flag
						if (obj.updated) {
							obj.updated = false;
						}
					}
				}
			}
			// draw the HUD
			context.drawImage(this.HUDCanvasSurface.canvas, this.pos.x, this.pos.y);
			// reset the flag
			this.HUD_invalidated = false;
		}
	});


	/*---------------------------------------------------------*/
	// END END END
	/*---------------------------------------------------------*/
})(window);
/*
 * MelonJS Game Engine
 * Copyright (C) 2011, Olivier BIOT
 * http://www.melonjs.org
 *
 * Audio Mngt Objects
 *
 *
 */

(function($, undefined) {
	/*
	 * -----------------------------------------------------
	 * 
	 * a audio class singleton to manage the game fx & music
	 * -----------------------------------------------------
	 */

	/**
	 * There is no constructor function for me.audio.
	 * 
	 * @final
	 * @memberOf me
	 * @constructor Should not be called by the user.
	 */

	me.audio = (function() {
		// hold public stuff in our singletong
		var obj = {};

		// audio channel array
		var audio_channels = [];

		// supported Audio Format
		var supportedFormat = [ "mp3", "ogg", "wav" ];

		// Request format by the app/game
		var requestedFormat = null;

		// Active (supported) audio extension
		var activeAudioExt = -1;

		// loadcb function
		var load_cb = null;

		// current music
		var current_track = null;

		// enable/disable flag
		var sound_enable = true;

		// defaut reset value
		var reset_val = 0;// .01;

		// a retry counter
		var retry_counter = 0;

		/*
		 * ---------------------------------------------
		 * 
		 * PRIVATE STUFF
		 * 
		 * ---------------------------------------------
		 */

		/*
		 * ---
		 * 
		 * return the audio format extension supported by the browser ---
		 */

		function getSupportedAudioFormat() {

			var extIdx = 0;

			// check for sound support by the browser
			if (!me.sys.sound) {
				sound_enable = false;
				return;
			}

			// check for MP3
			if ((requestedFormat.search(/mp3/i) != -1) && obj.capabilities.mp3) {
				// console.log("mp3 audio supported");
				return supportedFormat[extIdx];
			}

			// check for OGG/Vorbis
			if ((requestedFormat.search(/ogg/i) != -1) && obj.capabilities.ogg) {
				// console.log("ogg audio supported");
				return supportedFormat[++extIdx];
			}

			// check for WAV
			if ((requestedFormat.search(/wav/i) != -1) && obj.capabilities.wav) {
				// console.log("wav audio supported");
				return supportedFormat[++extIdx];
			}

			// deactivate sound
			sound_enable = false;

			return -1;
		}
		;

		/*
		 * ---
		 * 
		 * return the specified sound ---
		 */

		function get(sound_id) {
			var channels = audio_channels[sound_id];
			// find which channel is available
			for ( var i = 0, soundclip; soundclip = channels[i++];) {
				if (soundclip.ended || !soundclip.currentTime)// soundclip.paused)
				{
					// console.log ("requested %s on channel %d",sound_id, i);
					soundclip.currentTime = reset_val;
					return soundclip;
				}
			}
			// else force on channel 0
			channels[0].pause();
			channels[0].currentTime = reset_val;
			return channels[0];
		}
		;

		/*
		 * ---
		 * 
		 * event listener callback on load error
		 * 
		 * ---
		 */

		function soundLoadError(sound_id) {
			// check the retry counter
			if (retry_counter++ > 3) {
				// something went wrong
				var errmsg = "melonJS: failed loading " + sound_id + "." + activeAudioExt;
				if (me.sys.stopOnAudioError===false) {
					// disable audio
					me.audio.disable();
					// call load callback if defined
					if (load_cb) {
						load_cb();
					}
					// warning
					console.log(errmsg + ", disabling audio");
				} else {
					// throw an exception and stop everything !
					throw errmsg;
				}
			// else try loading again !
			} else {
				audio_channels[sound_id][0].load();
			}
		};

		/*
		 * ---
		 * 
		 * event listener callback when a sound is loaded
		 * 
		 * ---
		 */

		function soundLoaded(sound_id, sound_channel) {
			// reset the retry counter
			retry_counter = 0;

			// create other "copy" channels if necessary
			if (sound_channel > 1) {
				var soundclip = audio_channels[sound_id][0];
				// clone copy to create multiple channel version
				for (var channel = 1; channel < sound_channel; channel++) {
					// make sure it's a new copy each time
					var node = soundclip.cloneNode(true);
					// fix for IE platform not properly
					// initializating everything when using cloneNode
					if (node.currentSrc.length == 0) {
						node.src = soundclip.src;
					}
					// allocate the new channel
					audio_channels[sound_id][channel] = node;
					audio_channels[sound_id][channel].load();
				}
			}
			// callback if defined
			if (load_cb) {
				load_cb();
			}
		}
		;

		/**
		 * play the specified sound
		 * 
		 * @name me.audio#play
		 * @public
		 * @function
		 * @param {String}
		 *            sound_id audio clip id
		 * @param {String}
		 *            [loop="false"] loop audio
		 * @param {Function}
		 *            [callback] callback function
		 * @example // play the "cling" audio clip me.audio.play("cling"); //
		 *          play & repeat the "engine" audio clip
		 *          me.audio.play("engine", true); // play the "gameover_sfx"
		 *          audio clip and call myFunc when finished
		 *          me.audio.play("gameover_sfx", false, myFunc);
		 */

		function _play_audio_enable(sound_id, loop, callback) {
			// console.log("play!!");
			var soundclip = get(sound_id);

			soundclip.loop = loop || false;
			soundclip.play();

			// set a callback if defined
			if (callback && !loop) {
				soundclip.addEventListener('ended', function(event) {
					soundclip.removeEventListener('ended', arguments.callee,
							false);
					// soundclip.pause();
					// soundclip.currentTime = reset_val;
					// execute a callback if required
					callback();
				}, false);
			}

		}
		;

		/*
		 * ---
		 * 
		 * play_audio with simulated callback ---
		 */

		function _play_audio_disable(sound_id, loop, callback) {
			// check if a callback need to be called
			if (callback && !loop) {
				// SoundMngr._play_cb = callback;
				setTimeout(callback, 2000); // 2 sec as default timer ?
			}
		}
		;

		/*
		 * ---------------------------------------------
		 * 
		 * PUBLIC STUFF
		 * 
		 * ---------------------------------------------
		 */

		// audio capabilities
		obj.capabilities = {
			mp3 : false,
			ogg : false,
			ma4 : false,
			wav : false,
		};

		/**
		 * initialize the audio engine<br>
		 * the melonJS loader will try to load audio files corresponding to the
		 * browser supported audio format<br>
		 * if not compatible audio format is found, audio will be disabled
		 * 
		 * @name me.audio#init
		 * @public
		 * @function
		 * @param {String}
		 *            audioFormat audio format provided ("mp3, ogg, wav")
		 * @example // initialize the "sound engine", giving "mp3" and "ogg" as
		 *          available audio format me.audio.init("mp3,ogg"); // i.e. on
		 *          Safari, the loader will load all audio.mp3 files, // on
		 *          Opera the loader will however load audio.ogg files
		 */
		obj.init = function(audioFormat) {
			if (audioFormat)
				requestedFormat = new String(audioFormat);
			else
				// if no param is given to init we use mp3 by default
				requestedFormat = new String("mp3");

			// detect the prefered audio format
			activeAudioExt = getSupportedAudioFormat();

			if (sound_enable)
				obj.play = _play_audio_enable;
			else
				obj.play = _play_audio_disable;

			return sound_enable;
		};

		/*
		 * ---
		 * 
		 * 
		 * ---
		 */

		/**
		 * set call back when a sound (and instances) is/are loaded
		 * 
		 * @name me.audio#setLoadCallback
		 * @private
		 * @function
		 */
		obj.setLoadCallback = function(callback) {
			load_cb = callback;
		};

		/**
		 * return true if audio is enable
		 * 
		 * @see me.audio#enable
		 * @name me.audio#isAudioEnable
		 * @public
		 * @function
		 * @return {boolean}
		 */
		obj.isAudioEnable = function() {
			return sound_enable;
		};

		/**
		 * enable audio output <br>
		 * only useful if audio supported and previously disabled through
		 * audio.disable()
		 * 
		 * @see me.audio#disable
		 * @name me.audio#enable
		 * @public
		 * @function
		 */
		obj.enable = function() {
			sound_enable = me.sys.sound;

			if (sound_enable)
				obj.play = _play_audio_enable;
			else
				obj.play = _play_audio_disable;
		};

		/**
		 * disable audio output
		 * 
		 * @name me.audio#disable
		 * @public
		 * @function
		 */
		obj.disable = function() {
			sound_enable = false;
			obj.play = _play_audio_disable;
		};

		/**
		 * load a sound sound struct : name: id of the sound src: src path
		 * channel: number of channel to allocate
		 * 
		 * @private
		 */
		obj.load = function(sound) {
			// do nothing if no compatible format is found
			if (activeAudioExt == -1)
				return 0;

			// var soundclip = document.createElement("audio");

			var soundclip = new Audio(sound.src + sound.name + "."
					+ activeAudioExt + me.nocache);

			// soundclip.autobuffer = true; // obsolete
			soundclip.preload = 'auto';

			soundclip.addEventListener('canplaythrough', function(e) {
				// console.log(soundclip);
				this.removeEventListener('canplaythrough', arguments.callee,
						false);
				soundLoaded(sound.name, sound.channel);
			}, false);

			soundclip.addEventListener("error", function(e) {
				soundLoadError(sound.name);
			}, false);

			soundclip.src = sound.src + sound.name + "." + activeAudioExt
					+ me.nocache;

			// document.body.appendChild(soundclip);

			// load it
			soundclip.load();

			audio_channels[sound.name] = [ soundclip ];

			return 1;
		};

		/**
		 * stop the specified sound on all channels
		 * 
		 * @name me.audio#stop
		 * @public
		 * @function
		 * @param {String}
		 *            sound_id audio clip id
		 * @example me.audio.stop("cling");
		 */
		obj.stop = function(sound_id) {
			if (sound_enable) {
				var sound = audio_channels[sound_id];
				for (var channel_id = sound.length; channel_id--;) {
					sound[channel_id].pause();
					// force rewind to beginning
					sound[channel_id].currentTime = reset_val;
				}

			}
		};

		/**
		 * pause the specified sound on all channels<br>
		 * this function does not reset the currentTime property
		 * 
		 * @name me.audio#pause
		 * @public
		 * @function
		 * @param {String}
		 *            sound_id audio clip id
		 * @example me.audio.pause("cling");
		 */
		obj.pause = function(sound_id) {
			if (sound_enable) {
				var sound = audio_channels[sound_id];
				for (var channel_id = sound.length; channel_id--;) {
					sound[channel_id].pause();
				}

			}
		};

		/**
		 * play the specified audio track<br>
		 * this function automatically set the loop property to true<br>
		 * and keep track of the current sound being played.
		 * 
		 * @name me.audio#playTrack
		 * @public
		 * @function
		 * @param {String}
		 *            sound_id audio track id
		 * @example me.audio.playTrack("awesome_music");
		 */
		obj.playTrack = function(sound_id) {
			if (sound_enable) {
				if (current_track != null)
					obj.stopTrack();

				current_track = get(sound_id);

				if (current_track) {
					current_track.loop = true;
					current_track.play();
				}
			}
		};

		/**
		 * stop the current audio track
		 * 
		 * @see me.audio#playTrack
		 * @name me.audio#stopTrack
		 * @public
		 * @function
		 * @example // play a awesome music me.audio.playTrack("awesome_music"); //
		 *          stop the current music me.audio.stopTrack();
		 */
		obj.stopTrack = function() {
			if (sound_enable && current_track) {
				current_track.pause();
				current_track = null;
			}
		};

		/**
		 * pause the current audio track
		 * 
		 * @name me.audio#pauseTrack
		 * @public
		 * @function
		 * @example me.audio.pauseTrack();
		 */
		obj.pauseTrack = function() {
			if (sound_enable && current_track) {
				current_track.pause();
			}
		};

		/**
		 * resume the previously paused audio track
		 * 
		 * @name me.audio#resumeTrack
		 * @public
		 * @function
		 * @param {String}
		 *            sound_id audio track id
		 * @example // play a awesome music me.audio.playTrack("awesome_music"); //
		 *          pause the audio track me.audio.pauseTrack(); // resume the
		 *          music me.audio.resumeTrack();
		 */
		obj.resumeTrack = function() {
			if (sound_enable && current_track) {
				current_track.play();
			}
		};

		// return our object
		return obj;

	})();

	/*---------------------------------------------------------*/
	// END END END
	/*---------------------------------------------------------*/
})(window);
/*
 * MelonJS Game Engine
 * Copyright (C) 2011, Olivier BIOT
 * http://olivierbiot.wordpress.com/
 *
 *
 * video Mngt 
 *
 *
 */

(function($, undefined) {
	/**
	 * a Timer object to manage time function (FPS, Game Tick, Time...)<p>
	 * There is no constructor function for me.timer
	 * @final
	 * @memberOf me
	 * @constructor Should not be called by the user.
	 */
	me.timer = (function() {
		// hold public stuff in our api
		var api = {};

		/*---------------------------------------------
			
			PRIVATE STUFF
				
			---------------------------------------------*/

		//hold element to display fps
		var htmlCounter = null;
		var debug = false;
		var framecount = 0;
		var framedelta = 0;

		/* fps count stuff */
		var last = 0;
		var now = 0;
		var delta = 0;
		var step = Math.ceil(1000 / me.sys.fps); // ROUND IT ?
		// define some step with some margin
		var minstep = (1000 / me.sys.fps) * 1.25; // IS IT NECESSARY?

		/* ---
		
			update the fps counter
			
			---*/
		function draw(fps) {
			htmlCounter.replaceChild(document.createTextNode("(" + fps + "/"
					+ me.sys.fps + " fps)"), htmlCounter.firstChild);
		}
		;

		/*---------------------------------------------
			
			PUBLIC STUFF
				
			---------------------------------------------*/

		/**
		 * last game tick value
		 * @public
		 * @type {Int}
		 * @name me.timer#tick
		 */
		api.tick = 1.0;

		/* ---
		
			init our time stuff
			
			---							*/
		api.init = function() {
			// check if we have a framecounter display in the HTML
			htmlCounter = document.getElementById("framecounter");
			debug = (htmlCounter !== null);

			// reset variables to initial state
			api.reset();
		};

		/**
		 * reset time (e.g. usefull in case of pause)
		 * @name me.timer#reset
		 * @private
		 * @function
		 */
		api.reset = function() {
			// set to "now"
			now = last = new Date().getTime();
			// reset delta counting variables
			framedelta = 0;
			framecount = 0;

		};

		/**
		 * return the current time
		 * @name me.timer#getTime
		 * @return {Date}
		 * @function
		 */
		api.getTime = function() {
			return now;
		};

		/* ---
		
			update game tick
			should be called once a frame
			
			---                           */
		api.update = function() {
			last = now;
			now = new Date().getTime();

			delta = (now - last);

			// only draw the FPS on in the HTML page 
			if (debug) {
				framecount++;
				framedelta += delta;
				if (framecount % 10 == 0) {
					var lastfps = ~~((1000 * framecount) / framedelta);
					// clamp the result and "draw" it
					draw(lastfps.clamp(0, me.sys.fps));
					framedelta = 0;
					framecount = 0;
				}
			}
			// get the game tick
			api.tick = (delta > minstep && me.sys.interpolation) ? delta / step	: 1;
		};

		// return our apiect
		return api;

	})();
	/************************************************************************************/

	/**
	 * video functions
	 * There is no constructor function for me.video
	 * @final
	 * @memberOf me
	 * @constructor Should not be called by the user.
	 */
	me.video = (function() {
		// hold public stuff in our apig
		var api = {};

		// internal variables
		var canvas = null;
		var context2D = null;
		var backBufferCanvas = null;
		var backBufferContext2D = null;
		var wrapper = null;

		var double_buffering = false;
		var game_width_zoom = 0;
		var game_height_zoom = 0;

		/*---------------------------------------------
			
			PUBLIC STUFF
				
			---------------------------------------------*/

		/* ---
		
			init the video part
			
			
			---							*/
		/**
		 * init the "video" part<p>
		 * return false if initialization failed (canvas not supported)
		 * @name me.video#init
		 * @function
		 * @param {String} wrapper the "div" element id to hold the canvas in the HTML file
		 * @param {Int} width game width
		 * @param {Int} height game height
		 * @param {Boolean} [double_buffering] enable/disable double buffering
		 * @param {Number} [scale] enable scaling of the canvas (note : if scale is used, double_buffering must be enabled)
		 * @return {Boolean}
		 * @example
		 * // init the video with a 480x320 canvas
		 * if (!me.video.init('jsapp', 480, 320))
		 * {
		 *    alert("Sorry but your browser does not support html 5 canvas !");
		 *    return;
		 * }
		 */
		api.init = function(wrapperid, game_width, game_height,
				doublebuffering, scale) {
			double_buffering = doublebuffering || false;

			// zoom only work with the double buffering since we 
			// actually zoom the backbuffer before rendering it
			me.sys.scale = double_buffering === true ? scale || 1.0 : 1.0;

			game_width_zoom = game_width * me.sys.scale;
			game_height_zoom = game_height * me.sys.scale;

			wrapper = document.getElementById(wrapperid);

			canvas = document.createElement("canvas");

			canvas.setAttribute("width", (game_width_zoom) + "px");
			canvas.setAttribute("height", (game_height_zoom) + "px");
			canvas.setAttribute("border", "0px solid black");

			// add our canvas
			wrapper.appendChild(canvas);

			// check if WebGL feature is supported & required
			if (me.sys.enableWebGL && window.WebGLRenderingContext) {
				// in case the library is not loaded
				try {
					// try to enable WebGL
					WebGL2D.enable(canvas);
					context2D = canvas.getContext('webgl-2d');
					// enable cacheImage feature, so that we use
					// canvas and not Image for assets.
					me.sys.cacheImage = true;
				} catch (e) {
					// just to be sure
					context2D = null;
				}
			}

			// if context2D not initialized, 
			if (context2D == null) {
				// make sure it's disabled
				me.sys.enableWebGL = false;

				if (!canvas.getContext)
					return false;

				context2D = canvas.getContext('2d');
			}

			// create the back buffer if we use double buffering
			if (double_buffering) {
				backBufferContext2D = api.createCanvasSurface(game_width,
						game_height);
				backBufferCanvas = backBufferContext2D.canvas;
			} else {
				backBufferContext2D = context2D;
				backBufferCanvas = context2D.canvas;
			}
			return true;
		};

		/**
		 * return a reference to the wrapper
		 * @name me.video#getWrapper
		 * @function
		 * @return {Document}
		 */
		api.getWrapper = function() {
			return wrapper;
		};

		/**
		 * return the width of the display canvas (before scaling)
		 * @name me.video#getWidth
		 * @function
		 * @return {Int}
		 */
		api.getWidth = function() {
			return backBufferCanvas.width;

		};

		/**
		 * return the height of the display canvas (before scaling)
		 * @name me.video#getHeight
		 * @function
		 * @return {Int}
		 */
		api.getHeight = function() {
			return backBufferCanvas.height;
		};

		/**
		 * allocate and return a new Canvas 2D surface
		 * @name me.video#createCanvasSurface
		 * @function
		 * @param {Int} width canvas width
		 * @param {Int} height canvas height
		 * @return {Context2D}
		 */
		api.createCanvasSurface = function(width, height) {
			var privateCanvas = document.createElement("canvas");

			privateCanvas.width = width || backBufferCanvas.width;
			privateCanvas.height = height || backBufferCanvas.height;

			/* !! this should be working, no ?
			if (me.sys.enableWebGL)
			{   
			   WebGL2D.enable(privateCanvas);
			   return privateCanvas.getContext('webgl-2d');
			}
			else
			{ 
			 */
			return privateCanvas.getContext('2d');
			//}
		};

		/**
		 * return a reference of the display canvas
		 * @name me.video#getScreenCanvas
		 * @function
		 * @return {Canvas}
		 */
		api.getScreenCanvas = function() {
			//console.log(VideoMngr._canvas);
			return canvas;
		};

		/**
		 * return a reference to the screen framebuffer
		 * @name me.video#getScreenFrameBuffer
		 * @function
		 * @return {Context2D}
		 */
		api.getScreenFrameBuffer = function() {
			return backBufferContext2D;
		};

		/* ---
		
			Update the display size (zoom ratio change)
			if no parameter called from the outside (select box)
			---								*/

		/**
		 * change the display scaling factor
		 * @name me.video#updateDisplaySize
		 * @function
		 * @param {Number} scale scaling value
		 */
		api.updateDisplaySize = function(scale) {
			if (double_buffering) {
				if (scale)
					me.sys.scale = scale;
				else
					// to be changed by something else :)
					me.sys.scale = document.getElementById("screen size").value;

				game_width_zoom = backBufferCanvas.width * me.sys.scale;
				game_height_zoom = backBufferCanvas.height * me.sys.scale;

				canvas.width = game_width_zoom; // in pixels
				canvas.height = game_height_zoom; // in pixels

			}
		};

		/**
		 * Clear the specified context with the given color
		 * @name me.video#clearSurface
		 * @function
		 * @param {Context2D} context
		 * @param {Color} col
		 */
		api.clearSurface = function(context, col) {
			context.fillStyle = col;
			context.fillRect(0, 0, context.canvas.width, context.canvas.height);
		};

		/**
		 * scale & keep canvas centered<p>
		 * usefull for zooming effect
		 * @name me.video#scale
		 * @function
		 * @param {Context2D} context
		 * @param {scale} scale
		 */
		api.scale = function(context, scale) {
			context
					.translate(
							-(((context.canvas.width * scale) - context.canvas.width) >> 1),
							-(((context.canvas.height * scale) - context.canvas.height) >> 1));

			context.scale(scale, scale);

		};

		/**
		 * enable/disable Alpha for the specified context
		 * @name me.video#setAlpha
		 * @function
		 * @param {Context2D} context
		 * @param {Boolean} enable
		 */
		api.setAlpha = function(context, enable) {
			context.globalCompositeOperation = enable ? "source-over" : "copy";
		};

		/**
		 * render the main framebuffer on screen
		 * @name me.video#blitSurface
		 * @function
		 */
		api.blitSurface = function() {
			if (double_buffering) {
				api.blitSurface = function() {
					//FPS.update();
					context2D.drawImage(backBufferCanvas, 0, 0,
							backBufferCanvas.width, backBufferCanvas.height, 0,
							0, game_width_zoom, game_height_zoom);
					
				};
			} else {
				// "empty" function, as we directly render stuff on "context2D"
				api.blitSurface = function() {
				};
			}
			api.blitSurface();
		};

		/**
		 * apply the specified filter to the main canvas
		 * and return a new canvas object with the modified output<br>
		 * (!) Due to the internal usage of getImageData to manipulate pixels,
		 * this function will throw a Security Exception with FF if used locally
		 * @name me.video#applyRGBFilter
		 * @function
		 * @param {Object} object Canvas or Image Object on which to apply the filter
		 * @param {String} effect "b&w", "brightness", "transparent"
		 * @param {String} option : level [0...1] (for brightness), color to be replaced (for transparent) 
		 * @return {Context2D} context object
		 */
		api.applyRGBFilter = function(object, effect, option) {
			//create a output canvas using the given canvas or image size
			var fcanvas = api.createCanvasSurface(object.width, object.height);
			// get the pixels array of the give parameter
			var imgpix = me.utils.getPixels(object);
			// pointer to the pixels data
			var pix = imgpix.data;

			// apply selected effect
			switch (effect) {
			case "b&w": {
				for ( var i = 0, n = pix.length; i < n; i += 4) {
					var grayscale = (3 * pix[i] + 4 * pix[i + 1] + pix[i + 2]) >>> 3;
					pix[i] = grayscale; // red
					pix[i + 1] = grayscale; // green
					pix[i + 2] = grayscale; // blue
				}
				break;
			}

			case "brightness": {
				// make sure it's between 0.0 and 1.0
				var brightness = Math.abs(option).clamp(0.0, 1.0);
				for ( var i = 0, n = pix.length; i < n; i += 4) {

					pix[i] *= brightness; // red
					pix[i + 1] *= brightness; // green
					pix[i + 2] *= brightness; // blue
				}
				break;
			}

			case "transparent": {
				for ( var i = 0, n = pix.length; i < n; i += 4) {
					if (me.utils.RGBToHex(pix[i], pix[i + 1], pix[i + 2]) === option) {
						pix[i + 3] = 0;
					}
				}
				break;
			}

			default:
				return null;
			}

			// put our modified image back in the new filtered canvas
			fcanvas.putImageData(imgpix, 0, 0);

			// return it
			return fcanvas;
		};

		// return our api
		return api;

	})();

	/*---------------------------------------------------------*/
	// END END END
	/*---------------------------------------------------------*/
})(window);
/*
 * MelonJS Game Engine
 * Copyright (C) 2011, Olivier BIOT
 * http://www.melonjs.org
 *
 */

(function($, undefined) {

	/**
	 * There is no constructor function for me.input.
	 * @final
	 * @memberOf me
	 * @constructor Should not be called by the user.
	 */
	me.input = (function() {

		// hold public stuff in our singletong
		var obj = {};

		/*---------------------------------------------
			
			PRIVATE STUFF
				
		  ---------------------------------------------*/

		// list of binded keys
		var KeyBinding = [];

		// corresponding actions
		var keyStatus = [];

		// lock enable flag for keys
		var keyLock = [];
		// actual lock status of each key
		var keyLocked = [];

		// callback function for mouse & gyro
		var mouseEventCB = null;
		var gyroEventCB = null;

		// some usefull flags
		var keyboardInitialized = false;

		/*---
			
			enable keyboard event
				
			---*/
		function enableKeyboardEvent(enable) {
			if (enable) {
				// Event Management
				if (!keyboardInitialized) {
					$.addEventListener('keydown', keydown, false);
					$.addEventListener('keyup', keyup, false);
				}
			} else {
				// remove the even listeners
				$.removeEventListener('keydown', keydown, false);
				$.removeEventListener('keyup', keyup, false);
			}
			keyboardInitialized = enable;
		};

		/* ---
			
			prevent event propagation
				
			---*/
		function preventDefault(e) {
			e.stopPropagation();
			if (e.preventDefault)
				e.preventDefault();
			e.returnValue = false;
			// this is apprently needed on some platforms
			e.cancelBubble = true;
		};

		/* ---
			
			key down event
				
			---	*/
		/*
		function dispatchEvent (e)
		{
			var action = KeyBinding[e.keyCode || e.which];
			
			if(action)
			{
				console.log(e);
				if ((e.type === "keydown")&&(!keyLocked[action]))
				{
						keyStatus[action] = true;
						// lock the key if requested
						keyLocked[action] = keyLock[action];
				} 
				else if(e.type === "keyup")
				{
					keyStatus[action] = false;
					keyLocked[action] = false;
				}
			}
			// prevent event propagation
			preventDefault(event);
			return false;
		};
		 */

		function keydown(e) {

			var action = KeyBinding[e.keyCode || e.which];

			if (action) {
				//console.log(e, action);

				//console.log(action);
				if (!keyLocked[action]) {
					keyStatus[action] = true;
					// lock the key if requested
					keyLocked[action] = keyLock[action];
				}
				// prevent event propagation
				preventDefault(e);
				return false;
			}
			return true;
		}
		;

		/* ---
			
			key up event
				
			---	*/
		function keyup(e) {

			var action = KeyBinding[e.keyCode || e.which];

			//console.log(e, action);

			if (action) {

				keyStatus[action] = false;
				keyLocked[action] = false;
				// prevent the event propagation
				preventDefault(e);
				return false;
			}
			return true;

		}
		;

		/* ---
		
			 mouse event management (click)
			
			---										*/
		function onMouseEvent(e) {
			var x = e.clientX - me.video.getScreenCanvas().offsetLeft;
			var y = e.clientY - me.video.getScreenCanvas().offsetTop;

			// propagate the event to the callback with x,y coords
			mouseEventCB(x, y);

		}
		;

		/* ---
			
				 event management (Gyroscopic)
				
				---										*/
		function onGyroEvent(event) {
			// http://www.mobilexweb.com/samples/ball.html
			// http://www.mobilexweb.com/blog/safari-ios-accelerometer-websockets-html5
			// 
			// ax = event.accelerationIncludingGravity.x;
			// ay = event.accelerationIncludingGravity.y;

			// use acceleration instead on iphone4  
			// event.accelerationIncludingGravity.x
			// event.accelerationIncludingGravity.y
			// event.accelerationIncludingGravity.z

			// Gyroscope
			// window.ondeviceorientation = function(event) {
			// event.alpha
			// event.beta
			// event.gamma
			//}
		}
		;

		/*---------------------------------------------
			
			PUBLIC STUFF
				
		  ---------------------------------------------*/

		/**
		 * list of mappable keys :
		 * LEFT, UP, RIGHT, DOWN, ENTER, SHIFT, CTRL, ALT, PAUSE, ESC, ESCAPE, [0..9], [A..Z]
		 * @public
		 * @enum {number}
		 * @name me.input#KEY
		 */
		obj.KEY = {
			'LEFT' : 37,
			'UP' : 38,
			'RIGHT' : 39,
			'DOWN' : 40,
			'ENTER' : 13,
			'SHIFT' : 16,
			'CTRL' : 17,
			'ALT' : 18,
			'PAUSE' : 19,
			'ESC' : 27,
			'SPACE' : 32,
			'0' : 48,
			'1' : 49,
			'2' : 50,
			'3' : 51,
			'4' : 52,
			'5' : 53,
			'6' : 54,
			'7' : 55,
			'8' : 56,
			'9' : 57,
			'A' : 65,
			'B' : 66,
			'C' : 67,
			'D' : 68,
			'E' : 69,
			'F' : 70,
			'G' : 71,
			'H' : 72,
			'I' : 73,
			'J' : 74,
			'K' : 75,
			'L' : 76,
			'M' : 77,
			'N' : 78,
			'O' : 79,
			'P' : 80,
			'Q' : 81,
			'R' : 82,
			'S' : 83,
			'T' : 84,
			'U' : 85,
			'V' : 86,
			'W' : 87,
			'X' : 88,
			'Y' : 89,
			'Z' : 90,
		};

		/**
		 * return the key press status of the specified action
		 * @name me.input#isKeyPressed
		 * @public
		 * @function
		 * @example
		 * if (me.input.isKeyPressed('left'))
		 * {
		 *    //do something
		 * }
		 * else if (me.input.isKeyPressed('right'))
		 * {
		 *    //do something else...
		 * }
		 *
		 */

		obj.isKeyPressed = function(action) {
			if (keyStatus[action]) {
				if (keyLock[action]) {
					keyLocked[action] = true;
					// "eat" the event
					keyStatus[action] = false;
				}
				return true;
			}
			return false;
		};

		/**
		 * return the key status of the specified action
		 * @name me.input#keyStatus
		 * @public
		 * @function
		 * @return {boolean} down (true) or up(false)
		 */

		obj.keyStatus = function(action) {
			return (keyLocked[action] === true) ? true : keyStatus[action];
		};

		/**
		 * associate a user defined action to a keycode
		 * @name me.input#bindKey
		 * @public
		 * @function
		 * @param {me.input#KEY} keycode
		 * @param {String} action user defined corresponding action
		 * @param {boolean} lock cancel the keypress event once read
		 * @example
		 * // enable the keyboard
		 * me.input.bindKey(me.input.KEY.LEFT,  "left");
		 * me.input.bindKey(me.input.KEY.RIGHT, "right");
		 * me.input.bindKey(me.input.KEY.X,     "jump", true);
		 */
		obj.bindKey = function(keycode, action, lock) {
			if (!keyboardInitialized)
				enableKeyboardEvent(true);

			KeyBinding[keycode] = action;

			keyLock[action] = lock ? lock : false;
			keyLocked[action] = false;
			//console.log(this);
		};

		/**
		 * unbind the defined keycode
		 * @name me.input#unbindKey
		 * @public
		 * @function
		 * @example
		 * me.input.unbindKey(me.input.KEY.LEFT);
		 */
		obj.unbindKey = function(keycode) {
			// clear the event status
			keyStatus[KeyBinding[keycode]] = false;
			keyLock[KeyBinding[keycode]] = false;
			// remove the key binding
			KeyBinding[keycode] = null;
		};

		/**
		 * enable mouse event
		 * @name me.input#enableMouseEvent
		 * @public
		 * @function
		 * @deprecated to be rewritten
		 */
		obj.enableMouseEvent = function(enable, callback) {
			if (enable) {
				// add a listener for the mouse
				me.video.getScreenCanvas().addEventListener('click',
						onMouseEvent, false);
				// set the callback
				mouseEventCB = callback || me.game.mouseEvent.bind(me.game);
			} else {
				me.video.getScreenCanvas().removeEventListener('click',
						onMouseEvent, false);
			}
		};

		/**
		 * enable gyroscopic event (not implemented)
		 * @name me.input#enableGyroscopicEvent
		 * @public
		 * @function
		 */
		obj.enableGyroscopicEvent = function(enable, callback) {
			if ($.sys.gyro) {
				// add a listener for the mouse
				$.ondevicemotion = enable ? onGyroEvent : null;
				// set the callback
				gyroEventCB = enable ? callback : null;
			}

		};

		// return our object
		return obj;

	})();

	/*---------------------------------------------------------*/
	// END END END
	/*---------------------------------------------------------*/
})(window);
/*
 * MelonJS Game Engine
 * Copyright (C) 2011, Olivier BIOT
 * http://www.melonjs.org
 *
 *
 */

(function($, undefined) {

	/**
	 *  Base64 decoding
	 *  @see <a href="http://www.webtoolkit.info/">http://www.webtoolkit.info/</A>
	 */
	var Base64 = (function() {

		// hold public stuff in our singletong
		var singleton = {};

		// private property
		var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

		// public method for decoding
		singleton.decode = function(input) {
			
			// make sure our input string has the right format
			input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
			
			if (me.sys.nativeBase64) {
				// use native decoder
				return $.atob(input);
			}
			else {
				// use cross-browser decoding
				var output = [], chr1, chr2, chr3, enc1, enc2, enc3, enc4, i = 0;

				while (i < input.length) {
					enc1 = _keyStr.indexOf(input.charAt(i++));
					enc2 = _keyStr.indexOf(input.charAt(i++));
					enc3 = _keyStr.indexOf(input.charAt(i++));
					enc4 = _keyStr.indexOf(input.charAt(i++));

					chr1 = (enc1 << 2) | (enc2 >> 4);
					chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
					chr3 = ((enc3 & 3) << 6) | enc4;

					output.push(String.fromCharCode(chr1));

					if (enc3 != 64) {
						output.push(String.fromCharCode(chr2));
					}
					if (enc4 != 64) {
						output.push(String.fromCharCode(chr3));
					}
				}

				output = output.join('');
				return output;
			}
		};

		return singleton;

	})();

	/**
	 * a collection of utility Function
	 * @final
	 * @memberOf me
	 * @private
	 * @constructor Should not be called by the user.
	 */

	me.utils = (function() {
		// hold public stuff in our singletong
		var api = {};

		/*---------------------------------------------
			
		   PRIVATE STUFF
				
		 ---------------------------------------------*/

		// cache rgb converted value
		var rgbCache = {};
		
		// guid default value
		var GUID_base  = "";
		var GUID_index = 0;


		/*---------------------------------------------
			
			PUBLIC STUFF
				
			---------------------------------------------*/

		/**
		 * Decode a base64 encoded string into a binary string
		 *
		 * @param {String} input Base64 encoded data
		 * @return {String} Binary string
		 */
		api.decodeBase64 = function(input) {
			return Base64.decode(input);
		};

		/**
		 * Decode a base64 encoded string into a byte array
		 *
		 * @param {String} input Base64 encoded data
		 * @param {Int} [bytes] number of bytes per array entry
		 * @return {Int[]} Array of bytes
		 */
		api.decodeBase64AsArray = function(input, bytes) {
			bytes = bytes || 1;

			var dec = Base64.decode(input), ar = [], i, j, len;

			for (i = 0, len = dec.length / bytes; i < len; i++) {
				ar[i] = 0;
				for (j = bytes - 1; j >= 0; --j) {
					ar[i] += dec.charCodeAt((i * bytes) + j) << (j << 3);
				}
			}
			return ar;
		};

		/**
		 * Decode a CSV encoded array into a binary array
		 *
		 * @param  {String} input CSV formatted data
		 * @param  {Int} limit row split limit
		 * @return {Int[]} Int Array
		 */
		api.decodeCSV = function(input, limit) {
			input = input.trim().split("\n");

			var result = [];
			for ( var i = 0; i < input.length; i++) {
				entries = input[i].split(",", limit);
				for ( var e = 0; e < entries.length; e++) {
					result.push(+entries[e]);
				}
			}
			return result;
		};

		/* ---
		 
			enable the nocache mechanism
		  
		  ---*/
		api.setNocache = function(enable) {
			me.nocache = enable ? "?" + parseInt(Math.random() * 10000000) : '';
		};

		// a Hex to RGB color function
		api.HexToRGB = function(h, a) {
			// remove the # if present
			h = (h.charAt(0) == "#") ? h.substring(1, 7) : h;
			// check if we already have the converted value cached
			if (rgbCache[h] == null) {
				// else add it (format : "r,g,b")
				rgbCache[h] = parseInt(h.substring(0, 2), 16) + ","
						+ parseInt(h.substring(2, 4), 16) + ","
						+ parseInt(h.substring(4, 6), 16);
			}
			return (a ? "rgba(" : "rgb(") + rgbCache[h]
					+ (a ? "," + a + ")" : ")");
		};

		// a Hex to RGB color function
		api.RGBToHex = function(r, g, b) {
			return r.toHex() + g.toHex() + b.toHex();
		};
		
		// return the given canvas or image pixels
		api.getPixels = function(arg) {
			if (arg instanceof HTMLImageElement) {
				var c = me.video.createCanvasSurface(arg.width, arg.height);
				c.drawImage(arg, 0, 0);
				return c.getImageData(0, 0, arg.width, arg.height);
			} else { 
				// canvas !
				return arg.getContext('2d').getImageData(0, 0, arg.width, arg.height);
			}
		};
   
		// reset the GUID Base Name
		// the idea here being to have a unique ID
		// per level / object
		api.resetGUID = function(base) {
			// also ensure it's only 8bit ASCII characters
			GUID_base  = base.toUpperCase().toHex();
			GUID_index = 0;
		};
      
		// create and return a very simple GUID
		// Game Unique ID
		api.createGUID = function() {
			return GUID_base + "-" + (GUID_index++);
		};
		
		// apply friction to a force
		api.applyFriction = function(v, f) {
			return (v+f<0)?v+(f*me.timer.tick):(v-f>0)?v-(f*me.timer.tick):0;
		};

		// return our object
		return api;

	})();

	/*---------------------------------------------------------*/
	// END END END
	/*---------------------------------------------------------*/
})(window);
/*
 * MelonJS Game Engine
 * Copyright (C) 2011, Olivier BIOT
 * http://www.melonjs.org
 *
 *
 */

(function($, undefined) {

	/************************************************************************************/
	/*      Game stat FUNCTIONS :                                                       */
	/*      a basic object to store and retreive values                                 */
	/*                                                                                  */
	/************************************************************************************/

	/* ----
		Item skeleton for game stat element
	
			--- */

	function Stat_Item(val) {
		this.defaultvalue = val || 0;
		this.value = val || 0;
		this.updated = true;
	};

	/* ----
		
		reset to default value
		
		--- */

	Stat_Item.prototype.reset = function() {
		this.set(this.defaultvalue);
	};

	/* ----
		
		update the value of an item
		
		--- */

	Stat_Item.prototype.update = function(val) {
		return this.set(this.value + val);
	};
	
	/** 
      * Sets the value of an item 
      */ 
    Stat_Item.prototype.set = function(value) { 
		this.value = value; 
		this.updated = true; 
		return this.updated; 
	}; 

	/*---------------------------------------------------------*/

	/**
	 * manage game statistics<p>
	 * me.gamestat can be used to store useful values during the game<p>
	 * there is no constructor for me.gamestat
	 * @final
	 * @memberOf me
	 * @constructor Should not be called by the user.
	 */
	me.gamestat = (function() {

		// hold public stuff in our singletong
		var singleton = {};

		/*---------------------------------------------
			
			PRIVATE STUFF
				
		  ---------------------------------------------*/
		// hold all the items							
		var items = {};
		var obj = [];
		var objCount = 0;

		/*---------------------------------------------
			
			PUBLIC STUFF
				
		  ---------------------------------------------*/

		/**
		 * add an item to the me.gamestat Object
		 * @name me.gamestat#add
		 * @public
		 * @function
		 * @param {String} name name of the item
		 * @param {int} [val="0"] default value
		 * @example
		 * // add a "stars" item
		 * me.gamestat.add("stars", 0);
		 */
		singleton.add = function(name, val) {
			items[name] = new Stat_Item(val);
			obj.push(items[name]);
			objCount++;
		};

		/**
		 * update an item
		 * @name me.gamestat#updateValue
		 * @public
		 * @function
		 * @param {String} name name of the item
		 * @param {int} val value to be added
		 * @example
		 * // update the "stars" item
		 * me.gamestat.updateValue("stars", 1);
		 */
		singleton.updateValue = function(name, value) {
			if (items[name])
				items[name].update(value);
		};
		
		/** 
		 * set value of an item 
		 * @name me.gamestat#setValue 
		 * @public 
		 * @function 
		 * @param {String} name name of the item 
		 * @param {int} val value to be set 
		 * @example 
		 * // set the"stars" item 
		 * me.gamestat.setValue("stars", 1); 
		 */ 
		singleton.setValue = function(name, value) { 
			if (items[name]) 
				items[name].set(value); 
		}; 

		
		/**
		 * return an item value
		 * @name me.gamestat#getItemValue
		 * @public
		 * @function
		 * @param {String} name name of the item
		 * @return {int}
		 * @example
		 * // get the "stars" value
		 * totalStars = me.gamestat.getItemValue("stars");
		 */
		singleton.getItemValue = function(name) {
			return (items[name]) ? items[name].value : 0;
		};

		/**
		 * reset the specified item to default value
		 * @name me.gamestat#reset
		 * @public
		 * @function
		 * @param {String} [name="all"] name of the item
		 * @example
		 */
		singleton.reset = function(name) {
			if (name != undefined) {
				// only reset the specified one
				if (items[name])
					items[name].reset();
			} else {
				// reset everything
				singleton.resetAll();
			}
		};

		/**
		 * reset all items to default value
		 * @name me.gamestat#resetAll
		 * @private
		 * @function
		 */
		singleton.resetAll = function() {
			for ( var i = objCount, objt; i--, objt = obj[i];) {
				objt.reset();
			}
		};

		// return our object
		return singleton;

	})();

	/*---------------------------------------------------------*/
	// END END END
	/*---------------------------------------------------------*/
})(window);
/*
 * MelonJS Game Engine
 * Copyright (C) 2011, Olivier BIOT
 * http://www.melonjs.org
 *
 */

(function($, undefined) {
	// some regexp
	var removepath = /^.*(\\|\/|\:)/;
	var removeext = /\.[^\.]*$/;

	// some custom level constants
	me.LevelConstants = {
		//# name of the collision map
		COLLISION_MAP : "collision",
		PARALLAX_MAP : "parallax",
	};

	/**
	 * a basic tile object
	 * @memberOf me
	 * @private
	 * @constructor
	 */
	me.Tile = me.Rect.extend({
		init : function(x, y, w, h, tileId) {
			this.parent(new me.Vector2d(x * w, y * h), w, h);

			// tileID
			this.tileId = tileId;

			this.row = x;
			this.col = y;
		}
	});

	/************************************************************************************/
	/*                                                                                  */
	/*      a  Tileset object                                                           */
	/*                                                                                  */
	/************************************************************************************/

	function TileSet(name, tilewidth, tileheight, spacing, margin, imagesrc) {
		this.name = name;
		this.tilewidth = tilewidth;
		this.tileheight = tileheight;
		this.spacing = spacing;
		this.margin = margin;
		this.image = (imagesrc) ? me.loader.getImage(imagesrc.replace(
				removepath, '').replace(removeext, '')) : null;

		// tile types
		this.type = {
			SOLID : "solid",
			PLATFORM : "platform",
			L_SLOPE : "lslope",
			R_SLOPE : "rslope",
			LADDER : "ladder",
			BREAKABLE : "breakable"
		};

		// tile properties
		// (collidable, etc..)
		this.TileProperties = [];

		// number of tiles per horizontal line 
		if (this.image) {
			this.hTileCount = ~~((this.image.width - this.margin) / (this.tilewidth + this.spacing));
			this.vTileCount = ~~((this.image.height - this.margin) / (this.tileheight + this.spacing));
		}

	};

	/* -----

		return the list of property for a tile
			
		------								*/

	TileSet.prototype.getPropertyList = function() {
		return {
			// collectable tiles
			//isCollectable	: false,
			// collidable tiles
			isCollidable : false,
			isSolid : false,
			isPlatform : false,
			isSlope : false,
			isLeftSlope : false,
			isRightSlope : false,
			isLadder : false,
			isBreakable : false
		};
	};

	/* -----

		return the assiocated property of the specified tile
		
		e.g. getTileProperty (gid)		
		
		------								*/

	TileSet.prototype.getTileProperties = function(tileId) {
		return this.TileProperties[tileId];
	};

	/* -----

		return collidable status of the specifiled tile
		
		------								*/

	TileSet.prototype.isTileCollidable = function(tileId) {
		return this.TileProperties[tileId].isCollidable;
	};

	/* -----

		return collectable status of the specifiled tile
		
		------								*/
	/*
	TileSet.prototype.isTileCollectable = function (tileId)
	{
		return this.TileProperties[tileId].isCollectable;
	};
	 */

	/* -----

		return an Image Object with the specified tile
			
		------								*/

	TileSet.prototype.getTileImage = function(tileId) {
		// create a new image object
		var image = me.video.createCanvasSurface(this.tilewidth,
				this.tileheight);

		this.drawTile(image, 0, 0, tileId);

		return image.canvas;
	};

	/* -----

		draw the x,y tile
			
		------								*/
	TileSet.prototype.drawTile = function(context, x, y, tileId, flipx, flipy) {
		var texturePositionX = this.margin + (this.spacing + this.tilewidth)
				* (tileId % this.hTileCount);
		var texturePositionY = this.margin + (this.spacing + this.tileheight)
				* ~~(tileId / this.hTileCount);

		if (flipx || flipy) {
			// "normalize" the flag value
			flipx = (flipx == 0) ? 1.0 : -1.0;
			flipy = (flipy == 0) ? 1.0 : -1.0;

			context.scale(flipx, flipy);

			x = (x * flipx) - (flipx < 0 ? this.tilewidth : 0);
			y = (y * flipy) - (flipy < 0 ? this.tileheight : 0);
		}

		context.drawImage(this.image, texturePositionX, texturePositionY,
				this.tilewidth, this.tileheight, x, y, this.tilewidth,
				this.tileheight);

		if (flipx || flipy) {
			// restore the transform matrix to the normal one
			context.setTransform(1, 0, 0, 1, 0, 0);
		}

	};

	/************************************************************************************/
	/*                                                                                  */
	/*      a generic Collision Tile based Layer object                                 */
	/*                                                                                  */
	/************************************************************************************/
	function CollisionTiledLayer(realwidth, realheight) {
		this.realwidth = realwidth;
		this.realheight = realheight;

		this.isCollisionMap = true;

	}
	;

	/* -----

		test for the world limit
			
		------*/

	CollisionTiledLayer.prototype.checkCollision = function(obj, pv) {
		//var x = (pv.x < 0) ? obj.pos.x + obj.colPos.x + pv.x: obj.pos.x + obj.colPos.x + obj.width  + pv.x- 1;
		//var y = (pv.y < 0) ? obj.pos.y + obj.colPos.y + pv.y: obj.pos.y + obj.colPos.y + obj.height + pv.y ;

		var x = (pv.x < 0) ? obj.left + pv.x : obj.right + pv.x;
		var y = (pv.y < 0) ? obj.top + pv.y : obj.bottom + pv.y;

		//to return tile collision detection
		var res = {
			x : 0, // !=0 if collision on x axis
			y : 0, // !=0 if collision on y axis
			xprop : {},
			yprop : {}
		};

		// test x limits
		if (x <= 0 || x >= this.realwidth) {
			res.x = pv.x;
		}

		// test y limits
		if (y <= 0 || y >= this.realheight) {
			res.y = pv.y;
		}

		// return the collide object if collision
		return res;
	};

	/************************************************************************************/
	/*                                                                                  */
	/*      a generic Tile based Layer object                                           */
	/*                                                                                  */
	/************************************************************************************/
	function TiledLayer(w, h, tilesets, z) {
		this.width = w;
		this.height = h;

		// for displaying order
		this.z = z;

		this.name = null;
		this.visible = false;

		// data array
		this.layerData = null;

		// some lookup table to avoid unecessary math operation
		this.xLUT = {};
		this.yLUT = {};

		// a reference to the tilesets object
		this.tilesets = tilesets;
		// link to the first tileset by default
		this.tileset = tilesets?this.tilesets.getTilesetByIndex(0):null;

		// tile width & height
		this.tilewidth  = this.tileset?this.tileset.tilewidth:0;
		this.tileheight = this.tileset?this.tileset.tileheight:0;
  
		// layer "real" size
		this.realwidth = this.width * this.tilewidth;
		this.realheight = this.height * this.tileheight;
	};

	/* -----

		Create all required arrays
			
		------								*/
	TiledLayer.prototype.initArray = function(createLookup) {
		// initialize the array
		this.layerData = [];//new Array (this.width);
		for ( var x = 0; x < this.width + 1; x++) {
			this.layerData[x] = [];//new Array (this.height);
			for ( var y = 0; y < this.height + 1; y++) {
				this.layerData[x][y] = null;
			}
		}

		// create lookup table to speed up the table access
		// this is only valid for collision layer
		if (createLookup) {
			// initialize the lookuptable
			for ( var x = 0; x < this.width * this.tilewidth; x++)
				this.xLUT[x] = ~~(x / this.tilewidth);

			for ( var y = 0; y < this.height * this.tileheight; y++)
				this.yLUT[y] = ~~(y / this.tileheight);

			//console.log(this.xLUT);
		}

	};

	/* -----

		get the x,y tile
			
		------								*/
	TiledLayer.prototype.getTileId = function(x, y) {
		//return this.layerData[~~(x / this.tilewidth)][~~(y / this.tileheight)];
		var tile = this.layerData[this.xLUT[~~x]][this.yLUT[~~y]];

		return tile ? tile.tileId : null;
	};

	/* -----

		get the x,y tile
			
		------								*/
	TiledLayer.prototype.getTile = function(x, y) {
		//return this.layerData[~~(x / this.tilewidth)][~~(y / this.tileheight)];
		return this.layerData[this.xLUT[~~x]][this.yLUT[~~y]];
	};

	/* -----

		set the x,y tile
			
		------								*/
	TiledLayer.prototype.setTile = function(x, y, tileId) {
		this.layerData[x][y] = new me.Tile(x, y, this.tilewidth, this.tileheight,
				tileId);
	};

	/* -----

		clear a tile
			
		------								*/
	TiledLayer.prototype.clearTile = function(x, y) {
		// clearing tile
		this.layerData[x][y] = null;
	};

	/* -----

		check for collision 
		obj - obj
		pv   - projection vector
		
		res : result collision object
			
		------*/

	TiledLayer.prototype.checkCollision = function(obj, pv) {

		var x = (pv.x < 0) ? obj.left + pv.x : obj.right + pv.x;
		var y = (pv.y < 0) ? obj.top + pv.y : obj.bottom + pv.y;
		//to return tile collision detection
		var res = {
			x : 0, // !=0 if collision on x axis
			xtile : undefined,
			xprop : {},
			y : 0, // !=0 if collision on y axis
			ytile : undefined,
			yprop : {}
		};

		//var tile;
		if (x <= 0 || x >= this.realwidth) {
			res.x = pv.x;
		} else {
			// x, bottom corner
			res.xtile = this.getTile(x, obj.bottom - 1);// obj.height - 1
			if (res.xtile && this.tileset.isTileCollidable(res.xtile.tileId)) {
				res.x = pv.x; // reuse pv.x to get a 
				res.xprop = this.tileset.getTileProperties(res.xtile.tileId);
			} else {
				// x, top corner
				res.xtile = this.getTile(x, obj.top);
				if (res.xtile && this.tileset.isTileCollidable(res.xtile.tileId)) {
					res.x = pv.x;
					res.xprop = this.tileset.getTileProperties(res.xtile.tileId);
				}
			}
		}

		// check for y movement
		// left, y corner
		res.ytile = this.getTile((pv.x < 0) ? obj.left : obj.right, y);// obj.width + 1
		if (res.ytile && this.tileset.isTileCollidable(res.ytile.tileId)) {
			res.y = pv.y || 1;
			res.yprop = this.tileset.getTileProperties(res.ytile.tileId);
		} else { // right, y corner
			res.ytile = this.getTile((pv.x < 0) ? obj.right : obj.left, y);
			if (res.ytile && this.tileset.isTileCollidable(res.ytile.tileId)) {
				res.y = pv.y || 1;
				res.yprop = this.tileset.getTileProperties(res.ytile.tileId);
			}
		}
		// return the collide object
		return res;
	};

	/* -----

		a dummy update function
			
		------								*/
	TiledLayer.prototype.update = function() {
		return false;
	};

	/************************************************************************************/
	/*       a basic level object skeleton                                              */
	/************************************************************************************/
	function TileMap(x, y) {
		this.pos = new me.Vector2d(x, y);
		this.z = 0;

		// tilemap size
		this.width = 0;
		this.height = 0;

		// realwidth (in pixels) of the level
		this.realwidth = -1;
		this.realheight = -1;

		// tile size
		this.tilewidth = 0;
		this.tileheight = 0;

		// corresponding tileset for this map
		this.tilesets = null;

		// map layers
		this.mapLayers = [];

		// map Object
		this.objectGroups = [];

		// loading flag
		this.initialized = false;

	};

	/* -----

		a dummy update function
			
		------								*/
	TileMap.prototype.reset = function() {
		this.tilesets = null;
		this.mapLayers = [];
		this.objectGroups = [];
		this.initialized = false;
	};

	/* -----

		return the specified object group
			
		------*/

	TileMap.prototype.getObjectGroupByName = function(name) {
		return this.objectGroups[name];
	};

	/* -----

		return all the object group
			
		------*/

	TileMap.prototype.getObjectGroups = function() {
		return this.objectGroups;
	};

	/* -----

		return the specified layer object
			
		------*/

	TileMap.prototype.getLayerByName = function(name) {
		var layer = null;

		// normalize name
		name = name.trim().toLowerCase();
		for ( var i = this.mapLayers.length; i--;) {
			if (this.mapLayers[i].name.contains(name)) {
				layer = this.mapLayers[i];
				break;
			}
		}
		;

		// return a fake collision layer if not found
		if ((name.contains(me.LevelConstants.COLLISION_MAP)) && (layer == null)) {
			layer = new CollisionTiledLayer(me.game.currentLevel.realwidth,
					me.game.currentLevel.realheight);
		}

		return layer;
	};

	/*  -----
		
		 clear a tile from all layers
		
		------				*/

	TileMap.prototype.clearTile = function(x, y) {
		// add all layers
		for ( var i = this.mapLayers.length; i--;) {
			// that are visible
			if (this.mapLayers[i].visible || this.mapLayers[i].isCollisionMap) {
				this.mapLayers[i].clearTile(x, y);
			}
		}
		;
	};

	/*  -----
		
		 add all visible layers to the game mngr
		
		------				*/

	TileMap.prototype.addTo = function(gameMngr) {
		// add ourself (for background color)
		if (this.visible) {
			gameMngr.add(this);
		}

		// add all layers
		for ( var i = this.mapLayers.length; i--;) {
			// that are visible
			if (this.mapLayers[i].visible) {
				gameMngr.add(this.mapLayers[i]);
			}
		}
		;
	};

	/* -----

		a dummy update function
			
		------								*/
	TileMap.prototype.update = function() {
		return false;
	};

	// TMX extends sprite object to benefit from some
	// nice mechanism (sprite Object to be redone)
	//LevelEntity.prototype = new me.SpriteObject();

	/************************************************************************************/
	/*                                                                                  */
	/*      a level Director                                                            */
	/*                                                                                  */
	/************************************************************************************/
	/**
	 * a level manager object <br>
	 * once ressources loaded, the level director contains all references of defined levels<br>
	 * There is no constructor function for me.levelDirector, this is a static object
	 * @final
	 * @memberOf me
	 * @constructor Should not be called by the user.
	 */
	me.levelDirector = (function() {
		// hold public stuff in our singletong
		var obj = {};

		/*---------------------------------------------
			
			PRIVATE STUFF
				
			---------------------------------------------*/

		// our levels
		var levels = {};
		// current level
		var currentLevel = null;

		/*---------------------------------------------
			
			PUBLIC STUFF
				
			---------------------------------------------*/

		/**
		 * reset the level director 
		 * @private
		 */
		obj.reset = function() {

		};

		/**
		 * add a level  
		 * @private
		 */
		obj.addLevel = function(level) {
			throw "melonJS: no level loader defined";
		};

		/**
		 *
		 * add a TMX level  
		 * @private
		 */
		obj.addTMXLevel = function(levelId, callback) {
			// just load the level with the XML stuff
			if (levels[levelId] == null) {
				//console.log("loading "+ levelId);
				levels[levelId] = new me.TMXTileMap(levelId, 0, 0);
			}
			//else console.log("level %s already loaded", levelId);

			// call the callback if defined
			if (callback)
				callback();
		};

		/**
		 * load a level into the game manager<br>
		 * (will also create all level defined entities, etc..)
		 * @name me.levelDirector#loadLevel
		 * @public
		 * @function
		 * @param {String} level level id
		 * @example
		 * // the game defined ressources
		 * // to be preloaded by the loader
		 * // TMX maps
		 * ...
		 * {name: "a4_level1",   type: "tmx",   src: "data/level/a4_level1.tmx"},
		 * {name: "a4_level2",   type: "tmx",   src: "data/level/a4_level2.tmx"},
		 * {name: "a4_level3",   type: "tmx",   src: "data/level/a4_level3.tmx"},
		 * ...
		 * ...
		 * // load a level
		 * me.levelDirector.loadLevel("a4_level1");
		 */
		obj.loadLevel = function(level) {
			if (levels[level] === undefined) {
				throw ("melonJS: level " + level + " not found");
			}

			if (levels[level] instanceof me.TMXTileMap) {

				// check the status of the state mngr
				var isRunning = me.state.isRunning();

				if (isRunning) {
					// pause the game loop to avoid 
					// some silly side effects
					me.state.pause();
				}

				// reset the gameObject Manager (just in case!)
				me.game.reset();
				
				// reset the GUID generator
				// and pass the level id as parameter
				me.utils.resetGUID(level);
				
				// load the level
				levels[level].reset();
				levels[level].load();
				// set the current level
				currentLevel = level;
				// add the specified level to the game manager
				me.game.loadTMXLevel(levels[currentLevel]);

				if (isRunning) {
					// resume the game loop if it was
					// previously running
					me.state.resume();
				}
			} else
				throw "melonJS: no level loader defined";
		};

		/**
		 * return the current level id<br>
		 * @name me.levelDirector#getCurrentLevelId
		 * @public
		 * @function
		 * @return {String}
		 */
		obj.getCurrentLevelId = function() {
			return currentLevel;
		},

		/**
		 * reload the current level<br>
		 * @name me.levelDirector#getCurrentLevelId
		 * @public
		 * @function
		 */
		obj.reloadLevel = function() {
			// reset the level to initial state
			//levels[currentLevel].reset();
			return obj.loadLevel(currentLevel);
		},

		/**
		 * load the next level<br>
		 * @name me.levelDirector#nextLevel
		 * @public
		 * @function
		 */
		obj.nextLevel = function() {
			//go to the next level 
			if (currentLevel + 1 < levels.length) {
				return obj.loadLevel(currentLevel + 1);
			} else {
				return false;
			}
		};

		/**
		 * load the previous level<br>
		 * @name me.levelDirector#previousLevel
		 * @public
		 * @function
		 */
		obj.previousLevel = function() {
			// go to previous level
			if (currentLevel - 1 >= 0) {
				return obj.loadLevel(currentLevel - 1);
			} else {
				return false;
			}
		};

		/* -----

			set the specified level  
		
			------ 
		
		obj.goToLevel = function(level)
		{
			obj.loadLevel(level);
		};
		 */

		// return our object
		return obj;

	})();

	/*---------------------------------------------------------*/
	// expose our stuff to the global scope
	/*---------------------------------------------------------*/
	me.TileSet = TileSet;
	me.TiledLayer = TiledLayer;
	me.TileMap = TileMap

	/*---------------------------------------------------------*/
	// END END END
	/*---------------------------------------------------------*/
})(window);
/*
 * MelonJS Game Engine
 * Copyright (C) 2011, Olivier BIOT
 * http://www.melonjs.org
 *
 *
 * TMX Loader
 * Tile QT 0.7.x format
 *	http://www.mapeditor.org/	
 *
 */

(function($, undefined) {
		
	// some TMX constants
	var
	TMX_TAG_MAP                 = "map",
	TMX_TAG_NAME                = "name",
	TMX_TAG_VALUE               = "value",	
	TMX_TAG_VERSION             = "version",
	TMX_TAG_ORIENTATION	        = "orientation",
	TMX_TAG_WIDTH               = "width",
	TMX_TAG_HEIGHT              = "height",
	TMX_TAG_OPACITY             = "opacity",
	TMX_TAG_TRANS               = "trans",
	TMX_TAG_TILEWIDTH           = "tilewidth",
	TMX_TAG_TILEHEIGHT          = "tileheight",
	TMX_TAG_FIRSTGID            = "firstgid",
	TMX_TAG_GID                 = "gid",
	TMX_TAG_TILE                = "tile",
	TMX_TAG_ID                  = "id",
	TMX_TAG_DATA                = "data",
	TMX_TAG_COMPRESSION         = "compression",
	TMX_TAG_ENCODING            = "encoding",
	TMX_TAG_ATTR_BASE64         = "base64",
	TMX_TAG_CSV                 = "csv",
	TMX_TAG_SPACING             = "spacing",
	TMX_TAG_MARGIN              = "margin",
	TMX_TAG_PROPERTIES          = "properties",
	TMX_TAG_PROPERTY            = "property",
	TMX_TAG_IMAGE               = "image",
	TMX_TAG_SOURCE              = "source",
	TMX_TAG_VISIBLE             = "visible",
	TMX_TAG_TILESET             = "tileset",
	TMX_TAG_LAYER               = "layer",
	TMX_TAG_OBJECTGROUP         = "objectgroup",
	TMX_TAG_OBJECT              = "object",
	TMX_TAG_X                   = "x",
	TMX_TAG_Y                   = "y",
	TMX_TAG_WIDTH               = "width",
	TMX_TAG_HEIGHT              = "height",

	// some other global value 

	// bitmaks to check for flipped tiles
	FlipH_Flag                  = 0x80000000,
	FlipV_Flag                  = 0x40000000;

	
	/* -----

		check if properties are defined for the given objet
			
		------									*/

	function setTMXProperties(obj, xmldata) {
		var layer_properties = xmldata.getElementsByTagName(TMX_TAG_PROPERTIES)[0];

		if (layer_properties) {
			var oProp = layer_properties.getElementsByTagName(TMX_TAG_PROPERTY);

			for ( var i = 0; i < oProp.length; i++) {
				applyTMXProperty(obj, oProp[i]);
			}
		}

	}
	;

	/* -----

		apply the specified TMX properties (name, value) to the object
			
		------									*/

	function applyTMXProperty(object, prop) {
		var propname = me.XMLParser.getStringAttribute(prop, TMX_TAG_NAME);
		var value = me.XMLParser.getStringAttribute(prop, TMX_TAG_VALUE);

		// if value not defined or boolean
		if (!value || value.isBoolean()) {
			value = value ? (value == "true") : true;
		}
		// check if numeric
		else if (value.isNumeric()) {
			value = parseInt(value);
		}
		// add the new prop to the object prop list
		object[propname] = value;
	};

	/***************************************************************/
	/*                                                             */
	/*    Manage a tile map                                        */
	/*    Tile QT 0.7.0 format                                     */
	/*    http://www.mapeditor.org/                                */
	/*                                                             */
	/***************************************************************/
	function TMXTileMap(xmlfile, x, y) {
		// call the constructor
		me.TileMap.call(this, x, y);

		this.xmlMap = me.loader.getXML(xmlfile);

		if (!this.xmlMap) {
			throw "melonJS:" + xmlfile + " TMX map not found";
		}

		// tilemap version
		this.version = "";

		// map type (only orthogonal format supported)
		this.orientation = "";

		// a canvas where to draw our map(s)
		this.tileMapCanvas = null;
      
      // tileset(s)
      this.tilesets = null;

	};
	TMXTileMap.prototype = new me.TileMap();

	/* -----

		Load & initialize the Tile Map
			
		------									*/
	TMXTileMap.prototype.load = function() {
		// if already loaded, do nothing
		if (this.initialized)
			return;

		// to automatically increment z index
		var zOrder = 0,
		// and parallax layer speed
		pLayer = 1;

		// init the parser
		me.XMLParser.parseFromString(this.xmlMap);

		// retreive all the elements of the XML file
		var xmlElements = me.XMLParser.getAllTagElements();

		// parse all tags
		for ( var i = 0; i < xmlElements.length; i++) {
			// check each Tag
			var tagName = xmlElements.item(i).nodeName;

			switch (tagName) {
            // get the map information
            case TMX_TAG_MAP: {
               var map = xmlElements.item(i);
               this.version = me.XMLParser.getStringAttribute(map, TMX_TAG_VERSION);
               this.orientation = me.XMLParser.getStringAttribute(map, TMX_TAG_ORIENTATION);
               this.width = me.XMLParser.getIntAttribute(map, TMX_TAG_WIDTH);
               this.height = me.XMLParser.getIntAttribute(map, TMX_TAG_HEIGHT);
               this.tilewidth = me.XMLParser.getIntAttribute(map,	TMX_TAG_TILEWIDTH);
               this.tileheight = me.XMLParser.getIntAttribute(map, TMX_TAG_TILEHEIGHT);
               this.realwidth = this.width * this.tilewidth;
               this.realheight = this.height * this.tileheight;
               this.z = zOrder++;

               // check some returned values
			   /*
			   if (this.orientation != "orthogonal") {
                  throw "melonJS: " + this.orientation + " type TMX Tile Map not supported!";
               }
			   */

			   // set the map properties (if any)
               setTMXProperties(this, map);

               // ensure the visible flag is set to false, by default
               this.visible = false;

               // check if a backgroud color is defined  
               if (this.background_color) {
                  this.visible = true;
                  // convert to a rgb string (needed for Opera)
                  this.background_color = me.utils
                        .HexToRGB(this.background_color);
               }

               // check if a backgroud image is defined
               if (this.background_image) {
                  this.visible = true;
                  // retrieve the corresponding image ressource
                  this.background_image = me.loader.getImage(this.background_image);
               }
               break;
            }
               

            // get the tileset information
            case TMX_TAG_TILESET: {
            
               // Initialize our object if not yet done
               if (!this.tilesets)
               {
                  // make sure tilesets if of the right type
                  this.tilesets = new TMXTileSetGroup();
               }

               // add the new tileset
               this.tilesets.add(new TMXTileSet(xmlElements.item(i)));
               break;
            }
               

            // get the layer(s) information
            case TMX_TAG_LAYER: {
               // try to identify specific layer type based on the naming convention
               var layer_name = me.XMLParser.getStringAttribute(xmlElements
                     .item(i), TMX_TAG_NAME);

               // parallax layer
               if (layer_name.contains(me.LevelConstants.PARALLAX_MAP)) {
                  var visible = (me.XMLParser.getIntAttribute(xmlElements
                        .item(i), TMX_TAG_VISIBLE, 1) == 1);

                  // only add if visible
                  if (visible) {
                     // check the object properties 
                     var tprop = {};
                     setTMXProperties(tprop, xmlElements.item(i));

                     // check if we already have a parallax layer
                     var parallax_layer = this.getLayerByName(me.LevelConstants.PARALLAX_MAP);

                     if (!parallax_layer) {
                        parallax_layer = new me.ParallaxBackgroundEntity(zOrder);
                        this.mapLayers.push(parallax_layer);
                     }
                     // add the new parallax layer
                     parallax_layer.addLayer(tprop.imagesrc, pLayer++, zOrder++);
                  }
               }
               else {
                  // regular layer or collision layer
                  this.mapLayers.push(new TMXLayer(xmlElements.item(i), this.orientation, this.tilesets, zOrder++));
                  zOrder++;
               }
               break;
            }
               

            // get the object groups information
            case TMX_TAG_OBJECTGROUP: {
               var name = me.XMLParser.getStringAttribute(xmlElements.item(i), TMX_TAG_NAME);
               this.objectGroups.push(new TMXOBjectGroup(name, xmlElements.item(i), this.tilesets, zOrder++));
               break;
            }
				
			} // end switch 
		} // end for

		// free the XMLParser ressource
		me.XMLParser.free();

		// flag as loaded
		this.initialized = true;

	};

	/* -----

		draw the tile map
		this is only called if the background_color property is defined
			
		------								*/
	TMXTileMap.prototype.draw = function(context, rect) {
		if (this.background_color) {
			// set the background color
			context.fillStyle = this.background_color;
			// clear the specified rect
			context.fillRect(rect.left, rect.top, rect.width, rect.height);
		}
		if (this.background_image) {
			context.drawImage(this.background_image, rect.left, rect.top,
					rect.width, rect.height, rect.left, rect.top, rect.width,
					rect.height);

		}
	};

	/**************************************************/
	/*                                                */
	/*      Tileset Management                        */
	/*                                                */
	/**************************************************/
	
	/* -------------------------
	 * Manage a group of Tileset
	 * -------------------------*/
	function TMXTileSetGroup() {
		this.tilesets = [];
	};
	/*
	 * add a tileset to the tileset group
	 */
	TMXTileSetGroup.prototype.add = function(tileset) {
		this.tilesets.push(tileset);
	};

	/*
	 * return the tileset at the specified index
	 */
	TMXTileSetGroup.prototype.getTilesetByIndex = function(i) {
		return this.tilesets[i];
	};
   
	/*
	 * return the tileset corresponding to  the specified gid
	 *		
	 */
	TMXTileSetGroup.prototype.getTilesetByGid = function(gid) {
      	var invalidRange = -1;
		// cycle through all tilesets
		for ( var i = 0, len = this.tilesets.length; i < len; i++) {
			// return the corresponding tileset if matching
			if (this.tilesets[i].contains(gid))
				return this.tilesets[i];
			// typically indicates a layer with no asset loaded (collision?)
			if (this.tilesets[i].firstgid == this.tilesets[i].lastgid) {
				if (gid >= this.tilesets[i].firstgid)
				// store the id if the [firstgid .. lastgid] is invalid
				invalidRange = i;
			}
		}
		// return the tileset with the invalid range
		if (invalidRange!=-1)
			return this.tilesets[invalidRange];
		else
		throw "no matching tileset found for gid " + gid;
	};
   
	/* -------------------------
	 * Tileset Object
	 * -------------------------*/
	function TMXTileSet(xmltileset) {

		// first gid
		this.firstgid = me.XMLParser.getIntAttribute(xmltileset, TMX_TAG_FIRSTGID);

		// call our super parent
		me.TileSet.call(this,
                        me.XMLParser.getStringAttribute(xmltileset, TMX_TAG_NAME),
                        me.XMLParser.getIntAttribute(xmltileset, TMX_TAG_TILEWIDTH),
                        me.XMLParser.getIntAttribute(xmltileset, TMX_TAG_TILEHEIGHT),
                        me.XMLParser.getIntAttribute(xmltileset, TMX_TAG_SPACING, 0), 
                        me.XMLParser.getIntAttribute(xmltileset, TMX_TAG_MARGIN, 0), 
                        xmltileset.getElementsByTagName(TMX_TAG_IMAGE)[0].getAttribute(TMX_TAG_SOURCE));
		
		// compute the last gid value in the tileset
		this.lastgid = this.firstgid + ( ((this.hTileCount * this.vTileCount) - 1) || 0);
      
		// check if transparency is defined for a specific color
		this.trans = xmltileset.getElementsByTagName(TMX_TAG_IMAGE)[0].getAttribute(TMX_TAG_TRANS);

		// set Color Key for transparency if needed
		if (this.trans !== null && this.image) {
			// applyRGB Filter (return a context object)
			this.image = me.video.applyRGBFilter(this.image, "transparent", this.trans.toUpperCase()).canvas;
		}

		// set tile properties, if any
		var tileInfo = xmltileset.getElementsByTagName(TMX_TAG_TILE);
		for ( var i = 0; i < tileInfo.length; i++) {
			var tileID = me.XMLParser.getIntAttribute(tileInfo[i], TMX_TAG_ID) + this.firstgid;

			this.TileProperties[tileID] = {};

			var tileProp = this.TileProperties[tileID];

			// apply tiled defined properties
			setTMXProperties(tileProp, tileInfo[i]);

			// check what we found and adjust property
			tileProp.isSolid = tileProp.type ? tileProp.type.toLowerCase() === this.type.SOLID : false;
			tileProp.isPlatform = tileProp.type ? tileProp.type.toLowerCase() === this.type.PLATFORM : false;
			tileProp.isLeftSlope = tileProp.type ? tileProp.type.toLowerCase() === this.type.L_SLOPE : false;
			tileProp.isRightSlope = tileProp.type ? tileProp.type.toLowerCase() === this.type.R_SLOPE	: false;
			tileProp.isBreakable = tileProp.type ? tileProp.type.toLowerCase() === this.type.BREAKABLE : false;
			tileProp.isLadder = tileProp.type ? tileProp.type.toLowerCase() === this.type.LADDER : false;
			tileProp.isSlope = tileProp.isLeftSlope || tileProp.isRightSlope;

			// ensure the collidable flag is correct
			tileProp.isCollidable = tileProp.isSolid || tileProp.isPlatform
					|| tileProp.isSlope || tileProp.isLadder
					|| tileProp.isBreakable;

		}

	};
	TMXTileSet.prototype = new me.TileSet();

	/*
	 * check if the gid belongs to the tileset
	 */
	TMXTileSet.prototype.contains = function(gid) {
		return (gid >= this.firstgid && gid <= this.lastgid)
	}
	
	/************************************************************************************/
	/*                                                                                  */
	/*      Tile map Stuff                                                              */
	/*      Manage a tile Layer                                                         */
	/*                                                                                  */
	/************************************************************************************/
	function TMXLayer(layer, orientation, tilesets, zOrder) {
		// call the parent
		me.TiledLayer.call(this, 
                         me.XMLParser.getIntAttribute(layer, TMX_TAG_WIDTH), 
                         me.XMLParser.getIntAttribute(layer, TMX_TAG_HEIGHT),
                         // tilesets should exist here !
                         tilesets, zOrder);
      
 		// get invalidated when the viewport is changed
		this.orientation = orientation;
		this.layerInvalidated = true;
		this.name = me.XMLParser.getStringAttribute(layer, TMX_TAG_NAME);
		this.visible = (me.XMLParser.getIntAttribute(layer, TMX_TAG_VISIBLE, 1) == 1);
		this.opacity = me.XMLParser.getFloatAttribute(layer, TMX_TAG_OPACITY, 1.0);
            
		// check if we have any properties 
		setTMXProperties(this, layer);

		// detect if the layer is a collision map
		this.isCollisionMap = (this.name.contains(me.LevelConstants.COLLISION_MAP));
		if (this.isCollisionMap) {
			// force the layer as invisible
			this.visible = false;
		}

		// link to the gameviewport;
		this.vp = me.game.viewport;

		// store the data information
		var xmldata = layer.getElementsByTagName(TMX_TAG_DATA)[0];
		var encoding = me.XMLParser.getStringAttribute(xmldata, TMX_TAG_ENCODING, null);
		var compression = me.XMLParser.getStringAttribute(xmldata, TMX_TAG_COMPRESSION, null);

		// make sure this is not happening
		if (encoding == '')
			encoding = null;
		if (compression == '')
			compression = null;

		// create a canvas where to draw our layer
		if (this.visible) {
			this.layerSurface = me.video.createCanvasSurface(this.width
					* this.tilewidth, this.height * this.tileheight);
			this.layerCanvas = this.layerSurface.canvas;

			// set alpha value for this layer
			if (this.opacity > 0.0 && this.opacity < 1.0) {
				this.layerSurface.globalAlpha = this.opacity;
			}
		}

		if (this.visible || this.isCollisionMap) {
			// initialize the layer lookup table (only in case of collision map)
			this.initArray(this.isCollisionMap);

			// populate our level with some data
			this.fillArray(xmldata, encoding, compression);
		}
	};
	TMXLayer.prototype = new me.TiledLayer();

	/* -----

		Build the tiled layer
			
		------								*/
	TMXLayer.prototype.fillArray = function(xmldata, encoding, compression) {
		// check if data is compressed
		switch (compression) {
         
         // no compression
         case null: {
            // decode data based on encoding type
            switch (encoding) {
            // XML encoding
               case null: {
                  var data = xmldata.getElementsByTagName(TMX_TAG_TILE);
                  break;
               }
               
               // CSV encoding
               case TMX_TAG_CSV:
                  // Base 64 encoding
               case TMX_TAG_ATTR_BASE64: {
                  // Merge all childNodes[].nodeValue into a single one
                  var nodeValue = '';
                  for ( var i = 0, len = xmldata.childNodes.length; i < len; i++) {
                     nodeValue += xmldata.childNodes[i].nodeValue;
                  }
                  // and then decode them
                  if (encoding == TMX_TAG_ATTR_BASE64)
                     var data = me.utils.decodeBase64AsArray(nodeValue, 4);
                  else
                     var data = me.utils.decodeCSV(nodeValue, this.width);

                  // ensure nodeValue is deallocated
                  nodeValue = null;
                  break;
               }
                  
               default:
                  throw "melonJS: TMX Tile Map " + encoding + " encoding not supported!";
                  break;
            }
            
         break;
         }
            
         default:
            throw "melonJS: " + compression+ " compressed TMX Tile Map not supported!";
            break;
		}

		// I love reversed loop !
		var idx = data.length - 1;

		var flipx, flipy;
		
		var gid;

		// set everything
		for ( var y = this.height - 1; y >= 0; y--) {
			for ( var x = this.width - 1; x >= 0; x--) {
				// get the value of the gid
				gid = (encoding == null) ? me.XMLParser.getIntAttribute(data[idx--], TMX_TAG_GID) : data[idx--];

				// check if tile is horizontally flipped
				// (this should be save somewhere!)
				flipx = (gid & FlipH_Flag);

				// check if tile is vertically flipped
				// (this should be save somewhere!)
				flipy = (gid & FlipV_Flag);

				// clear out the flags
				gid &= ~(FlipH_Flag | FlipV_Flag);

				// fill the array										
				if (gid > 0) {
					this.setTile(x, y, gid);
					// check if we are using the right tileset
					if (!this.tileset.contains(gid)) {
						// switch to the right tileset
						this.tileset = this.tilesets.getTilesetByGid(gid);
					}
				   
					if (this.visible) {
						//draw our tile
						if (this.orientation == "orthogonal") { 
							this.tileset.drawTile(this.layerSurface, 
													x * this.tilewidth, 
													y * this.tileheight,
													gid - this.tileset.firstgid, 
													flipx, flipy);
						}
						else { // isometric
							this.tileset.drawTile(this.layerSurface, 
													(this.width-1) * this.tilewidth + (x - y) * this.tilewidth>>1, 
													-this.tileheight + (y + x) * this.tileheight>>2,
													gid - this.tileset.firstgid, 
													flipx, flipy);
						}
					}
				}
			}
		}

		// make sure data is deallocated :)
		data = null;

	};

	/* -----

		clear a tile
			
		------								*/
	TMXLayer.prototype.clearTile = function(x, y) {
		// call the parent function
		me.TiledLayer.prototype.clearTile.call(this, x, y);
		// erase the corresponding area in the canvas
		if (this.visible) {
			this.layerSurface.clearRect(x * this.tilewidth,
					y * this.tileheight, this.tilewidth, this.tileheight);
		}
	};

	/* -----

		draw a tileset layer
			
		------								*/
	TMXLayer.prototype.draw = function(context, rect) {
		context.drawImage(this.layerCanvas, 
                        this.vp.pos.x + rect.pos.x, //sx
                        this.vp.pos.y + rect.pos.y, //sy
                        rect.width, rect.height,    //sw, sh
                        rect.pos.x, rect.pos.y,     //dx, dy
                        rect.width, rect.height);   //dw, dh
	};

	/************************************************************************************/
	/*                                                                                  */
	/*      Tile map Stuff                                                              */
	/*      Manage a Object Group                                                       */
	/*                                                                                  */
	/************************************************************************************/
	function TMXOBjectGroup(name, tmxObjGroup, tilesets, z) {
		this.objects = [];

		this.name   = name;
		this.width  = me.XMLParser.getIntAttribute(tmxObjGroup, TMX_TAG_WIDTH);
		this.height = me.XMLParser.getIntAttribute(tmxObjGroup, TMX_TAG_HEIGHT);
		this.z      = z;

		var data = tmxObjGroup.getElementsByTagName(TMX_TAG_OBJECT);

		for ( var i = 0; i < data.length; i++) {
			this.objects.push(new TMXOBject(data[i], tilesets, z));
		}

	};

	TMXOBjectGroup.prototype.getObjectCount = function() {
		return this.objects.length;
	};

	TMXOBjectGroup.prototype.getObjectByIndex = function(idx) {
		return this.objects[idx];
	};

	/************************************************************************************/
	/*                                                                                  */
	/*      Tile map Stuff                                                              */
	/*      Manage a TMX Object                                                         */
	/*                                                                                  */
	/************************************************************************************/
	function TMXOBject(tmxObj, tilesets, z) {
		this.name = me.XMLParser.getStringAttribute(tmxObj, TMX_TAG_NAME);
		this.x = me.XMLParser.getIntAttribute(tmxObj, TMX_TAG_X);
		this.y = me.XMLParser.getIntAttribute(tmxObj, TMX_TAG_Y);
		this.z = z;

		this.gid = me.XMLParser.getIntAttribute(tmxObj, TMX_TAG_GID, null);
		// check if the object has an associated gid	
		if (this.gid) {
			
			// get the corresponding tileset
			var tileset = tilesets.getTilesetByGid(this.gid);
         
			// set width and height equal to tile size
			this.width = tileset.tilewidth;
			this.height = tileset.tileheight;

			// force spritewidth size
			this.spritewidth = this.width;
			// adjust y coordinates (bug in tile 0.6.2?)
			this.y -= this.height;

			// get the corresponding tile into our object
			this.image = tileset.getTileImage(this.gid - tileset.firstgid);
		} 
		else {
			this.width = me.XMLParser.getIntAttribute(tmxObj, TMX_TAG_WIDTH, 0);
			this.height = me.XMLParser.getIntAttribute(tmxObj, TMX_TAG_HEIGHT, 0);
		}
		// set the object properties
		setTMXProperties(this, tmxObj);

	};

	/* -----

		return the specified object group
			
		------									*/
	TMXOBject.prototype.getObjectPropertyByName = function(name) {
		return this[name];
	};

	/*------------------------------------------------------*/
	// expose our stuff to the me scope
	/*------------------------------------------------------*/
	me.TMXTileMap = TMXTileMap;
	/*---------------------------------------------------------*/
	// END END END
	/*---------------------------------------------------------*/
})(window);
/*!
 * Tween JS
 * https://github.com/sole/Tween.js
 *
 * author sole / http://soledadpenades.com
 * author mr.doob / http://mrdoob.com
 * author Robert Eisele / http://www.xarg.org
 * author Philippe / http://philippe.elsass.me
 * author Robert Penner / http://www.robertpenner.com/easing_terms_of_use.html
 */

(function($, undefined) {
	/**
	 * Javascript Tweening Engine<p>
	 * Super simple, fast and easy to use tweening engine which incorporates optimised Robert Penner's equation<p>
	 * <a href="https://github.com/sole/Tween.js">https://github.com/sole/Tween.js</a><p>
	 * @author <a href="http://soledadpenades.com">sole</a>
	 * @author <a href="http://mrdoob.com">mr.doob</a>
	 * @author <a href="http://www.xarg.org">Robert Eisele</a>
	 * @author <a href="http://philippe.elsass.me">Philippe</a>
	 * @author <a href="http://www.robertpenner.com/easing_terms_of_use.html">Robert Penner</a>
	 * @class
	 * @memberOf me
	 * @constructor
	 * @param {Object} object object on which to apply the tween
	 * @example
	 * // add a tween to change the object pos.y variable to 200 in 3 seconds
	 * tween = new me.Tween(myObject.pos).to({y: 200}, 3000).onComplete(myFunc);
	 * tween.easing(me.Tween.Easing.Bounce.EaseOut);
	 * tween.start();
	 */
	me.Tween = function(object) {

		var _object = object, _valuesStart = {}, _valuesDelta = {}, _valuesEnd = {}, _duration = 1000, _delayTime = 0, _startTime = null, _easingFunction = me.Tween.Easing.Linear.EaseNone, _chainedTween = null, _onUpdateCallback = null, _onCompleteCallback = null;

		/**
		 * object properties to be updated and duration
		 * @name me.Tween#to
		 * @public
		 * @function
		 * @param {Properties} prop list of properties
		 * @param {int} duration tween duration
		 */
		this.to = function(properties, duration) {

			if (duration !== null) {

				_duration = duration;

			}

			for ( var property in properties) {

				// This prevents the engine from interpolating null values
				if (_object[property] === null) {

					continue;

				}

				// The current values are read when the Tween starts;
				// here we only store the final desired values
				_valuesEnd[property] = properties[property];

			}

			return this;

		};

		/**
		 * start the tween
		 * @name me.Tween#start
		 * @public
		 * @function
		 */
		this.start = function() {

			// add the tween to the object pool on start
			me.game.add(this, 999);

			_startTime = me.timer.getTime() + _delayTime;

			for ( var property in _valuesEnd) {

				// Again, prevent dealing with null values
				if (_object[property] === null) {

					continue;

				}

				_valuesStart[property] = _object[property];
				_valuesDelta[property] = _valuesEnd[property]
						- _object[property];

			}

			return this;
		};

		/**
		 * stop the tween
		 * @name me.Tween#stop
		 * @public
		 * @function
		 */
		this.stop = function() {

			me.game.remove(this);
			return this;

		};

		/**
		 * delay the tween
		 * @name me.Tween#delay
		 * @public
		 * @function
		 * @param {int} amount delay amount
		 */
		this.delay = function(amount) {

			_delayTime = amount;
			return this;

		};

		/**
		 * set the easing function
		 * @name me.Tween#easing
		 * @public
		 * @function
		 * @param {Function} easing easing function
		 */
		this.easing = function(easing) {

			_easingFunction = easing;
			return this;

		};

		/**
		 * chain the tween
		 * @name me.Tween#chain
		 * @public
		 * @function
		 * @param {me.Tween} chainedTween Tween to be chained
		 */
		this.chain = function(chainedTween) {

			_chainedTween = chainedTween;

		};

		/**
		 * onUpdate callback
		 * @name me.Tween#onUpdate
		 * @public
		 * @function
		 * @param {function} onUpdateCallback callback
		 */
		this.onUpdate = function(onUpdateCallback) {

			_onUpdateCallback = onUpdateCallback;
			return this;

		};

		/**
		 * onComplete callback
		 * @name me.Tween#onComplete
		 * @public
		 * @function
		 * @param {function} onCompleteCallback callback
		 */
		this.onComplete = function(onCompleteCallback) {

			_onCompleteCallback = onCompleteCallback;
			return this;

		};

		/** @private*/
		this.update = function(/* time */) {

			var property, elapsed, value;

			var time = me.timer.getTime();

			if (time < _startTime) {

				return true;

			}

			elapsed = (time - _startTime) / _duration;
			elapsed = elapsed > 1 ? 1 : elapsed;

			value = _easingFunction(elapsed);

			for (property in _valuesDelta) {

				_object[property] = _valuesStart[property]
						+ _valuesDelta[property] * value;

			}

			if (_onUpdateCallback !== null) {

				_onUpdateCallback.call(_object, value);

			}

			if (elapsed == 1) {

				// remove the tween from the object pool
				me.game.remove(this);

				if (_onCompleteCallback !== null) {

					_onCompleteCallback.call(_object);

				}

				if (_chainedTween !== null) {

					_chainedTween.start();

				}

				return false;

			}

			return true;

		};

		/** @private*/
		this.destroy = function() {

			// indicate we can safely be destroyed
			return true;

		};

	}

	/**
	 * Easing Function :<p>
	 * Easing.Linear.EaseNone<p>
	 * Easing.Quadratic.EaseIn<p>
	 * Easing.Quadratic.EaseOut<p>
	 * Easing.Quadratic.EaseInOut<p>
	 * Easing.Cubic.EaseIn<p>
	 * Easing.Cubic.EaseOut<p>
	 * Easing.Cubic.EaseInOut<p>
	 * Easing.Quartic.EaseIn<p>
	 * Easing.Quartic.EaseOut<p>
	 * Easing.Quartic.EaseInOut<p>
	 * Easing.Quintic.EaseIn<p>
	 * Easing.Quintic.EaseOut<p>
	 * Easing.Quintic.EaseInOut<p>
	 * Easing.Sinusoidal.EaseIn<p>
	 * Easing.Sinusoidal.EaseOut<p>
	 * Easing.Sinusoidal.EaseInOut<p>
	 * Easing.Exponential.EaseIn<p>
	 * Easing.Exponential.EaseOut<p>
	 * Easing.Exponential.EaseInOut<p>
	 * Easing.Circular.EaseIn<p>
	 * Easing.Circular.EaseOut<p>
	 * Easing.Circular.EaseInOut<p>
	 * Easing.Elastic.EaseIn<p>
	 * Easing.Elastic.EaseOut<p>
	 * Easing.Elastic.EaseInOut<p>
	 * Easing.Back.EaseIn<p>
	 * Easing.Back.EaseOut<p>
	 * Easing.Back.EaseInOut<p>
	 * Easing.Bounce.EaseIn<p>
	 * Easing.Bounce.EaseOut<p>
	 * Easing.Bounce.EaseInOut
	 * @public
	 * @type enum
	 * @name me.Tween#Easing
	 */
	me.Tween.Easing = {
		Linear : {},
		Quadratic : {},
		Cubic : {},
		Quartic : {},
		Quintic : {},
		Sinusoidal : {},
		Exponential : {},
		Circular : {},
		Elastic : {},
		Back : {},
		Bounce : {}
	};

	/** @ignore */
	me.Tween.Easing.Linear.EaseNone = function(k) {

		return k;

	};

	/** @ignore */
	me.Tween.Easing.Quadratic.EaseIn = function(k) {

		return k * k;

	};
	/** @ignore */
	me.Tween.Easing.Quadratic.EaseOut = function(k) {

		return -k * (k - 2);

	};
	/** @ignore */
	me.Tween.Easing.Quadratic.EaseInOut = function(k) {

		if ((k *= 2) < 1)
			return 0.5 * k * k;
		return -0.5 * (--k * (k - 2) - 1);

	};
	/** @ignore */
	me.Tween.Easing.Cubic.EaseIn = function(k) {

		return k * k * k;

	};
	/** @ignore */
	me.Tween.Easing.Cubic.EaseOut = function(k) {

		return --k * k * k + 1;

	};
	/** @ignore */
	me.Tween.Easing.Cubic.EaseInOut = function(k) {

		if ((k *= 2) < 1)
			return 0.5 * k * k * k;
		return 0.5 * ((k -= 2) * k * k + 2);

	};
	/** @ignore */
	me.Tween.Easing.Quartic.EaseIn = function(k) {

		return k * k * k * k;

	};
	/** @ignore */
	me.Tween.Easing.Quartic.EaseOut = function(k) {

		return -(--k * k * k * k - 1);

	}
	/** @ignore */
	me.Tween.Easing.Quartic.EaseInOut = function(k) {

		if ((k *= 2) < 1)
			return 0.5 * k * k * k * k;
		return -0.5 * ((k -= 2) * k * k * k - 2);

	};
	/** @ignore */
	me.Tween.Easing.Quintic.EaseIn = function(k) {

		return k * k * k * k * k;

	};
	/** @ignore */
	me.Tween.Easing.Quintic.EaseOut = function(k) {

		return (k = k - 1) * k * k * k * k + 1;

	};
	/** @ignore */
	me.Tween.Easing.Quintic.EaseInOut = function(k) {

		if ((k *= 2) < 1)
			return 0.5 * k * k * k * k * k;
		return 0.5 * ((k -= 2) * k * k * k * k + 2);

	};
	/** @ignore */
	me.Tween.Easing.Sinusoidal.EaseIn = function(k) {

		return -Math.cos(k * Math.PI / 2) + 1;

	};
	/** @ignore */
	me.Tween.Easing.Sinusoidal.EaseOut = function(k) {

		return Math.sin(k * Math.PI / 2);

	};
	/** @ignore */
	me.Tween.Easing.Sinusoidal.EaseInOut = function(k) {

		return -0.5 * (Math.cos(Math.PI * k) - 1);

	};
	/** @ignore */
	me.Tween.Easing.Exponential.EaseIn = function(k) {

		return k == 0 ? 0 : Math.pow(2, 10 * (k - 1));

	};
	/** @ignore */
	me.Tween.Easing.Exponential.EaseOut = function(k) {

		return k == 1 ? 1 : -Math.pow(2, -10 * k) + 1;

	};
	/** @ignore */
	me.Tween.Easing.Exponential.EaseInOut = function(k) {

		if (k == 0)
			return 0;
		if (k == 1)
			return 1;
		if ((k *= 2) < 1)
			return 0.5 * Math.pow(2, 10 * (k - 1));
		return 0.5 * (-Math.pow(2, -10 * (k - 1)) + 2);

	};
	/** @ignore */
	me.Tween.Easing.Circular.EaseIn = function(k) {

		return -(Math.sqrt(1 - k * k) - 1);

	};
	/** @ignore */
	me.Tween.Easing.Circular.EaseOut = function(k) {

		return Math.sqrt(1 - --k * k);

	};
	/** @ignore */
	me.Tween.Easing.Circular.EaseInOut = function(k) {

		if ((k /= 0.5) < 1)
			return -0.5 * (Math.sqrt(1 - k * k) - 1);
		return 0.5 * (Math.sqrt(1 - (k -= 2) * k) + 1);

	};
	/** @ignore */
	me.Tween.Easing.Elastic.EaseIn = function(k) {

		var s, a = 0.1, p = 0.4;
		if (k == 0)
			return 0;
		if (k == 1)
			return 1;
		if (!p)
			p = 0.3;
		if (!a || a < 1) {
			a = 1;
			s = p / 4;
		} else
			s = p / (2 * Math.PI) * Math.asin(1 / a);
		return -(a * Math.pow(2, 10 * (k -= 1)) * Math.sin((k - s)
				* (2 * Math.PI) / p));

	};
	/** @ignore */
	me.Tween.Easing.Elastic.EaseOut = function(k) {

		var s, a = 0.1, p = 0.4;
		if (k == 0)
			return 0;
		if (k == 1)
			return 1;
		if (!p)
			p = 0.3;
		if (!a || a < 1) {
			a = 1;
			s = p / 4;
		} else
			s = p / (2 * Math.PI) * Math.asin(1 / a);
		return (a * Math.pow(2, -10 * k)
				* Math.sin((k - s) * (2 * Math.PI) / p) + 1);

	};
	/** @ignore */
	me.Tween.Easing.Elastic.EaseInOut = function(k) {

		var s, a = 0.1, p = 0.4;
		if (k == 0)
			return 0;
		if (k == 1)
			return 1;
		if (!p)
			p = 0.3;
		if (!a || a < 1) {
			a = 1;
			s = p / 4;
		} else
			s = p / (2 * Math.PI) * Math.asin(1 / a);
		if ((k *= 2) < 1)
			return -0.5
					* (a * Math.pow(2, 10 * (k -= 1)) * Math.sin((k - s)
							* (2 * Math.PI) / p));
		return a * Math.pow(2, -10 * (k -= 1))
				* Math.sin((k - s) * (2 * Math.PI) / p) * 0.5 + 1;

	};
	/** @ignore */
	me.Tween.Easing.Back.EaseIn = function(k) {

		var s = 1.70158;
		return k * k * ((s + 1) * k - s);

	};
	/** @ignore */
	me.Tween.Easing.Back.EaseOut = function(k) {

		var s = 1.70158;
		return (k = k - 1) * k * ((s + 1) * k + s) + 1;

	};
	/** @ignore */
	me.Tween.Easing.Back.EaseInOut = function(k) {

		var s = 1.70158 * 1.525;
		if ((k *= 2) < 1)
			return 0.5 * (k * k * ((s + 1) * k - s));
		return 0.5 * ((k -= 2) * k * ((s + 1) * k + s) + 2);

	};
	/** @ignore */
	me.Tween.Easing.Bounce.EaseIn = function(k) {

		return 1 - Tween.Easing.Bounce.EaseOut(1 - k);

	};
	/** @ignore */
	me.Tween.Easing.Bounce.EaseOut = function(k) {

		if ((k /= 1) < (1 / 2.75)) {

			return 7.5625 * k * k;

		} else if (k < (2 / 2.75)) {

			return 7.5625 * (k -= (1.5 / 2.75)) * k + 0.75;

		} else if (k < (2.5 / 2.75)) {

			return 7.5625 * (k -= (2.25 / 2.75)) * k + 0.9375;

		} else {

			return 7.5625 * (k -= (2.625 / 2.75)) * k + 0.984375;

		}

	};
	/** @ignore */
	me.Tween.Easing.Bounce.EaseInOut = function(k) {

		if (k < 0.5)
			return Tween.Easing.Bounce.EaseIn(k * 2) * 0.5;
		return Tween.Easing.Bounce.EaseOut(k * 2 - 1) * 0.5 + 0.5;

	};


	/*---------------------------------------------------------*/
	// END END END
	/*---------------------------------------------------------*/
})(window);