﻿jQuery.ufo = function(cfg) {
    var fwd = 0,
        back = 1,
        offset = 100;

    var animate = function($ufo) {
        var speed = 10000 + (Math.random() * 30000);
        $ufo.css('top', Math.floor(40 + (Math.random() * 300)) + 'px');

        if (Math.floor(Math.random() * 2) === fwd) {
            $ufo.show();
            $ufo.css('left', 0);
            $ufo.animate(
                { left: '+=' + (parseInt($('body').width()) - parseInt($ufo.width())) },
                speed,
                'linear',
                function() {
                    $ufo.hide();
                    setTimeout(function() { animate($ufo); }, 2000);
                }
            );
        }
        else {
            $ufo.show();
            $ufo.css('left', (parseInt($('body').width()) - parseInt($ufo.width())));
            $ufo.animate(
                { left: '-=' + (parseInt($('body').width()) - parseInt($ufo.width())) },
                speed,
                'linear',
                function() {
                    $ufo.hide();
                    setTimeout(function() { animate($ufo); }, 2000);
                }
            );
        }
    };

    var $ufos = $([$('<img width="35"  height="14" class="ufo" src="/Content/images/ufo-35.png">').prependTo('body'),
                 $('<img width="70"  height="27" class="ufo" src="/Content/images/ufo-70.png">').prependTo('body'),
                 $('<img width="100" height="39" class="ufo" src="/Content/images/ufo-100.png">').prependTo('body')]);

    //Setup position
    $ufos.each(function() {
        animate(this);
    });


};

