/**
 * Script to provide functionality on the buy now page
 * Requires JQuery and JQueryUI
 * @author Chris MacPherson
 */
var game;
var gameDivId;
var gamePrefix;
var trans = Array(); // Not great but needed for regenerated elements with translations

trans['Full Game'] = 'Full Game';
trans['Downloadable Content'] = 'Downloadable Content';
trans['loadingMsg'] = 'loading...';
trans['initialMsg'] = 'Please select a game';
trans['emptyMsg']   = 'Coming soon';
trans['Unique Unit'] = 'Unique Unit';
trans['Retailer Promotion'] = 'Retailer Promotion';


$(document).ready(function(){
    // Add event handler for dropdown box game links
    $('#buynow #games-list-items a').click(function(){

        // If user clicks on a new game then all games/game-types/versions/retailer info should be reset
        if ($(this).parent().hasClass('on') == false) {
            game = $(this).parent();
            gameDivId = game.attr('id');
            gamePrefix = gameDivId.substr(gameDivId.indexOf('-') + 1);

            // Clear game-type
            if ($('#game-type-options').length > 0) {
                // Clear retailer info

                // Clear editions
                $('#game-editions-wrapper').fadeOut("slow", function() {
                    // Hide all game-editions
                    $('div.game-edition').hide();
                    
                    // Clear game types
                    $('#game-type-options').slideUp("slow", function() {
                        $(this).remove();  // remove game type nodes

                        // Clear retailer info 
                        buildRetailers(0);

                        $('div[id^="game-"]').removeClass('on'); // switch off highlighted state

                        // Show correct background image for game
                        //$('#game-editions').css('background-image', 'url(/images/buynow/buynow' + gamePrefix + '_poster.jpg)');
                        $('#buynow').css('background-image', 'url(/images/buynow/buynow' + gamePrefix + '_poster.jpg)');

                        // Black semi-transparent overlay
                        $('#buyNowOverlay').css('display', 'none');

                        showGameTypes(game, gamePrefix);
                    });                    
                });
            } else {
                //$('#game-editions').css('background-image', 'url(/images/0/buynow' + gamePrefix + '_poster.jpg)');
                $('#buynow').css('background-image', 'url(/images/buynow/buynow' + gamePrefix + '_poster.jpg)');
                
                // Initial click so no clearing necessary
                showGameTypes(game, gamePrefix);
            }
        }
        return false;
    });
    
    // Add another event handler for Version Game box clicks
    $('#game-editions-wrapper div[id^=game-]').click(function(e){
       
        // Parse out game info
        var parts = $(this).attr('id').split('-');
        game = parseInt(parts[parts.length - 3], 10);
        
        buildRetailers(game, parts[parts.length - 2], parts[parts.length - 1]);        
    });
    
    // Add another event handler to stop Version Game 'more info' links from bubbling up
    $('#game-editions-wrapper .more-info').click(function(e){
        e.stopPropagation();
    });
    
    
    
});

/**
 * Add a 'full game' and 'downloadable content' button under the selected game button.
 * Also need add event handlers after buttons are created to deal with stuff like hiding 
 * content and de-selecting buttons that become irrelevant on click. 
 * @param int game 
 * @param int gamePrefix
 */
function showGameTypes(game, gamePrefix) {
    $('#game-editions-wrapper').css('display', 'block');
    if (game.hasClass('on') == false) {
        var gameTypeSelectors = '<div id="game-type-options" style="display:none;"><div id="fullgame-' +gamePrefix + '" class="game-type">';
        gameTypeSelectors += '<a href="#"><span>' + trans['Full Game'] + '</span><span class="arrow"></span></a><div class="separator">&nbsp;</div></div>';
        
        // Add downloadable button only if downloads exist
        if ($('div[id^="game-' + gamePrefix + '-downloadable-"]').length > 0) {
            gameTypeSelectors += '<div id="downloadable-' +gamePrefix + '" class="game-type">';
            gameTypeSelectors += '<a href="#"><span>' + trans['Downloadable Content'] + '</span><span class="arrow"></span></a><div class="separator">&nbsp;</div></div></div>';
        }
        
        game.addClass('on'); // highlight selected game
        game.after(gameTypeSelectors); // Add game-type selectors

        // Add event handler for full game button
        $('#buynow div[id^="fullgame"] a').click(function() {
            gameType = $(this).parent();
            gameDivId = gameType.attr('id');
            gamePrefix = gameDivId.substr(gameDivId.indexOf('-') + 1);

            // If this button is not switched on
            if (gameType.hasClass('on') == false) {
                // Clear all game editions - fullgames and downloads
                $('div.game-edition').hide();

                // Clear all retailer info
                buildRetailers(0);

                // Switch off download games incase it's on
                $('div[id^="downloadable-"]').removeClass('on');

                // Black semi-transparent overlay
                $('#buyNowOverlay').css('display', 'block');

                // Switch on button
                gameType.addClass('on');

                // Turn off all other buttons
                deselectEditionButtons();
                
                // Show fullgames
                var counter = 0;
                $('div[id^="game-' + gamePrefix + '-fullgame-"]').each(function(){
                    counter++;
                    $(this).fadeIn();
                });
                if(counter > 4) {
                    $('#game-editions-wrapper').addClass('scrollableArea');
                } else {
                    $('#game-editions-wrapper').removeClass('scrollableArea');
                }

                // Add event handlers to new game-edition buttons
                $('div[id^="game-' + gamePrefix + '-fullgame-"] a').click(function(){
                    if ($(this).parent().hasClass('on') == false) {
                        // Turn off all other buttons
                        deselectEditionButtons();

                        // Turn this one on
                        $(this).parent().addClass('on');
                    }
                });
            }
            return false
        });
        
        // Add event handler for downloadable button
        $('#buynow div[id^="downloadable"] a').click(function() {
            gameType = $(this).parent();
            gameDivId = gameType.attr('id');
            gamePrefix = gameDivId.substr(gameDivId.indexOf('-') + 1);

            // If this button is not switched on
            if (gameType.hasClass('on') == false) {
                // Clear all game editions - fullgames and downloads
                $('div.game-edition').hide();

                // Clear all retailer info
                buildRetailers(0);
                
                // Switch off full games incase it's on
                $('div[id^="fullgame-"]').removeClass('on');
                
                // Black semi-transparent overlay
                $('#buyNowOverlay').css('display', 'block');

                // Switch on button
                gameType.addClass('on');

                // Turn off all edition buttons
                deselectEditionButtons();
                
                // Show fullgames
                var counter = 0;
                $('div[id^="game-' + gamePrefix + '-downloadable-"]').each(function(){
                    counter++;
                    $(this).fadeIn();
                });
                if(counter > 4) {
                    $('#game-editions-wrapper').addClass('scrollableArea');
                } else {
                    $('#game-editions-wrapper').removeClass('scrollableArea');
                }

                // Add event handlers to new game-edition buttons
                $('div[id^="game-' + gamePrefix + '-downloadable-"] a').click(function(){
                    if ($(this).parent().hasClass('on') == false) {
                        // Turn off all other buttons
                        deselectEditionButtons();

                        // Turn this one on
                        $(this).parent().addClass('on');
                    }
                });
            }
            return false;
        });
        $('#game-type-options').slideDown("slow"); // show game-type selectors
    }
} 

/**
 * De-select all of the edition buttons
 */
function deselectEditionButtons() {
    $('div.game-edition').removeClass('on');
}

/**
 * Build the HTML for the retailers panel. Add event handlers too. 
 * @param game
 * @param language
 */
function buildRetailers(game, language, territoryid) {
    // First remove all retailer nodes that exists and add loading status.
    var boxedCountries = '';
    var digitalCountries = '';

    // Update HTML
    $('#boxed-game .country-list').empty().html('<div class="retailer-status"><p>' + trans['loadingMsg'] + '</p></div>');
    $('#digital-download .country-list').empty().html('<div class="retailer-status"><p>' + trans['loadingMsg'] + '</p></div>');
        
    if (parseInt(game, 10) > 0) {
        $.getJSON("/liblocal/buynow.php?g=" + game + '&l=' + language+'&territoryid='+territoryid, function(countries){            
            if (countries && countries.length > 0) {
                for (var i = 0; i < countries.length; i++) {
                    // If has boxed retailers add country to boxed list.
                    if (countries[i].retailers.physical.length > 0) {
                        boxedCountries += '<div class="country"><a class="accordian" href="#"><img class="flag" src="/images/flags/' + (countries[i].identifier.toLowerCase() == 'world' ? '' : 'all_flags/');
                        boxedCountries += countries[i].identifier.toLowerCase() + '.' + (countries[i].identifier.toLowerCase() == 'world' ? 'png' : 'gif') + '" /><span class="country-name">' + countries[i].name;
                        boxedCountries += '</span><span class="toggle"><img class="toggle-image" src="/images/0/iconPlus.png" /></span></a><div class="retailer-list">';

                        // Now add retailers for the country

                        for (var j = 0; j < countries[i].retailers.physical.length; j++) {

                            var retailer = countries[i].retailers.physical[j];
                            
                            boxedCountries += '<div class="retailer-link"><a target="_blank" href="' + (retailer.url ? retailer.url : retailer.link) + '" class="retailer-logo"><span><img src="' + retailer.logo + '"></span></a></div><div class="clear">&nbsp;</div>';
                            boxedCountries += '<div class="retailer">';
                            if (typeof retailer.extraInfo == 'string' && retailer.extraInfo.length > 0) {
                                boxedCountries += '<a class="retailer-promotion-' + retailer.extraInfo + '" href="#">' + trans['Retailer Promotion'] + ' <img src="/images/0/buynow_infoBtn.png" /></a>';
                            }
                            
                            boxedCountries += '</div>'; 
                        }

                        // Close retailer and country elements
                        boxedCountries += '<div class="clear">&nbsp;</div></div></div>';
                    }
                                
                    // If has boxed retailers add country to boxed list.
                    if (countries[i].retailers.digital.length > 0) {
                        digitalCountries += '<div class="country"><a class="accordian" href="#"><img class="flag" src="/images/flags/' + (countries[i].identifier.toLowerCase() == 'world' ? '' : 'all_flags/');
                        digitalCountries += countries[i].identifier.toLowerCase() + '.' + (countries[i].identifier.toLowerCase() == 'world' ? 'png' : 'gif') + '" /><span class="country-name">' + countries[i].name;
                        digitalCountries += '</span><span class="toggle"><img class="toggle-image" src="/images/0/iconPlus.png" /></span></a><div class="retailer-list">';

                        // Now add retailers for the country
                        for (var j = 0; j < countries[i].retailers.digital.length; j++) {

                            var retailer = countries[i].retailers.digital[j];
                            
                            digitalCountries += '<div class="retailer-link"><a target="_blank" href="' + (retailer.url ? retailer.url : retailer.link) + '" class="retailer-logo"><span><img src="' + retailer.logo + '"></span></a></div><div class="clear">&nbsp;</div>';
                            digitalCountries += '<div class="retailer">';
                            
                            if (typeof retailer.extraInfo == 'string' && retailer.extraInfo.length > 0) {
                                digitalCountries += '<a class="retailer-promotion-' + retailer.extraInfo + '" href="#">' + trans['Retailer Promotion'] + ' <img src="/images/0/buynow_infoBtn.png" /></a>';
                            }
                            
                            digitalCountries += '</div>'; 
                        }
                        
                        // Close retailer and country elements
                        digitalCountries += '<div class="clear">&nbsp;</div></div></div>';
                    }
                }
            }

            // If there are no retailers for eaither section then add a message
            if (boxedCountries == '') {
                // No retailers available
                boxedCountries = '<div class="retailer-status">' + trans['emptyMsg'] + '</div>';
            }
            
            if (digitalCountries == '') {
                // No retailers available
                digitalCountries = '<div class="retailer-status">' + trans['emptyMsg'] + '</div>';
            }
            
            $('#boxed-game .country-list').empty().html(boxedCountries);
            $('#digital-download .country-list').empty().html(digitalCountries);

            // If there is only one country then open it up by default
            if (countries && countries.length == 1) {
                $('.country .retailer-list').each(function(){
                    if ($(this).is(":hidden")) {
                        $(this).slideDown('slow', function(){
                            $(this).children('.retailer').children('.unit-info').css('position', 'static');
                            $(this).parent().children('a').children('.toggle').children().attr('src', '/images/0/iconMinus.png');
                        });
                        
                    }
                });
            }
            
            
            // Add event handlers to toggle countries
            $('div.country a.accordian').click(function(){
                
                var rList = $(this).parent().children('.retailer-list');
             
                // Close
                if (rList.is(":visible")) {
                    rList.slideUp('slow', function(){
                        rList.children('.retailer').children('.unit-info').css('position', 'static');
                        $(this).parent().children('a').children('.toggle').children().attr('src', '/images/0/iconPlus.png');
                    });
                    
                } else {
                    // Open 
                    
                    // First close any open country
                    $('.country .retailer-list').each(function(){
                        if ($(this).is(":visible")) {
                            $(this).slideUp('slow', function(){
                                $(this).children('.retailer').children('.unit-info').css('position', 'static');
                                $(this).parent().children('a').children('.toggle').children().attr('src', '/images/0/iconPlus.png');
                            });
                            
                        }
                    });
                    
                    rList.slideDown('slow', function(){
                        rList.children('.retailer').children('.unit-info').css('position', 'relative');
                        $(this).parent().children('a').children('.toggle').children().attr('src', '/images/0/iconMinus.png');
                    });
                }
                return false;
            });
            
            // Add event handlers to the retailer promotion links
            $('a[class^=retailer-promotion]').live('click', function(e) {
                e.preventDefault();
                var promotion = $(this).attr('class').substr(19);
                openDialog(promotion);             
                return false;
            });
        });     
    } else {
        // Update HTML
        $('#boxed-game .country-list').empty().html('<div class="retailer-status"><p>' + trans['initialMsg'] + '</p></div>');
        $('#digital-download .country-list').empty().html('<div class="retailer-status"><p>' + trans['initialMsg'] + '</p></div>');
    }
}

/**
 * Create and open a JQuery dialog popup for retailer promotions
 * @param string retailerPromotion
 * @return void
 */
function openDialog(retailerPromotion) {
    
    var dialog;
    var options = {
            autoOpen   : false,
            autoResize : true,
            modal      : true,
            resizable  : false,
            draggable  : false,
            width      : 665,
            height     : 'auto',
            position   : 'center',
            open       : function(event, ui) {
                $(this).closest('.ui-dialog').find('.ui-dialog-titlebar-close').hide();
            }
        };
        
    // Configure and init dialog if not already 
    if (!dialog) {
        dialog = $('#popup').dialog(options);
    }
    
    // Set the body to loading message
    $('#popup-success').hide();
    $('#popup-loading').show();
    
    
    // Try and fetch steam details for game
    $.post('/liblocal/retailer-promotion.php', {p: retailerPromotion}, function(content){
        // Queue the centering of the dialog until after content has been added and thus height established.
        $('#popup-success').html(content).queue(function() {
            dialog.dialog('option', 'position', 'center');
        }).show();
        $('#popup-loading').hide();        
        dialog.dialog('open');
    });
    
    
    
    // Add event handler for close button
    $('.pop-up-close').click(function() {
        dialog.dialog('close');
    });
    
}

/**
 * Close the retailer promotion popup dialog
 * @return void
 */
function closeDialog() {
    // Close game unlock pop-up if open
    $('#popup').dialog('close');
}
