(function($){
    function start() {
        var basesize = 4;
        var grid = 12;

        var board = $('#board');
        var timer = $('#timer');
        $('#timerC').css('display', 'block');
        board.css('width', (220*basesize));
        var images = [], img;
        for(var i=1;i<=6;i++)
        {
            images.push('<img style="background-image: url(images/'+i+'.jpg);" src="images/back.jpg" />');
            images.push('<img style="background-image: url(images/'+i+'.jpg);" src="images/back.jpg" />');
        }


        fisherYates(images);
        board.append(images.join(''));
        
        var shown = 0;
        var found = 0;
        
        var last = null;
        var start = null;
        var timerT = null;
/*         var start = new Date();
        var timerT = setInterval(function () {
            timer.html((((new Date()) - start)/1000).toFixed(0));
        }, 500); */
        
        function finish() {
            var end = new Date();
            var d = (end - start)/1000;
            saveResult(d);
            clearTimeout(timerT);
            $('#timerC').css('display', 'none');
            $('#status').html('You finished the game in ' + d + ' seconds<br />Thank you for playing. Come back tomorrow to try again.<br />');
        }
        function saveResult(d)
        {
            $.ajax({
                url : 'ajax.php?act=saveresult',
                type: 'POST',
                data: "spenttime="+d,
                success: function (j) {},
                error: function (x, d, e) {
                }
            })
        }

        
        $('#board img').crossfade({
            type : 'mousedown',
            delay : 250,
            condition : function () {
                return !$(this).data('shown');
            }
        },
        {
            type : 'mouseleave',
            delay : 0,
            condition : function () {
                return !$(this).data('shown');
            }
        }).click(function () {
        
            if(start == null)
            {
                start = new Date();
            }
            if(timerT == null)
            {
                timerT = setInterval(function () {
                    timer.html((((new Date()) - start)/1000).toFixed(0));
                }, 500);
            }

        
            var $$ = $(this);

            if ($$.data('shown') || $$.data('found')) return false;
            
            shown++;
                                
            if (!last) {
                $$.data('found', true);
                last = $$;
            } else if (last.prev().attr('src') == $$.prev().attr('src')) {
                // found
                $$.data('found', true);
                last.data('found', true);
                
                //$('#status').html('Match found!');

                found++;
                
                $('#count').html(found + '/' + grid/2);
                

                // finished?
                if ((found*2) == grid) {
                    finish();
                }
            } else {
                //$('#status').html('No good :-(');
            }
            
            if (!$$.data('shown')) $$.data('shown', true);
            else $$.data('shown', false);
            
            $$.css('opacity', 0);

            if (shown == 2) {
                if (!$$.data('found')) last.removeData('found');
                $('img').filter(function () {
                    return !$(this).data('found');
                //}).removeData('shown').css('opacity', 1);
                }).removeData('shown').stop().animate({
                            opacity: 1
                        }, 1500);

                shown = 0;
                last = null;
            }
                                                    
            return false;
        });
        //document.documentElement.offsetHeight
        window.setTimeout(function(){document.documentElement.scrollTop = 1000}, 600)
    }
    
    
    function fisherYates(array) {
      var j, tempi, tempj, i = array.length;
      if ( i == 0 ) return false;
      while ( --i ) {
         j = Math.floor( Math.random() * ( i + 1 ) );
         tempi = array[i];
         tempj = array[j];
         array[i] = tempj;
         array[j] = tempi;
       }
    }
    
    function validateEmail(email) {
        var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
        if(reg.test(email) == false)
        {
            return false;
        }
        return true;
    }
    
    $(document).ready(function(){
        $('#startGameButton').click(function(){
            var name = $('#name').attr('value');
            var email = $('#email').attr('value');
            if(name == undefined || name == '')
            {
                $('#loginError').attr('innerHTML','Name cannot be left blank.');
                return false;
            }
            if(email == undefined || email == '')
            {
                $('#loginError').attr('innerHTML','Email cannot be left blank.');
                return false;
            }else if(!validateEmail(email))
            {
                $('#loginError').attr('innerHTML','Invalid Email Address.');
                return false;
            }
            $.ajax({
                url : 'ajax.php?act=newgame',
                type: 'POST',
                data: "name="+name+"&email="+email,
                success: function (j) 
                {
                    //if()
                    if((eval('('+j+')').code) == 1)
                    {
                        $('#loginError').attr('innerHTML','Please come back and try your skills again tomorrow.');
                    }else if((eval('('+j+')').code) == 0){
                        //$('#loginForm').css('display', 'none')
                        start();  
                    }
                },
                error: function (x, d, e) {
                    $('#loginError').attr('innerHTML','Unknow Error.');
                }
            })
        })
    });
})(jQuery);