
/** coding: UTF-8
 *
 * Pictogame javascript tools
 *
 */

/*
opt.
    id              <= id of embed                                      (default: 'flashContainer')
    swf             <= path to game container swf
    flashvars       <= parameters to swf                                (if gamecode is defined, 'gameId={gamecode}' else empty string)
    width           <= width of swf                                     (default: 410)
    height          <= height of swf                                    (default: 340)
    internal        <= internal flash or not (allowScriptAccess)        (default: false)
    links           <= display links on the bottom of embed or not      (default: false)
    gamecode        <= gamecode if it's the only var to send to embed   (no default value)
    game_name       <= gameName                                         (no default value)
    template        <= game's template ID                               (no default value)
    template_name   <= game's template name                            (no default value)
*/

function makeFlashObject(opt)
{
    var default_opt = { id: 'flashContainer'+Math.ceil(Math.random()*1e9), width: 410, height: 340, internal: false, links: false, flashvars: '', wmode: '' }

    opt.flashvars = (opt.flashvars || '');
    if ((opt.flashvars.search(/gameId=/) == -1) // flashvars may not contain gameId variable
        && ((typeof opt.gamecode) != 'undefined')  // gamecode should be defined
        && (opt.template != 99)) // uploaded games don't need gameId
    {
        if (opt.flashvars.length > 0)
        {
            opt.flashvars += '&';
        }
        opt.flashvars += 'gameId=' + opt.gamecode;
    }

    if (opt.ads == false)
    {
        if (opt.flashvars.length > 0)
            opt.flashvars += '&';
        opt.flashvars += 'm=0';
    }

    var param_wmode = '';
    var embed_wmode = '';
    opt.wmode = (opt.wmode || '');
    if (opt.wmode.length > 0)
        {
            param_wmode = '<param name="wmode" value="'+opt.wmode+'" />';
            embed_wmode = 'wmode="'+opt.wmode+'"';
        }

    opt = Object.extend(default_opt, opt);

    var str = '';
    var movie = '';
    if (opt.swf.search(/http:\/\//) == 0 || opt.swf.search(/^\//) == 0) // if opt.swf is a direct link
    {
        movie = opt.swf
    }
    else
    {
        movie = ((yTools.s3BaseUrl + opt.swf) || '');
    }

    if (opt.links)
    {
        str += '<div>';
    }
    else
    {
        str += '<object width="' + opt.width + '" height="' + opt.height + '" id="' + opt.id + '"';
        str += ' classid="clsid:D27CDB6E-AE6D-11CF-96B8-444553540000"';
        str += ' codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,22,0">';
        str += '<param name="movie" value="' + movie + '" />';
        str += '<param name="quality" value="high" />';
        str += param_wmode;
        str += '<param name="flashvars" value="' + opt.flashvars + '" />';
        if (opt.internal) {
            str += '<param name="allowScriptAccess" value="always" />';
        }
        else {
            str += '<param name="allowScriptAccess" value="never" ';
        }
        str += '<param name="allowFullScreen" value="true" />';
    }
    str += '<embed type="application/x-shockwave-flash" quality="high" ';
    str += 'src="' + movie + '" width="' + opt.width + '" height="' + opt.height + '" ' + embed_wmode;
    if (opt.internal) {
        str += 'allowScriptAccess="always" ';
    }
    else {
        str += 'allowScriptAccess="never" ';
    }
    str += 'allowFullScreen="true" flashvars="' + opt.flashvars + '" name="' + opt.id + '">';
    str += '</embed>';
    if (opt.links)
    {
        var base_url = 'http://' + document.location.hostname;

        str += '<div style="width:' + opt.width + 'px; text-align: left;">';
        create_url = '/create/' + (opt.template ? opt.template + (opt.template_name ? opt.template_name : '') : '');
        str += '<a href="' + base_url + create_url + '"><strong>';
        str += 'Make a game</strong></a>&nbsp;|&nbsp;';
        str += '<a href="' + base_url + '/play/game/'+opt.gamecode + (opt.game_name ? opt.game_name : '')+'">';
        str += ((opt.game_title) ? game_title : 'Share')+'</a>&nbsp;|&nbsp;';
        str += '<a href="' + base_url + '/play/game/" title="';
        str += 'Free games" >Free games</a>&nbsp;|&nbsp;';
        str += '<a href="http://technorati.com/tag/Pictogame" rel="tag">Pictogame</a>';
        str += '</div>';
        str += '</div>';
    }
    else
    {
        str += '</object>';
    }

    return str;
}

//
// Game Container tools
//

var yTools = {
    s3BaseUrl: '',
    domCallback: null,

    initialize: function(s3url) {
        this.s3BaseUrl = s3url;
    },
    // onDOMLoad and wait4dom are both deprecated
    // use prototype Event.observe or better way, document.observe with 'dom:loaded' parameter
    // Keep function declaration to avoid javascript errors.

    // Invokes window.onDOMLoad() when the dom is loaded
    onDOMLoad: function() {},
    wait4dom: function() {},

    // Writes down the game details such as url and embed
    writeGameDetails: function(game, game_name, game_title, template, template_name, container, flashvars, targets, width, height) {
        var inputObj;
        for (var i=0; i < targets.length; ++i) {
            switch (targets[i]) {
                case 'publishGameFieldset_embed':
                    if (!!($('publishGameFieldset_embed')))
                        $('publishGameFieldset_embed').value = makeFlashObject({ links: true, gamecode: game, game_name: game_name, game_title: game_title, swf: container, width: width, height: height, template: template, template_name: template_name, flashvars: flashvars, ads: true});
                    break;
                case 'publishGameFieldset_forum':
                    if (!!($('publishGameFieldset_forum')))
                        $('publishGameFieldset_forum').value = '[url='+document.location.href+'][img]'+yTools.s3BaseUrl+'games/'+game+'_thumb.png[/img][/url]';
                    break;
            }
        }
    },

    // Writes down the game object/embed swf
    writeGameObject: function(game, container, target, width, height, game_template, flashvars, fullWidth) {
        var tObj;

        if (!Object.isElement(tObj = $(target)))
            return;

        if (fullWidth != true)
            tObj.setStyle({ 'width': width+'px', 'height': height+'px' });
        else
            tObj.setStyle({ 'height': (height+20)+'px' });

        tObj.update(makeFlashObject({ id: 'game_gameContainer_flashObj', swf: container, gamecode: game, width: width, height: height, template: game_template, flashvars: flashvars, ads: false }));
    },
    writeGameObjectInHomePage: function(game, container, target, width, height) {
        var tObj;

        if (!Object.isElement(tObj = $(target)))
            return;

        tObj.update(makeFlashObject({ swf: container, gamecode: game, width: width, height: height, ads: false }));
    },

    applyCustomSize: function(game, game_name, game_title, template, template_name, container, flashvars, target, width, height) {
        if (typeof width == 'undefined') {
            width = $('customWidth').value;
        } else {
            $('customWidth').value = width;
        }
        this.writeGameDetails(game, game_name, game_title, template, template_name, container, flashvars, target, width, Math.round(width*default_height/default_width));
    },
    writeFlash: function(msg) {
        document.write(msg);
    }
}

Element.addMethods({
    addOnlyClassName: function(element, cssClass) {
        if (!(element = $(element))) return;
        element.className = cssClass;
        return element;
    }
});

//
// Toggle other sizes
//

function yg_toggleSizes(elt) {
    if (typeof(elt) == 'undefined')
        elt = 'block_otherSizes';
    Effect.toggle(elt,'appear');
}

//
// Toggle game menu function
//

function yg_toggleMenu(id, link) {
    var blocks = ['block_user_games', 'block_last_created', 'block_best_rated', 'block_most_viewed'];
    blocks.each(Element.hide);
    $(blocks[id]).show();

    if (link != null)
    {
        $('game_relatedGamesMenu').select('a').invoke('removeClassName', 'block_visible');
        link.addClassName('block_visible');
    }
}

//
// Methods used by "Play more games" block in game page.
//

function yg_observeGamesBlock(e) {
    var element = Event.element(e);

    if (element.up().hasClassName('selected')) return;

    $$('#game_playMore_tabBar li.selected').invoke('removeClassName', 'selected');
    element.up().addClassName('selected');

    yg_getGamesBlock(element.readAttribute('block'), element.readAttribute('user'));
}

function yg_getGamesBlock(block, user) {
    var throbber = new yg_throbber();
    throbber.show('game_playMore_games_throbber', 'game_playMore_gamesList', false);

    gameBlock = new yRemote();
    gameBlock.onLoad = function(status, data)
    {
        $('game_playMore_gamesList').hide();
        if (status == 200 && data !== null)
        {
            // Got definitive response (success or failure)
            if (data.success && data.block) {
                if (throbber)
                    throbber.hide();
                $$('#game_playMore_tabBar li.selected').invoke('removeClassName', 'selected');
                $$('a[block="'+data.block+'"]').first().up().addClassName('selected');
            }
        }
    };

    var data = {
        block: block,
        login: user
    };

    gameBlock.post('/services/game/getBlock.php', data);
    return true;
}

//
// Methods used by "topGames" block in account page
//
function yg_observeUserTopGamesBlock(e) {
    var element = Event.element(e);

    if (element.up().hasClassName('selected')) return;

    $$('#userTopGames_tabCol li.selected').invoke('removeClassName', 'selected');
    element.up().addClassName('selected');

    yg_getUserTopGames(element.readAttribute('block'));
}

function yg_getUserTopGames(block) {
    var throbber = new yg_throbber();
    throbber.show('userTopGames_throbber', 'userTopGames_gameList', false);

    gameBlock = new yRemote();
    gameBlock.onLoad = function(status, data)
    {
        if (status == 200 && data !== null)
        {
            if (throbber)
                throbber.hide();
        }
    };

    var data = {
        blockType: block
    };

    gameBlock.post('/services/game/getUserTopGames.php', data);
    return true;
}

//
// Login / Register methods.
//

    function yg_goSignupAndBack(error) {
        if (typeof error != 'undefined' &&
            typeof(error['block_signinStatus']['value']) != 'undefined' &&
            typeof(error['block_signinStatus']['css']) != 'undefined' &&
            error['block_signinStatus']['css'] == 'error')
        {
            error = '<input type="hidden" id="error" name="error" value="'+encodeURIComponent(error['block_signinStatus']['value'])+'" />';
        }
        else
        {
            error = '';
        }

        $('container').insert({ after: '<form id="goSignupAndBack" action="/signup.php" method="post">'+
            '<input type="hidden" id="signinPage" name="signinPage" value="'+location.href+'" />'+error+'</form>' });
        (function() { $('goSignupAndBack').submit(); }).delay(0.02);
    }

    function yg_showLogin() {
        if (typeof redir_timer != 'undefined') {
            clearTimeout(redir_timer);
        }
        Effect.toggle('signinPart', 'blind', {
            afterFinish: function(){ Form.focusFirstElement('signinForm'); },
            duration: 0.1,
            from: 0,
            to: 0.5 });

    }

    function yg_redirectAfterSignup() {
        (function() { redirect('/'); }).delay(3);
        return false;
    }

    function signup(pageRedirection, callback) {
        var genderRadioElts = $$('input[name="block_signupGender"]');
        var genderValue = (genderRadioElts.first().checked ? 'M' : (genderRadioElts.last().checked ? 'F' : null));
        var error = '';

        if ($('block_signupLogin').value == '' || $('block_signupPassword').value == '') {
            error = 'Please enter a login and a password';
        }
        else if ($('block_signupEmail').value == '') {
            error = 'Please enter an email address';
        }
        else if ($('block_signupConfirmPassword').value == '') {
            error = 'Please confirm your password';
        }
        else if ($('block_signupPassword').value != $('block_signupConfirmPassword').value) {
            error = 'Passwords doesn\'t match';
        }
        else if ($('block_signupCountry').value == '0') {
            error = 'Please select your country';
        }
        else if (genderValue == null) {
            error = 'Please select your gender';
        }
        else if ($('block_signupBirthMonth').value == '0') {
            error = 'Please select your birth month';
        }
        else if ($('block_signupBirthDay').value == '0') {
            error = 'Please select your birth day';
        }
        else if ($('block_signupBirthYear').value == '0') {
            error = 'Please select your birth year';
        }

        if (error != '') {
            $('block_signupStatus').update(error).addOnlyClassName('error');
            return;
        }

        $('block_signupStatus').update('Signup in progress, please wait...').addOnlyClassName('status');

        var throbber = new yg_throbber();
        throbber.show('block_signup_throbber', null, false);

        signupRequest = new yRemote();
        signupRequest.onLoad = function(status, data)
        {
            if (status == 200 && data !== null)
            {
                if (throbber)
                    throbber.hide();
                // Got definitive response (success or failure)
                if (data.success)
                {
                    if (pageRedirection != '' && pageRedirection != null)
                    {
                        window.location = pageRedirection;
                        return;
                    }
                    if (typeof(callback) != 'undefined')
                    {
                        callback();
                    }
                }
            }
        };

        var data = {
            login: $('block_signupLogin').value,
            email: $('block_signupEmail').value,
            password: $('block_signupPassword').value,
            firstname: $('block_signupFirstName').value,
            lastname: $('block_signupLastName').value,
            country: $('block_signupCountry').value,
            gender: genderValue,
            birthday: $('block_signupBirthDay').value,
            birthmonth: $('block_signupBirthMonth').value,
            birthyear: $('block_signupBirthYear').value,
            newsletter: $('block_signupNewsletter').checked
        }

        if ($('block_signupReferer') != null)
            data['referer'] = $('block_signupReferer').value;

        signupRequest.post('/services/account/signup.php', data);
        return true;
    }

    function signin(pageRedirection, callback) {
        if ($('block_signinLogin').value == '' || $('block_signinPassword').value == '') {
            $('block_signinStatus').update('Please enter a login and a password').addOnlyClassName('error');
            return;
        }

        $('block_signinStatus').update('Login in progress, please wait...').addOnlyClassName('status');

        checkSigninRequest = new yRemote();

        //var throbber = new yg_throbber();
        //throbber.show('signinForm_throbber', 'signinForm_submit', true);

        checkSigninRequest.onLoad = function(status, data)
        {
            if (status == 200 && data !== null)
            {
                if (data.success)
                {
                    //throbber.hide();
                    if (data.redirect && data.redirect != null)
                    {
                        window.location = data.redirect;
                        return;
                    }
                    if (pageRedirection != '' && pageRedirection != null)
                    {
                        window.location = pageRedirection;
                        return;
                    }
                    if (typeof(callback) != 'undefined')
                    {
                        callback();
                    }
                }
            }
        }

        var rememberValue = !!($('block_signinRemember') && $('block_signinRemember').checked);

        var data = {
            login: $('block_signinLogin').value,
            password: $('block_signinPassword').value,
            remember: rememberValue
        }

        checkSigninRequest.post('/services/account/login.php', data);
    }

    function yg_signinBanner(form) {

        if (form.signinLogin.value == '' || form.signinPassword.value == '')
        {
            return false;
        }

        var checkSigninRequest = new yRemote();

        var throbber = new yg_throbber();
        throbber.show('signinForm_throbber', 'signinPart', false);

        checkSigninRequest.onLoad = function(status, data)
        {
            if (status == 200 && data !== null && data.success)
            {
                //if (throbber)
                //  throbber.hide();
                if (data.redirect && data.redirect != null)
                {
                    window.location = data.redirect;
                }
                else
                {
                    if (location.pathname.include('signup.php') || location.pathname.include('logout.php'))
                        setTimeout('window.location = \'/en/\'', 100);
                    else
                        setTimeout('window.location.reload(true)', 100);
                }
            }
            else
            {
                yg_goSignupAndBack(data.html);
            }
        }
        if (Prototype.Browser.WebKit) {
            var form = $('signinForm');
            form.action = '/services/account/loginSafari.php';
            form.method = 'post';
            form.submit();
        }
        else
        {
            var data = {
                login: form.signinLogin.value,
                password: form.signinPassword.value,
                remember: form.signinRemember.checked
            }

            checkSigninRequest.post('/services/account/login.php', data);
        }
    }

    function yg_signout() {
        signoutRequest = new yRemote();
        signoutRequest.onLoad = function(status, data)
        {
            if (status == 200 && data !== null && data.success)
            {
                setTimeout('window.location = \'\/en\/logout.php\'', 100);
            }
        }
        if (Prototype.Browser.WebKit) {
            $('container').insert({ after : '<form id="signoutForm" action="/services/account/logout.php" method="post">'+
                '<input type="hidden" name="signoutPage" value="/en/logout.php" />'+
                '<input type="hidden" name="safari" value="true" /></form>' });
            var form = $('signoutForm');
            form.submit();
        }
        else
        {
            signoutRequest.get('/services/account/logout.php');
        }
    }

    function recoverPassword(login) {
        if ($('block_passwordRecovery_login').value == '')
        {
            $('block_passwordRecoveryStatus').innerHTML = 'Please enter a login or an email address';
            return;
        }

        $('block_passwordRecoveryStatus').update('Your request is being processed, please wait...').addOnlyClassName('error');

        var args = {
            login: $('block_passwordRecovery_login').value
        }

        sendPostRequest('/services/account/recoverPassword.php', args);
    }

    function resendActivation(email) {
        if ($('block_resendActivation_email').value == '')
        {
            $('block_resendActivationStatus').update('Please enter an email address').addOnlyClassName('error');
            return;
        }

        $('block_resendActivationStatus').update('Your request is being processed, please wait...').addOnlyClassName('status');

        var args = {
            email: $('block_resendActivation_email').value
        }
        sendPostRequest('/services/account/resendActivation.php', args);
    }


//
// Language methods
//


    function yg_catchClickOnLanguage(e)
    {
        var element = e.element();
        if (!element.hasClassName('top_languageLink') && !element.hasClassName('currentFlag'))
            yg_closeLanguages();
    }

    function yg_toggleLanguages()
    {
        var elem = $('top_languagesList');

        if (!Object.isElement(elem))
            return;

        if (elem.visible())
            document.stopObserving('click', yg_catchClickOnLanguage);
        else
            document.observe('click', yg_catchClickOnLanguage);

        elem.toggle();
    }

    function yg_closeLanguages()
    {
        $('top_languagesList').hide();
        document.stopObserving('click', yg_catchClickOnLanguage);
    }

//
// Friends
//
    function yg_addToFriends(user)
    {
        var throbber = new yg_throbber();
        throbber.show('myfriends_friend_status_'+user, null, true);

        friendBlock = new yRemote();
        friendBlock.onLoad = function(status, data)
        {
            if (status == 200 && data !== null)
            {
                // Got definitive response (success or failure)
                if (data.success && data.block) {
                    if (throbber)
                        throbber.hide();
                }
            }
        };

        var args = {
            friend: user,
            action: 'add'
        }

        friendBlock.post('/services/friends/manageFriends.php', args);
        return true;
    }

    function yg_removeFromFriends(user, state, page)
    {
        var throbber = new yg_throbber();
        throbber.show('myfriends_friend_status_'+user, null, true);

        friendBlock = new yRemote();
        friendBlock.onLoad = function(status, data)
        {
            if (status == 200 && data !== null)
            {
                // Got definitive response (success or failure)
                if (data.success) {
                    if (throbber)
                        throbber.hide();
                    userDiv = 'myfriends_friend_'+user;
                    currentPage = page;
                    window.setTimeout("$(userDiv).hide(); checkIfElementExists('friends', currentPage); clearTimeout()", "2000");
                }
            }
        };

        var args = {
            friend: user,
            action: state
        }

        friendBlock.post('/services/friends/manageFriends.php', args);
        return true;
    }

    function yg_answerFriendRequest(user, answer, page)
    {
        var throbber = new yg_throbber();
        throbber.show('myfriends_friend_status_'+user, null, true);

        friendBlock = new yRemote();
        friendBlock.onLoad = function(status, data)
        {
            if (status == 200 && data !== null)
            {
                // Got definitive response (success or failure)
                if (data.success) {
                    if (throbber)
                        throbber.hide();
                    //userDiv = 'myfriends_friendRequest_'+user;
                    //spacerDiv = 'myfriends_friendRequest_'+user+'_spacer';
                    //currentPage = page;
                    //window.setTimeout("$(userDiv).hide(); $(spacerDiv).hide(); checkIfElementExists('friendRequests', currentPage); clearTimeout()", "2000");
                }
            }
        };

        var args = {
            friend: user,
            action: answer
        }

        friendBlock.post('/services/friends/manageFriends.php', args);
    }

//
// Messages
//
    function yg_removeMessage(form, id)
    {
        form.mymessages_remove.value = id;
        form.submit();
    }

    function yg_removeMessageList(form)
    {
        var checkedMessagesList = '';
        for (var i = 0; i < form.elements.length; i++)
        {
            if ((form.elements[i].type == 'checkbox') && (form.elements[i].checked))
            {
                checkedMessagesList += form.elements[i].value+',';
            }
        }
        form.mymessages_remove.value=checkedMessagesList;
    }

    yg_messagesChecked = false;
    function yg_checkMessages(form)
    {
        yg_messagesChecked = !yg_messagesChecked
        for (var i = 0; i < form.elements.length; i++)
        {
            if (form.elements[i].type == 'checkbox')
            {
                form.elements[i].checked = yg_messagesChecked;
            }
        }
    }

//
// Favorites
//

    function yg_favorite()
    {
        if ($('game_favorite'))
        {
            Effect.toggle('game_favorite', 'appear');
        }
    }

//
// Add to favorites
//
    function addToFavorites(gameCode)
    {
        var throbber = new yg_throbber();
        throbber.show('game_favorite', null, true);

        favoriteBlock = new yRemote();
        favoriteBlock.onLoad = function(status, data)
        {
            if (status == 200 && data !== null)
            {
                // Got definitive response (success or failure)
                if (data.success) {
                    if (throbber)
                        throbber.hide();
                }
            }
        };

        var args = {
            gameCode: gameCode,
            action: 'add'
        }

        favoriteBlock.post('/services/game/manageFavorites.php', args);
        return true;
    }

//
// Remove from favorites
//

    function removeFromFavorites(gameCode, page)
    {
        var throbber = new yg_throbber();
        throbber.show('myfavorites_favoriteGame_status_'+gameCode, null, true);

        favoriteBlock = new yRemote();
        favoriteBlock.onLoad = function(status, data)
        {
            if (status == 200 && data !== null)
            {
                // Got definitive response (success or failure)
                if (data.success) {
                    if (throbber)
                        throbber.hide();
                    gameDiv = 'myfavorites_favoriteGame_'+gameCode;
                    currentPage = page;
                    window.setTimeout("$(gameDiv).hide(); $(gameDiv+'_spacer').hide(); checkIfElementExists('favorites', currentPage); clearTimeout()", "1000");
                }
            }
        };

        var args = {
            gameCode: gameCode,
            action: 'remove'
        }

        favoriteBlock.post('/services/game/manageFavorites.php', args);
        return true;
    }

    function checkIfElementExists(type, page)
    {
        var selector = '';
        var exist = false;
        var redirection = '';

        switch(type)
        {
            case 'favorites':
                selector = 'tr.myfavorites_favoriteGame';
                redirection = 'myfavorites.php?page='+page;
                break;
            case 'friends':
                selector = 'div.myfriends_friend';
                redirection = 'myfriends.php?page='+page;
                break;
            case 'friendRequests':
                selector = 'tr.myfriends_friendRequest';
                redirection = 'myfriends.php?view=requests';
                break;
            case 'games':
                selector = 'tr.mygames_game';
                redirection = 'mygames.php?page='+page;
                break;
            case 'uploadedgames':
                selector = 'tr.mygames_game';
                redirection = 'myuploadedgames.php?page='+page;
                break;
            default:
                return false;
                break;
        }

        if (selector)
        {
            var elements = $$(selector);

            if (elements.length)
            {
                exist = elements.invoke('visible').any();
                if (!exist && redirection)
                    redirect(redirection);
                else
                    return false;
            }
            else
                return false;
        }
        else
            return false;
    }


//
// Show a div & change the sign before its title
//

    function yg_toggleDiv(elem)
    {
        var elem = $(elem);

        if (!Object.isElement(elem))
            return false;

        elem.toggle();

        var elemIcon = $(elem.id + 'Icon');

        if (!Object.isElement(elemIcon))
            return false;

        if (elemIcon.innerHTML == '-')
            elemIcon.update('+');
        else if (elemIcon.innerHTML == '+')
            elemIcon.update('-');
    }

//
// Send to a friend methods
//

    function showSendToAFriend() {
        if (!$('sendToAFriend').visible())
        {
            $('sendToAFriend_mailTo').value = '';
            $('sendToAFriend_mailBody').value = '';
            $('sendToAFriend_captcha').value = '';
            sendToAFriend_defaultMail();
            $('sendToAFriend_mailTo').observe('blur', sendToAFriend_defaultMail);
            $('sendToAFriend_mailTo').observe('focus', sendToAFriend_defaultMail);
            setTimeout('sendToAFriend_updateCaptcha()', 60);
        }
        else
        {
            $('sendToAFriend_mailTo').stopObserving('blur', sendToAFriend_defaultMail);
            $('sendToAFriend_mailTo').stopObserving('focus', sendToAFriend_defaultMail);
            //setTimeout("$('sendToAFriend_captchaImg').src = '/resources/generatingCaptcha.png'", 100);
        }
        Effect.toggle('sendToAFriend', 'appear');
        return false;
    }

    function sendToAFriend_updateCaptcha() {
        $('sendToAFriend_captchaImg').src = '/services/captcha/getCaptcha.php?seed=' + Math.floor(Math.random()*1000000000);
    }

    function sendToAFriend_defaultMail() {
        var elem = $('sendToAFriend_mailTo');

        if (!Object.isElement(elem))
            return;

        if (elem.value.blank())
            elem.setStyle({color: '#999', fontStyle: 'italic'}).setValue('john@yahoo.com, brittany@gmail.com');
        else if (elem.getValue() == 'john@yahoo.com, brittany@gmail.com')
            elem.setStyle({color: '#000', fontStyle: 'normal'}).setValue('');
    }

    function sendToAFriend(gameCode, redirect) {
        if ($('sendToAFriend_mailTo').value.match(/john@yahoo\.com.*/i))
        {
            $('sendToAFriend_status').update('Please insert other mail address than default.').addOnlyClassName('error');
            return false;
        }

        $('sendToAFriend_status').update('Sending mail...').addOnlyClassName('status');
        sendToAFriendRequest = new yRemote();

        var throbber = new yg_throbber();
        throbber.show('sendToAFriend_status', null, true);

        sendToAFriendRequest.onLoad = function(status, data) {
            if (status == 200 && data !== null) {
                // Got definitive response (success or failure)
                if (((!data.success) && (data.error == 'BAD_CAPTCHA')) || data.success) {
                    if (throbber)
                        throbber.hide();
                    //$('sendToAFriend_captchaImg').src = '/services/captcha/getCaptcha.php?seed=' + Math.floor(Math.random()*1000000000);
                    if(redirect == true)
                        window.location = 'game.php?game='+gameCode;
                }
            }
        };
        var data = {
            gameCode: gameCode,
            mailTo: $('sendToAFriend_mailTo').value,
            mailBody: $('sendToAFriend_mailBody').value,
            // empty value was added after desactivate captcha,
            // delete this when reactivate captcha
            captchaCode: ($('sendToAFriend_captcha').value || 'empty')
        }
        if ($('sendToAFriend_nickname') != null)
        {
            data['nickname'] = $('sendToAFriend_nickname').value;
            data['mailFrom'] = $('sendToAFriend_email').value;
        }

        sendToAFriendRequest.post('/services/email/sendToAFriend.php', data);
    }

//
// Invite friends
//

    function inviteFriends(form)
    {
        $('invitefriends_status').update('Sending mail...').addOnlyClassName('status');
        inviteFriendsRequest = new yRemote();

        var throbber = new yg_throbber();
        throbber.show('invitefriends_status', null, true);

        inviteFriendsRequest.onLoad = function(status, data) {
            if (status == 200 && data !== null)
            {
                // Got definitive response (success or failure)
                if (data.success)
                {
                    if (throbber)
                        throbber.hide();
                }
            }
        };

        var data = {
            mailTo: $('sendToAFriend_mailTo').value,
            mailBody: $('invitefriends_mailBody').value
        }

        if ($('invitefriends_nickname').value != undefined)
        {
            data['nickname'] = $('invitefriends_nickname').value;
            data['mailFrom'] = $('invitefriends_email').value;
        }
        inviteFriendsRequest.post('/services/email/inviteFriends.php', data);
    }

//
// Ratings methods
//

    function updateRate(rating, gameId, rate_count)
    {
        var throbber = new yg_throbber();
        throbber.show('block_Ratings', null, true);

        ratingBlock = new yRemote();
        ratingBlock.onLoad = function(status, data)
        {
            if (status == 200 && data !== null)
            {
                // Got definitive response (success or failure)
                if (data.success) {
                    if (throbber)
                        throbber.hide();
                }
            }
        };

        var args = {
            rate: rating,
            gameCode: gameId,
            rate_count: rate_count
        }

        ratingBlock.post('/services/rating/setRate.php', args);
        return true;
    }

//
// reportAsInappropriate object
//

    var yg_inpt = {
        flag: function ()
        {
            this.cancel();
            if ($('game_inappropriate_comment'))
            {
                $('game_inappropriate_comment').value = '';
                listInptTypeRequest = new yRemote();
                listInptTypeRequest.get('/services/inpt/getList.php');
                $('game_reportAsInptStatus').update();
            }
            return false;
        },
        cancel: function ()
        {
            Effect.toggle('game_reportAsInpt','appear');
        },
        send: function (gameCode, form)
        {
            var throbber = new yg_throbber();
            throbber.show('game_reportAsInptStatus', null, true);
            var type = form.game_inappropriate_select.selectedIndex;

            /* TODO: verify syntax for comment (quote, double quote, space, multiline, ...) */
            args = {
                game: gameCode,
                typeId: form.game_inappropriate_select.options[type].value,
                comment: form.game_inappropriate_comment.value
            }
            setInptRequest = new yRemote();
            setInptRequest.onLoad = function(status, data) {
                if (status == 200 && data !== null) {
                    // Got definitive response (success or failure)
                    if (data.success) {
                        if (throbber)
                            throbber.hide();
                        this.cancel();
                    }
                }
            }.bind(this);
            setInptRequest.post('/services/inpt/setInpt.php', args);
        }
    }

//
// Mark game as private / delete
//

function yg_changeGameStatus(gameCode, state, page) {
    currentPage = page;
    if (state == 'delete') {
        if (confirm("Are you sure you want to delete this game?\nThis operation cannot be undone.") == false) {
            return false;
        }
    }
    if ($('gameStatus_'+gameCode) == null)
    {
        if ($('game_createByAndDesc') == null)
        {
            var id = 'game_infos-'+gameCode;
        }
        else
        {
            var id = 'game_createByAndDesc';
        }

        $(id).insert({ after: '<p id="gameStatus_'+gameCode+'" class="gameStatus"></p>' });
    }

    var throbber = new yg_throbber();
    throbber.show('gameStatus_'+gameCode, null, true);

    var args = {
        game: gameCode,
        state: state
    }
    gameStateRequest = new yRemote();
    gameStateRequest.onLoad = function(status, data) {
        if (status == 200 && data !== null) {
            if (throbber)
                throbber.hide();
            if (state == 'delete')
            {
                code = gameCode;
                if(location.pathname.match(/mygames/))
                {
                    window.setTimeout("$('game_'+code).hide(); $('game_'+code+'_spacer').hide(); checkIfElementExists('games', currentPage); clearTimeout();", "2000");
                }
                else if(location.pathname.match(/myuploadedgames/))
                {
                    window.setTimeout("$('game_'+code).hide(); $('game_'+code+'_spacer').hide(); checkIfElementExists('uploadedgames', currentPage); clearTimeout();", "2000");
                }
            }
            else if (state == 'private') {
                $('gameStatusButton_'+gameCode).value = 'Mark as public';
                $('gamePublishSetting_'+gameCode).value = 'public';
                $('gamePublishSettingText_'+gameCode).update('Private');
            }
            else if (state == 'public') {
                $('gameStatusButton_'+gameCode).value = 'Mark as private';
                $('gamePublishSetting_'+gameCode).value = 'private';
                $('gamePublishSettingText_'+gameCode).update('Public');
            }
        }
    };
    gameStateRequest.post('/services/game/changeGameStatus.php', args);
}

///
/// getGameInfos
///

function yg_getGameInfos(gameCodes) {
    if (!gameCodes.length)
        return;

    sendPostRequest('/services/game/getGameInfos.php', { codes: gameCodes });
}

///
/// Highlight a game
///
function yg_setHighlightedGame(game)
{
    var throbber = new yg_throbber();
    throbber.show('gameStatus_'+game, null, true);

    gameHLRequest = new yRemote();
    gameHLRequest.onLoad = function(status, data) {
        if (status == 200 && data !== null) {
            if (data.success)
            {
                var games = $$('tr.mygames_gameHighlighted');
                for(var i=0; games[i]; i++)
                {
                    games[i].className = 'mygames_game';
                }
                if (element = $('game_'+game))
                    element.className = 'mygames_gameHighlighted';
            }
            if (throbber)
                throbber.hide();
        }
    };

    gameHLRequest.post('/services/game/setHighlightedGame.php', { game: game });
}

///
/// Copy to Clipboard
///
function yg_copyToClipboard(elt) {
    var urlSwf = '/resources/_clipboard.swf';
    var strMssgBoxId = 'notifyTextCopied';
    var eltNotify = null;
    if ((eltNotify = $(strMssgBoxId)) == null) {
        eltNotify = new Element('div', { id: strMssgBoxId }).update('Copied to clipboard').hide();
        document.body.appendChild(eltNotify);
    }
    elt.onblur = function (e) { Element.hide(eltNotify); return true; };
    var z = Element.cumulativeOffset(elt);
    var x = z[0];
    var y = z[1];
    Element.show(eltNotify);
    if (x > 100) {
        if (Prototype.Browser.IE)
            x += (elt.offsetWidth - 23);
        else
            x += (elt.offsetWidth + 3);
    }
    else
        x -= (eltNotify.offsetWidth + 2);
    eltNotify.setStyle({ left: x+'px', top: y + 'px' });
    var xEffect = Effect.Fade(eltNotify, {fps:75, from:1.9, to:0, duration:1, queue:"front"});
    window.status = 'Copied text to clipboard';
    var flashcopier = 'flashcopier';
    if (!$(flashcopier))
        document.body.appendChild(new Element('div', { id: flashcopier }));
    $(flashcopier).update();
    var flashFragment = '<embed src="#{1}" flashvars="clipboard=#{2}" width="0" height="0" type="application/x-shockwave-flash"></embed>';
    $(flashcopier).update(flashFragment.interpolate({ 1: urlSwf, 2: encodeURIComponent(elt.value) }));
    elt.select();
    return true;
}

///
/// Copy to Clipboard
///
function yg_notifyFieldUpdate(elt) {
    var strMssgBoxId = "notifyFieldUpdated";
    var eltNotify = null;
    if ((eltNotify = $(strMssgBoxId)) == null) {
        eltNotify = new Element('div', { id: strMssgBoxId }).update('Updated').hide();
        document.body.appendChild(eltNotify);
    }
    elt.onblur = function (e) { Element.hide(eltNotify); return true; };
    var z = Element.cumulativeOffset(elt);
    var x = z[0];
    var y = z[1];
    Element.show(eltNotify);
    if (x > 100) {
        if (Prototype.Browser.IE)
            x += (elt.offsetWidth - 23);
        else
            x += (elt.offsetWidth + 3);
    }
    else
        x -= (eltNotify.offsetWidth + 2);
    eltNotify.setStyle({ left: x+'px', top: y + 'px' });
    var xEffect = Effect.Fade(eltNotify, {fps:75, from:1.9, to:0, duration:1, queue:"front"});
    elt.select();
    return true;
}

//
// Profile swapping div
//

function yg_profileView(block)
{
    $$('#profile_content > div').invoke('hide');
    $$('#profile_content > div').invoke('removeClassName', 'selected');
    $('profile_'+block).addClassName('selected');
    $('profile_'+block).show();
    $$('td.profile_navBarMenu ul li.selected').invoke('removeClassName', 'selected');
    $$('td.profile_navBarMenu li[block="'+block+'"]').invoke('addClassName', 'selected');

    return true;
}


//
// Contacts
//

function yg_changeContactList(block)
{
    $$('#contactList_container div.selected').invoke('hide');
    $$('#contactList_container div.selected').invoke('removeClassName', 'selected');
    $('contactList_'+block).addClassName('selected');
    $('contactList_'+block).show();
    $$('#contactList_tabBar li.selected').invoke('removeClassName', 'selected');
    $$('a[block="'+block+'"]').first().up().addClassName('selected');

    return true;
}

function yg_getContactList(form, block, addContactsOnLoading)
{
    var type = $(form.type);

    if (!type.present() || !Object.isElement(elem = $('contactList_status_'+type.getValue())))
        return false;

    if ($(form.username).present() && $(form.pwd).present())
        elem.update().addOnlyClassName('status');
    else
    {
        elem.update('Please fill all the fields').addOnlyClassName('error');
        return false;

    }

    var throbber = new yg_throbber();
    throbber.show('contactList_throbber', 'contactList_'+block, false);

    contactListBlock = new yRemote();
    contactListBlock.onLoad = function(status, data)
    {
        if (status == 200 && data !== null)
        {
            if (throbber)
                throbber.hide();
        }
    };

    var args = {
        username: $F(form.username),
        pwd: $F(form.pwd),
        type: $F(form.type), // we can also use type.getValue(), because 'type' is already an extended node
        addContactsOnLoading: addContactsOnLoading
    }

    contactListBlock.post('/services/email/getContactList.php', args);
    return true;
}

function yg_selectContactFromCheckbox(type, id)
{
    if (type != null && id != null && Object.isElement(element = $('contactBox_'+type+'_'+id)))
        element.checked ? yg_addToRecipients(element.value) : yg_removeFromRecipients(element.value);
}

function yg_selectContact(type, id)
{
    if (type != null && id != null && Object.isElement(element = $('contactBox_'+type+'_'+id)))
    {
        element.checked ? yg_removeFromRecipients(element.value) : yg_addToRecipients(element.value);
        element.checked = !element.checked;
    }
}

function yg_selectAllContacts(block)
{
    var elem = $('contactList_contacts_'+block);

    if (!Object.isElement(elem))
        return false;

    $(elem).select('input.contactList_contact[type="checkbox"]').each(function(s) {
        if (!s.checked) {
            // Toggle checked status before use Form.Element.getValue()
            // because it returns 'null' if checkbox is not checked.
            s.checked = !s.checked;
            yg_addToRecipients(s.getValue());
        }
    });
}

function yg_deselectAllContacts(block)
{
    var elem = $('contactList_contacts_'+block);

    if (!Object.isElement(elem))
        return false;

    $(elem).select('input.contactList_contact[type="checkbox"]').each(function(s) {
        if (s.checked) {
            yg_removeFromRecipients(s.getValue());
            s.checked = !s.checked;
        }
    });
}

function yg_addToRecipients(email)
{
    if (!Object.isString(email) || email.blank())
        return false;

    var elem = $('sendToAFriend_mailTo');

    if (!Object.isElement(elem))
        return;

    var mails = elem.getValue();

    if (mails.include(email))
        return;

    mails = mails.split(/[,]+/g).invoke('strip').select(function(s) { return s.length; });
    mails.push(email);
    elem.setValue(mails.join(', '));
}

function yg_removeFromRecipients(email)
{
    var elem = $('sendToAFriend_mailTo');

    if (!Object.isElement(elem))
        return;

    var mails = elem.getValue();

    if (!mails.include(email))
        return;

    mails = mails.split(/[,]+/g).invoke('strip').without(email);
    elem.setValue(mails.join(', '));
}

function yg_closeContactManager(block)
{
    var throbber = new yg_throbber();
    throbber.show('contactList_throbber', 'contactList_'+block, false);

    contactListBlock = new yRemote();
    contactListBlock.onLoad = function(status, data)
    {
        if (status == 200 && data !== null)
        {
            if (data.success) {
                if (throbber)
                    throbber.hide();
            }
        }
    };

    contactListBlock.post('/services/email/getContactList.php', { type: block });
    return true;
}

function yg_displayHotGame(ids)
{
    if (typeof(ids) == 'object' && ids.length > 0)
    {
        var random = Math.floor(Math.random()*ids.length);
        if (element = $(ids[random]))
            element.show();
    }
}

function yg_enableFormElement(element)
{
    var formElt = $(element);

    if (!Object.isElement(formElt))
        return;

    if (formElt.disabled)
        formElt.setStyle({ 'backgroundColor': '' }).enable();
    else
        formElt.setStyle({ 'backgroundColor': '#DDD' }).disable();
}

//
// Throbber
//

var yg_throbber = function() {
    this.targetDiv = null;
    this.hiddenDiv = null;
    this.throbberDivId = null;
    this.src = '/resources/loader_small.gif';
    this.bigSrc = '/resources/loader_big.gif';
}

yg_throbber.prototype = {
    show: function(target, hidden, erase) {
        if ($(hidden) && $(target))
        {
            this.targetDiv = $(target);
            this.hiddenDiv = $(hidden);
            this.targetDiv.show();
            this.hiddenDiv.hide();
        }
        else if ($(target))
        {
            this.targetDiv = $(target);

            if (erase == true)
                $(this.targetDiv).update().removeClassName('notice').removeClassName('error');

            this.loaderDivId = target+'_throbber';
            var div = new Element('div', { id: this.loaderDivId }).addClassName('throbber');
            var img = new Element('img', { src: this.src }).addClassName('align-middle');
            div.insert(img);
            div.insert(' Please wait');
            this.targetDiv.insert(div);
        }
    },

    hide: function() {
        if ($(this.targetDiv) && $(this.hiddenDiv))
        {
            this.targetDiv.hide();
            this.hiddenDiv.show();
        }
        else if ($(this.loaderDivId))
        {
            $(this.loaderDivId).hide();
        }
    },

    requireBig: function() {
        this.changeSrc(this.bigSrc);
    },

    changeSrc: function(src) {
        this.src = src;
    }
}

//
// Search methods
//

RawSearchControl = function(results, moreResults) {
        this.query = '';
    this.results = $(results);
    this.moreResults = $(moreResults);
    this.gameCodes = [];

        this.activeSearcher = "web";
    this.searchers = [];

        var searcher = new GwebSearch();
    searcher.setUserDefinedLabel("Pictogames");
    searcher.setSiteRestriction("013283082891179843313:ilbvcb4onqy");
    searcher.setNoHtmlGeneration();
    searcher.setResultSetSize(GSearch.LARGE_RESULTSET);
    searcher.setSearchCompleteCallback(
        this,
        RawSearchControl.prototype.searchComplete,
        [searcher]
    );
    this.searchers["web"] = searcher;
}

RawSearchControl.prototype = {
    searchComplete: function(searcher) {
        this.clearResults();

        if (searcher.results && searcher.results.length > 0)
        {
            for (var i=0; i<searcher.results.length; i++)
            {
                var result = searcher.results[i];
                if (result.GsearchResultClass == 'GwebSearch')
                {
                    var args =  result.unescapedUrl.split(/[/]+/g);
                    var params = args[args.length-1].split(/[_]+/g);
                    if(this.gameCodes.indexOf(params[0]) == -1)
                        this.gameCodes.push(params[0]);
                }
            }
            var codes = this.gameCodes.join(',');
            yg_getGameInfos(codes);

            if (this.gameCodes.length == 0)
            {
                this.results.update('Sorry, no result found. <a href="/en/create/">Why not create a game instead?</a>');
            }
            else if (this.gameCodes.length == 8)
            {
                var langs = {
                    'fr_FR': 'fr',
                    'en_US': 'en',
                    'zh_CN': 'zh-CN',
                    'zh_TW': 'zh-TW'
                };

                var locale = 'en_US';
                var hl = langs[locale] || 'en';
                var url = 'http://www.google.com/search?hl=#{hl}&source=uds&cx=013283082891179843313:ilbvcb4onqy&q=#{q}'.interpolate({
                    hl: hl,
                    q: this.query
                });

                var linkTitle = 'See more results';
                var link = new Element('a', { href: url, title: linkTitle+' >>', target: '_blank'}).update(linkTitle+'&nbsp;&gt;&gt;');
                this.moreResults.update().insert(link);
            }
        }
        else if (searcher.results.length == 0)
        {
            this.results.update('Sorry, no result found. <a href="/en/create/">Why not create a game instead?</a>');
        }
    },

    clearResults: function() {
        this.results.update();
        this.moreResults.update();
        this.gameCodes = [];
    },

    runQuery: function(string) {
        this.query = string;
        this.searchers[this.activeSearcher].execute(string);
    }
}

/***********************************************************************/
/* Redirect function */

function redirect(url)
{
    window.location = url;
}
