;(function($) {

    Array.prototype.remove = function(from, to) {
        var rest = this.slice((to || from) + 1 || this.length);
        this.length = from < 0 ? this.length + from : from;
        return this.push.apply(this, rest);
    };

    var iScrollCounter = 0;
    var iCurX = 240;
    var iCurKey = -1;
    var iLives = 3;
    var iScore = 0;
    var iLevel = 1;
    var iItemCount = 0;
    var bStarted = false;
    var aItems = [] ;
    var iTimer = 0;

    $.fn.basket = function () {

        // Loop through matched elements
        return this.each(function() {

            // Get current object
            var obj = $(this);
            obj.html("");
            obj.html($('<div class="bike"></div><div class="backTop"></div><div class="backBottom"></div><div id="map-msg">Druk op start om<br/> het spel te beginnen</div><div id="stats">         <span id="stats-score-label">Punten</span>         <span id="stats-score">0</span>         <span id="stats-level-label">Level</span>         <span id="stats-level">0</span>         <span id="stats-lives-label">Levens</span>         <span id="stats-lives">0</span>         <a href="#start" id="start-game">Start</a>     </div>'));

            window.setInterval(function () {
                iScrollCounter++;
                iScrollCounter %= 5000;
                iScrollCounterTop = iScrollCounter % 1250;
                $('.backTop').css('background-position', '-' + iScrollCounterTop + 'px 0px');
                $('.backBottom').css('background-position', '-' + (iScrollCounter * 10) + 'px 0px');

                if (bStarted) {
                    switch (iCurKey) {
                        case 37:
                            iCurX -= 15;
                            if (iCurX < 79) {
                                iCurX = 79;
                            } else if (iCurX > 376) {
                                iCurX = 376;
                            }
                            $('.bike').css('left', (iCurX - 79) + 'px');
                            break;
                        case 39:
                            iCurX += 15;
                            if (iCurX < 79) {
                                iCurX = 79;
                            } else if (iCurX > 376) {
                                iCurX = 376;
                            }
                            $('.bike').css('left', (iCurX - 79) + 'px');
                            break;
                    }
                    var iRemove = -1;
                    for (var i = 0; i < aItems.length; i++) {
                        aItems[i].y += 13;
                        $('.basketItem' + aItems[i].itemcount)
                            .css({
                                'top': aItems[i].y
                            });
                        if (aItems[i].y == 210) {
                            if (Math.abs((aItems[i].x + 70) - iCurX) < 40) {
                                if (aItems[i].type == 0) {
                                    iScore += 10;
                                } else {
                                    iLives--;
                                    if (iLives == 0) {
                                        $('#map-msg').show();
                                        $("#map-msg").html('Je bent af, druk op start om nog een keer te spelen');
                                        bStarted = false;
                                    }
                                }
                                $('.basketItem' + aItems[i].itemcount).remove();
                                iRemove = i;
                                RepaintStats();
                            }
                        } else if (aItems[i].y > 456) {
                            if (aItems[i].type == 0) {
                                iLives--;
                                if (iLives == 0) {
                                    $('#map-msg').show();
                                    $("#map-msg").html('Je bent af, druk op start om nog een keer te spelen');
                                    bStarted = false;
                                }
                            }
                            $('.basketItem' + aItems[i].itemcount).remove();
                            iRemove = i;
                            RepaintStats();
                        }
                    }
                    if (iRemove != -1) {
                        aItems.shift();
                    }
                    if (iTimer % 50 == 0) {
                        var newitem = {
                            'itemcount': iItemCount,
                            'type': Math.random() < 0.7 ? 0 : 1,
                            'x': parseInt(Math.random() * (480-146)),
                            'y': -50
                        };
                        var typeString = 'basketType' + newitem['type'];
                        random = Math.random();
                        if (newitem['type'] == 0) {
                            if (random < 0.33) {
                                typeString = 'basketType0_1';
                            } else if (random < 0.66) {
                                typeString = 'basketType0_2';
                            }
                        }
                        if (newitem['type'] == 1) {
                            if (random < 0.5) {
                                typeString = 'basketType1_1';
                            }
                        }
                        obj.append($('<div class="basketItem basketItem' + iItemCount + ' ' + typeString + '"></div>'));
                        $('.basketItem' + newitem['itemcount'])
                            .css({
                                'left': newitem['x'],
                                'top': -50
                            });
                        aItems.push(newitem);
                        iItemCount++;
                        iLevel = 1 + parseInt(iItemCount / 10);
                    }
                    iTimer++;
                }
            }, 100);
            function RepaintStats () {
                $('#stats-score').html('' + iScore);
                $('#stats-lives').html('' + iLives);
                $('#stats-level').html('' + iLevel);
            }
            function NewGame () {
                iLives = 3;
                iScore = 0;
                iLevel = 1;
                iItemCount = 0;
                iTimer = 0;
                RepaintStats();
                $('.basketItem').remove();
                $('#map-msg').hide();
                bStarted = true;
                aItems = [];
            }
            $('#start-game').click (function () {
                NewGame();
            });

            document.onkeyup = function(e){
                iCurKey = -1;
            };
            document.onkeydown = function(e){
                keycode = (e == null) ? event.keyCode : e.which;
                iCurKey = keycode;
            };
        });
    };

    $(document).ready(function () {
        $(".basket").basket();
    });

})(jQuery);
