var DEALING_CARD_TOP = '0px';
var DEALING_CARD_LEFT = '435px';
var CARD_VERTICAL_OFFSET = 225;
var CARD_HORIZONTAL_OFFSET = 175;
var CARD_FLIP_SPEED = 150;
var CARD_MOVE_SPEED = 200;

var cardBoard, dealingCard, flipCard;
var cardPosition, remainingNumbers, remainingCards, numbers;
var randomCard, randomCardTop, randomCardLeft, randomNumber;
var reader;

var overlay = {	
    CARD_OVERLAY_FADE_IN_SPEED : 1000,
    CARD_OVERLAY_FADE_OUT_SPEED : 500,
	
    overlayDiv : null,
	
    initialiseOverlay : function() {
        var overlayDiv = $(document.createElement('div'));	
        overlayDiv.attr('id', 'overlay');		
        $('body').append(overlayDiv);	
        this.overlayDiv = $('#overlay');
    },
	
    showOverlay : function() {
        this.overlayDiv.width($(document).width());			
        this.overlayDiv.height($(document).height());
        this.overlayDiv.show();
    /*this.overlayDiv.fadeIn(this.CARD_OVERLAY_FADE_IN_SPEED);
                this.overlayDiv.css('filter', 'alpha(opacity=30)');*/
    },
	
    hideOverlay : function() {
        /*this.overlayDiv.fadeOut(this.CARD_OVERLAY_FADE_OUT_SPEED);*/
        this.overlayDiv.hide();
    }
};

		
jQuery(document).ready(function($) {
    $(window).load(function() {
        /***** Psychic Readings Page *****/
        if ($('body.page-template-page-psychicreadings-php').length > 0) {	
            initialise();
            $('#loading').hide();
            $('#reload').show();
            dealingCard.click();
        }	
    });
	
    function initialise() {
        initialiseVariables();
        initialiseCardBoard();
        initialiseDealingCard();
        initialiseFlipCard();
        overlay.initialiseOverlay();
        
        $('#reload-cards').click(function(event) {
            event.preventDefault();
            dealingCard.click();
        });
        
        $('#show-all-cards').click(function(event) {
            event.preventDefault();
            
            $('#card-board .card').each(function(i, el) {
                var cardFront = $(this).children('.card-front');
                
                $(this).addClass('flipped');
                
                $(this).flip({
                    direction: 'tb',
                    content: cardFront,
                    color: '#fff',
                    speed: CARD_FLIP_SPEED                    	
                });
            });        
        });
    }
		
    function initialiseVariables() {        
        cardPosition = 0;
        remainingNumbers = $('#cards .card').length;
        var numberOfCardsToDeal = parseInt($('#numberOfCardsToDeal').val());
        remainingCards = numberOfCardsToDeal <= remainingNumbers ? numberOfCardsToDeal : remainingNumbers;
        
        numbers = new Array();        
        for (var i = 1; i < remainingNumbers + 1; i++) {
            numbers.push(i);
        }
    }
                
    function initialiseCardBoard() {
        cardBoard = $('#card-board');
    }
		
    function initialiseDealingCard() {
        dealingCard = createDealingCard();
        $('body').append(dealingCard);
					
        dealingCard.click(function(event) {
            // Clear out old cards and reset variables
            $('#card-board .card:not(#dealing-card)').remove();
            initialiseVariables();
				
            // Generate the 12 cards and lay them out in a 4 X 3 pattern
            dealCard();		
        });
    }
				
    function initialiseFlipCard() {
        flipCard = $(document.createElement('div'));	
        flipCard.attr('id', 'flipcard');		
        $('body').append(flipCard);	
    }
		
    function createDealingCard() {
        dealingCard = $(document.createElement('div'));
        dealingCard.addClass('card');
        dealingCard.attr('id', 'dealing-card');
        resetDealingCard(dealingCard);
        return dealingCard;
    }
		
    function resetDealingCard() {
        DEALING_CARD_LEFT = $(window).width() / 2 - 60;
			
        dealingCard.css('top', DEALING_CARD_TOP);
        dealingCard.css('left', DEALING_CARD_LEFT);
    }	
		
    function dealCard() {	
        var cardBoardLeft = cardBoard.offset().left;
        var cardBoardTop = cardBoard.offset().top;
		
        randomNumber = Math.floor(Math.random() * remainingNumbers);
        remainingNumbers--;
			
        var randomCardId = 'dealt-card-' + numbers[randomNumber];
        randomCard = $('#cards #card-' + numbers[randomNumber]).clone();
        randomCard.attr('id', randomCardId);
        numbers.splice(randomNumber, 1);
							
        randomCardTop = cardBoardTop + (Math.floor(cardPosition / 4) * CARD_VERTICAL_OFFSET);
        randomCardLeft = cardBoardLeft + ((cardPosition % 4) * CARD_HORIZONTAL_OFFSET);
        cardPosition++;
			
        dealingCard.show();
        dealingCard.animate({
            top: randomCardTop + 'px',
            left: randomCardLeft + 'px'
        },
        350,
        function() {
            //Animation complete												
            cardBoard.append(randomCard);	
            remainingCards--;
            resetDealingCard();					
					
            if (numbers.length > 0 && remainingCards > 0) {
                dealCard();
            } else {
                // Set up click events for the flipbox	
                $('#card-board .card').click(function(event) {
                    event.preventDefault();
								
                    flipCard.children().remove();					
                    flipCard.css('top', $(this).offset().top + 'px');
                    flipCard.css('left', $(this).offset().left + 'px');
                    flipCard.css('padding', '10px');
                    flipCard.addClass('active');

                    cardBoardLeft = cardBoard.offset().left;
                    cardBoardTop = cardBoard.offset().top;

                    if (!$(this).hasClass('flipped')) {
                        flipCard.append($(this).find('.card-back').clone());
                        
                        var cardFront = $(this).find('.card-front');
                        
                        flipCard.flip({
                            direction: 'tb',
                            content: cardFront,
                            color: '#ecdbd3',
                            speed: CARD_FLIP_SPEED                            
                        });
                        
                        flipCard.animate({
                            top: cardBoardTop - 100,
                            left: cardBoardLeft + 165
                        },
                        CARD_MOVE_SPEED
                        );                        
                    } else {
                        flipCard.append($(this).children().clone());
                        flipCard.css('top', cardBoardTop - 100 + 'px');
                        flipCard.css('left', cardBoardLeft + 165 + 'px');
                    }
                        
                    flipCard.click(function(event) {
                        $(this).children().remove();	
                        $(this).css('top', '0px');
                        $(this).css('left', '0px');		
                        $(this).css('padding', '0px');	
                        overlay.hideOverlay();							
                    });
							
                    overlay.showOverlay();
                });
						
                // Hide dealing card
                dealingCard.hide();
            }
        }
        );	
    }		

	
    /***** Wheel of Stars Page *****/
    var displayCard, randomNumber;
    var coords = [
    {
        x : 110,
        y : 820	
    },
    {
        x : 110,
        y : 890	
    },
    {
        x : 110,
        y : 950
    },
    {
        x : 190,
        y : 680	
    },
    {
        x : 190,
        y : 750	
    },
    {
        x : 190,
        y : 820	
    },
    {
        x : 190,
        y : 890	
    },
    {
        x : 190,
        y : 950	
    },
    {
        x : 270,
        y : 820	
    },
    {
        x : 270,
        y : 890	
    },
    {
        x : 270,
        y : 950	
    },
    {
        x : 530,
        y : 820	
    },
    {
        x : 530,
        y : 890	
    },
    {
        x : 530,
        y : 950
    },
    {
        x : 610,
        y : 680	
    },
    {
        x : 610,
        y : 750	
    },
    {
        x : 610,
        y : 820	
    },
    {
        x : 610,
        y : 890	
    },
    {
        x : 610,
        y : 950	
    },
    {
        x : 680,
        y : 820	
    },
    {
        x : 680,
        y : 890	
    },
    {
        x : 680,
        y : 950	
    }
    ];
	
    if ($('body.page-template-page-oraclewheel-php').length > 0) { 
        var spinType = "CSS";
		
        initialiseDisplayCard();
        overlay.initialiseOverlay();
        //showDisplayCard();
		
        if ($('html').hasClass('csstransforms')) {
            //$('#wheel-of-stars').find('.wheel-spin').remove();
            spinType = "CSS";
        } else {
            spinType = "ALTERNATION";
        }

        $('#wheel').click(function(event) {
            event.preventDefault();
			
            //spinWheelAlternation.spin();
            //return;
			
            switch (spinType) {
                case "CSS" :
                    spinWheelCSS.spin();
                    break;	
					
                case "ALTERNATION" :
                    spinWheelAlternation.spin();
                    break;
            }
        });
		
        $(window).load(function() {
            $('#loading').hide();
            $('#reload').show();
            $('#wheel').click();
        });
    }
	
    function initialiseDisplayCard() {
        displayCard = $(document.createElement('div'));	
        displayCard.attr('id', 'display-card');		
        $('body').append(displayCard);

        displayCard.click(function(event) {
            resetDisplayCard();
            overlay.hideOverlay();
        });
    }
	
    function resetDisplayCard() {
        displayCard.removeAttr('style');		
        displayCard.children().remove();
    }
	
    function showDisplayCard() {
        // Choose a random coordinate from the set
        randomNumber = Math.floor(Math.random() * coords.length);
        displayCard.append($('#card-' + (randomNumber + 1)).clone());
        var baseCoords = $('#wheel-of-stars-container').offset();
        displayCard.css('top', coords[randomNumber].y + baseCoords.top);
        displayCard.css('left', coords[randomNumber].x + baseCoords.left);	
        displayCard.show();	
		
        setTimeout(function() {
            displayCard.animate({
                top: baseCoords.top + 275,
                left: baseCoords.left + 100,
                width: '620',
                height: '330'
            },
            1000
            );
		
        //overlay.showOverlay();
        },
        500
        );
    }

    var spinWheelCSS = {
        WHEEL : $('#wheel'),
        ROTATION_CLASS : 'rotating',
        ROTATION_DECREASE_INTERVAL : 10,
        ROTATION_INTERVAL_DIFF : 5,
	
        rotationPeriod : 1,
        rotationAngle : 40,
        rotationIntervalCounter : 0,
        currentAngle : 0,
        timeout : 0,
		
        initialiseValues : function() {
            this.rotationPeriod = 1;	
            this.rotationAngle = 40;
            this.rotationIntervalCounter = 0;
            this.currentAngle = 0;
        },
		
        spin : function() {
            this.initialiseValues();
				
            if (this.WHEEL.hasClass(this.ROTATION_CLASS)) {
                this.stopWheel();
            } else {
                this.rotateWheel();			
            }
        },
		
        rotateWheel : function() {
            this.WHEEL.addClass(this.ROTATION_CLASS);	
            this.rotateWheelByDegrees();			
            this.timeout = setTimeout(function() {
                if (spinWheelCSS.rotationPeriod < 150 && spinWheelCSS.rotationAngle > 1) {
                    spinWheelCSS.rotateWheel();
                } else {
                    spinWheelCSS.stopWheel();
                    showDisplayCard();
                }
            }, 
            this.rotationPeriod);
        },
			
        stopWheel : function() {
            clearTimeout(this.timeout);
            setTimeout(function() {
                spinWheelCSS.WHEEL.removeClass(this.ROTATION_CLASS);
            },
            200
            );
        },
		
        rotateWheelByDegrees : function() {
            this.currentAngle += this.rotationAngle;
				
            if (this.currentAngle >= 360) {
                this.currentAngle -= 360;
            }
				
            this.WHEEL.css('-webkit-transform', 'rotate(' + this.currentAngle + 'deg)');
            this.WHEEL.css('-moz-transform', 'rotate(' + this.currentAngle + 'deg)');
            this.WHEEL.css('-ms-transform', 'rotate(' + this.currentAngle + 'deg)');
            this.WHEEL.css('-o-transform', 'rotate(' + this.currentAngle + 'deg)');
				
            this.rotationIntervalCounter++;
			
            if (this.rotationIntervalCounter % this.ROTATION_DECREASE_INTERVAL == 0) {
                this.rotationPeriod += this.ROTATION_INTERVAL_DIFF;
				
                if (this.rotationAngle > 0) {
                    this.rotationAngle -= 2;
                }
            } 
        }
    };
	
    var spinWheelAlternation = {
        WHEEL : $('#wheel'),
        ROTATION_CLASS : 'rotating',
        ROTATION_ALT_MAX : 350,
        ROTATION_ALT_MIN : 60,
        ROTATION_ALT_DIFF : 30,
        ROTATION_ALT_INCREMENT : 10,
	
        rotationAlt : this.ROTATION_ALT_MIN,
        rotationAltIncrement : this.ROTATION_ALT_INCREMENT,
        timeout : null,
        finished : false,
        count : 0,
		
        initialiseValues : function() {
            this.rotationAlt = this.ROTATION_ALT_MIN;	
            this.rotationAltIncrement = this.ROTATION_ALT_INCREMENT;
            this.timeout = null;
            this.finished = false;
            this.count = 0;
            this.WHEEL.addClass('wheel-css');
        },
		
        spin : function() {
            this.initialiseValues();
				
            if (this.WHEEL.hasClass(this.ROTATION_CLASS)) {
                this.stopWheel();
            } else {
                $('#wheel-spin-1').show();	
                $('#wheel-spin-2').hide();	
                $('.wheel-css').hide();
                this.WHEEL.addClass(this.ROTATION_CLASS);	
                this.rotateWheel();			
            }
        },
		
        rotateWheel : function() {
            $('.wheel-spin').toggle();	

            if (this.count == this.rotationAltIncrement) {
                if (this.rotationAlt >= this.ROTATION_ALT_MAX) {
                    this.finished = true;	
                } else {
                    this.rotationAlt += this.ROTATION_ALT_DIFF;
                    if (this.rotationAltIncrement > 1) {
                        this.rotationAltIncrement -= 1;
                    }
					
                    this.count = 0;	
                }
            }
			
            this.count++;
			
            if (!this.finished) {
                this.timeout = setTimeout(function() {
                    spinWheelAlternation.rotateWheel();
                },
                this.rotationAlt	
                );								
            } else {
                $('.wheel-spin').hide();
                this.stopWheel();
                showDisplayCard();
            }
        },
			
        stopWheel : function() {
            $('.wheel-spin').hide();	
            $('#wheel').show();
            clearTimeout(this.timeout);
            setTimeout(function() {
                spinWheelAlternation.WHEEL.removeClass(this.ROTATION_CLASS);
            },
            200
            );
        }
    };
});
