/**
 * || PLUGIN.JS INFO ||
 * Overall use of jQuery in noConflictMode
 * Overall use of jQuery "live" plugin so ajax load's will be rebinded automatically
 *
 *
 **/

function refreshHighscore(  highscoreId ) {
    jQuery( '#highscorewrapper' ).html( '' );
    if( jQuery.user.currentuser > 0 ){
        if( highscoreId == "false" ){
            jQuery.component.highscore( ' ', '' );
        }else{
            jQuery.communicator.reloadHighscores();
        }
    }else{
        jQuery.component.highscore( ' ', '' );
    }
    
}

 /**
 jQuery.communicator - Flash Communicator plugin for Jaludo's speeleiland.nl
 * Written by Ronnie Visser (r.visser@vivens.com)
 * Date: 2010-05-06
 *
 * @author Ronnie Visser
 * @version 1.1
 *
 **/

jQuery.fn.extend({
    triggerCommunicator: function( gameID ) {
        return this.each(function() {
            jQuery.communicator.getMinimunTop10Score( this, gameID );
        });
    },
    gameCommunicator: function( gameID ) {
       return this.each(function() {
            jQuery.communicator.getMinimunTop10Score( this, gameID );
       });
    },
    showTop10Message: function(){
         return this.each(function() {
            jQuery.communicator.highscoreTop10Message( this );
         });
    }
});

jQuery.extend({
    communicator: {
        scoreLoaded: false,
        friendsLoaded: false,
        highscore : function( element ){
        },
        getMinimunTop10Score: function( element, gameID ){
            jQuery.communicator.gameid = gameID;
            jQuery.ajax({
                type: "GET",
                url: "/rpc.php?command=gettop10score&_format=xml&gameid=" + gameID,
                dataType: "xml",
                success: function( xml ) {
                    jQuery.communicator.top10score = jQuery( xml ).find( 'reply message' ).text();

                    jQuery.communicator.highscoreXML = xml;
                    jQuery.communicator.friendsinList();
                }
            });
        },
        friendsinList: function(){
            jQuery.ajax({
                type: "GET",
                url: "/rpc.php?command=friendinlist&_format=purexml&gameid=" + jQuery.communicator.gameid,
                dataType: "xml",
                success: function( xml ) {
                    jQuery.communicator.friendXML = xml;
                    jQuery.communicator.friendsAmount = jQuery( xml ).find( 'item total' ).text();
                }
            });
        },
        highscoreTop10Message: function(){
            jQuery( '#flashcommunicator' ).html( 'Om in de top 10 te komen heb je minimaal een score van <strong>' + jQuery.communicator.top10score + '</strong> nodig!' );
        },
        friendInListMessage: function( ){
           jQuery( '#flashcommunicator' ).html( '<strong>' + jQuery.communicator.friendsAmount + '</strong> van je vrienden hebben een highscore voor dit spel' );
        },
        reloadHighscores: function( ){
            jQuery.component.highscore();
        },
        emptyMessageContainer: function(){
            jQuery( '#flashcommunicator' ).fadeOut( 600, function(){
                jQuery( '#flashcommunicator' ).html( '' );
            });
        }
    }
});

/**
 * jQuery.Highscore - Highscore plugin for Jaludo's speeleiland.nl
 * Written by Ronnie Visser (r.visser@vivens.com)
 * Date: 2010-05-06
 *
 * @author Ronnie Visser
 * @version 1.1
 *
 **/

jQuery.fn.extend({
    initHighscore: function( elements, tabsText, gameHash, friendElement, userID, sDate ) {
        return this.each(function() {
            jQuery.highscore.init( this, elements, tabsText, gameHash, friendElement, userID, sDate );
        });
    }
});

jQuery.extend({
    highscore: {
        template : '/templates/site/block/highscores/highscores.tpl.php',
        templateData : "",
        limit: 20,
        filterByDate: false,
        init : function( element, targetElements, tabsText, gameHash, friendElement, userID, sDate ){
            usrid = userID;
            this.dateNOW = sDate;
            this.initialized = false;
            this.game = gameHash;
            this.object  = element;
            this.friendsElement = friendElement,
            elementsArray = targetElements.split( "," );
            tabsArray = tabsText.split( "," );
            this.attachDateEvent();
            //

            this.loadBaseTemplate();
        },
        createTabs : function( element, callbackFnk ){
            var tabs = "<ul>";
            for( var i = 0; i < elementsArray.length; i++ ){
                var state = elementsArray[ i ] == elementsArray[ 1 ] ? "state='open'" : "";
                var itemClass = elementsArray[ i ] == elementsArray[ 1 ] ? "item_active'" : "item_normal";

                if( elementsArray[ i ] == "achievements" || elementsArray[ i ] == "friendhighscores" )
                    tabs = tabs + "<li class='"+itemClass+"' rel='highscore' style='display:none;'><a href='#' rel='"+ elementsArray[ i ] +"' class='"+elementsArray[ i ]+"' " + state + ">" + tabsArray[ i ] + "</a></li>";
                else
                    tabs = tabs + "<li class='"+itemClass+"' rel='highscore'><a href='#' rel='"+ elementsArray[ i ] +"' class='"+elementsArray[ i ]+"' " + state + ">" + tabsArray[ i ] + "</a></li>";
            }

            tabs = tabs + "</ul>";
            jQuery( this.object ).find( '.topscore_menu' ).append( tabs );
            jQuery( this.object ).find( '.topscore_menu ul li[rel=highscore] a' ).live( 'click', function( e ){
                e.preventDefault();
                jQuery.highscore.filterByDate = false;
                if( jQuery( this ).attr( 'state' ) != 'open' ){
                    jQuery.highscore.toggleContainer( this );
                    var bLoadFriends = jQuery.highscore.friendsElement == jQuery( this ).attr( 'rel' ) ? true : false;
                    jQuery.highscore.loadData( this, bLoadFriends );
                    jQuery.highscore.removeActiveState();
                    jQuery( this ).attr( 'state', 'open' );
                    jQuery( this ).parent( 'li' ).removeClass( 'item_normal');
                    jQuery( this ).parent( 'li' ).addClass( 'item_active');
                }
            });

            if( typeof callbackFnk == 'function' ){
                callbackFnk.call( this );
            }
        },
        removeActiveState: function(){
            jQuery( this.object ).find( '.topscore_menu ul li a' ).attr( 'state', '' );
            jQuery( this.object ).find( '.topscore_menu ul li[rel=highscore]' ).removeClass( 'item_active');
            jQuery( this.object ).find( '.topscore_menu ul li[rel=highscore]' ).addClass( 'item_normal');
        },
        createHighscoreContainers : function( element ){
            for( var i = 0; i < elementsArray.length; i++ ){
                jQuery( '.topscore_menu' ).find( 'a[rel='+ elementsArray[ i ] +']' ).parent().after( '<li class="data" style="display:none;">\
                    <div class="dateselector right">\
                        <a href="#" rel="'+ elementsArray[ i ] +'" content="day"></a> | <a href="#" rel="'+ elementsArray[ i ] +'" content="month"></a> | <a href="#" rel="'+ elementsArray[ i ] +'" content="year"></a>\
                    </div><br class="clear"/>\
                    <div id="'+ elementsArray[ i ] +'"><ul></ul></div></li>' );
            }
        },
        toggleContainer : function( clickedElement ){

            var $containers = jQuery( 'li.data' );
            $containers.slideUp( 800 );


            jQuery( '#' + jQuery( clickedElement ).attr( 'rel' ) ).parent().slideDown( 800 );
        },
        loadBaseTemplate: function(){
            jQuery.get( this.template, {}, function( data ){
                jQuery.highscore.templateData = data;
                jQuery.highscore.createTabs( jQuery.highscore.object, function(){
                    this.createHighscoreContainers( this.object );
                    jQuery.highscore.loadData( jQuery( 'a[rel='+elementsArray[1]+']' ), false );
                    this.toggleContainer( jQuery( 'a[rel='+elementsArray[1]+']' ) );
                });
            });
        },
        loadData: function( clickedElement, bFriendsOnly ){

            jQuery.ajax({
                type: "GET",
                url: "/media/xml/highscores/" + this.game + "?q=" + ( Math.floor( Math.random() * 11 ) ),
                dataType: "xml",
                beforeSend: function(){
                    jQuery( clickedElement ).parents( '.highscorewrapper' ).addClass( 'ajaxprogress' );
                },
                error: function( XMLHttpRequest, textStatus, errorThrown ){
                    jQuery( '#' + jQuery( clickedElement ).attr( 'rel' ) ).hide();
                    if( jQuery( clickedElement ).attr( 'rel' ) == "achievements" ){
                       // if( jQuery( '#noachievements' ).length == 0 )
                            jQuery( '#' + jQuery( clickedElement ).attr( 'rel' ) ).after( '<div style="padding:5px" id="noachievements">Il n&#039;y a pas de résultat pour le moment.</div>' );
                    }else{
                        jQuery( 'div[rel=nohighscores]' ).html( '' );
                        jQuery( '#' + jQuery( clickedElement ).attr( 'rel' ) ).after( '<div style="padding:5px" rel="nohighscores">Il n&#039;y a pas de highscore pour ce jeu en ce moment.</div>' );
                    }
                    jQuery( '#highscore' ).parents().removeClass( 'ajaxprogress' );
                },
                success: function( xml ) {
                    jQuery( '#' + jQuery( clickedElement ).attr( 'rel' ) ).html( '<ul></ul>' );

                    if( jQuery.highscore.initialized == false ){
                        jQuery.highscore.myTopScore( xml );
                        jQuery.highscore.initialized = true;
                    }

                    if( bFriendsOnly ){
                        jQuery.highscore.matchWithFriends( xml, clickedElement );
                    }
                    else if( jQuery( clickedElement ).attr( 'rel' ) == "achievements" ){
                        jQuery.highscore.loadAchievements( clickedElement );
                    }
                    else if( jQuery.highscore.filterByDate == true ){
                        jQuery.highscore.dateFilter( clickedElement, xml, jQuery.highscore.filterByDateType );
                    }
                    else {
                        var i = 1;


                        jQuery( xml ).find( 'score' ).each( function(){
                            if( i <= jQuery.highscore.limit ){
                                var MsgValues = {
                                    usrid       : jQuery( this ).find( 'userid' ).text(),
                                    username    : jQuery( this ).find( 'username' ).text(),
                                    standing    : jQuery( this ).attr( 'standing' ),
                                    score       : jQuery( this ).find( 'highscore' ).text(),
                                    datediff    : getTimeDiff( jQuery( this ).find( 'timestamp' ).text() ),
                                    counter     : i,
                                    topscore    : i == 1 ? '<img src="/images/topscore_medaille.jpg"/>' : '&nbsp;',
                                    cssclass    : i == 1 ? 'first' : '',
                                    cssusername : i == 1 ? 'username' : 'otherusernames'
                                };

                                jQuery.highscore.templateDefaultData = jQuery.highscore.templateData;
                                for ( var key in MsgValues ) {
                                    jQuery.highscore.templateDefaultData = jQuery.highscore.templateDefaultData.replace( new RegExp("##" + key + "##", "gi"), MsgValues[key] );
                                }

                                jQuery( '#' + jQuery( clickedElement ).attr( 'rel' ) ).find( 'ul' ).append( jQuery.highscore.templateDefaultData );
                                i++;
                            }
                        });
                    }

                    jQuery( clickedElement ).parents( '.highscorewrapper' ).removeClass( 'ajaxprogress' );
                }
            });
        },
        loadAchievements: function( event ){
            jQuery( event ).parents( 'li' ).next( '.data' ).html( '<div style="margin: 10px 0 5px 5px;">Il n&#039;y a pas de résultat pour le moment.</div>' );
            jQuery( event ).parents( '.highscorewrapper' ).removeClass( 'ajaxprogress' );
        },
        matchWithFriends: function( scoreXML, clickedElement ){
            jQuery.ajax({
                type: "GET",
                url: "/rpc.php?command=loadfriends&_format=purexml",
                dataType: "xml",
                success: function( xml ) {
                    var i = 1;
                    var iFound = 0;

                    jQuery( xml ).find( 'item' ).each( function(){
                        var outerList = this;
                        jQuery( scoreXML ).find( 'score' ).each( function(){
                            if( i <= jQuery.highscore.limit ){
                                if( jQuery( outerList ).find( 'friendusrid' ).text() == jQuery( this ).find( 'userid' ).text() ){
                                    var MsgValues = {
                                        usrid       : jQuery( this ).find( 'userid' ).text(),
                                        username    : jQuery( this ).find( 'username' ).text(),
                                        standing    : jQuery( this ).attr( 'standing' ),
                                        score       : jQuery( this ).find( 'highscore' ).text(),
                                        datediff    : getTimeDiff( jQuery( this ).find( 'timestamp' ).text() ),
                                        counter     : i,
                                        topscore    : i == 1 ? '<img src="/images/topscore_medaille.jpg"/>' : '&nbsp;',
                                        cssclass    : i == 1 ? 'first' : '',
                                        cssusername : i == 1 ? 'username' : ''
                                    };

                                    jQuery.highscore.templateDefaultData = jQuery.highscore.templateData;
                                    for ( var key in MsgValues ) {
                                        jQuery.highscore.templateDefaultData = jQuery.highscore.templateDefaultData.replace( new RegExp("##" + key + "##", "gi"), MsgValues[key] );
                                    }

                                    jQuery( '#' + jQuery( clickedElement ).attr( 'rel' ) ).find( 'ul' ).append( jQuery.highscore.templateDefaultData );
                                    i++;
                                    iFound++;
                                }
                            }
                        });
                    });

                    if( iFound == 0 )
                        jQuery( '#' + jQuery( clickedElement ).attr( 'rel' ) ).append( 'Tu n&#039;es pas connecté ou tu n&#039;as aucun ami avec des highscores pour ce jeu.' );

                    jQuery( clickedElement ).parents( '.highscorewrapper' ).removeClass( 'ajaxprogress' );

                }
            });
        },
        attachDateEvent: function(){
             jQuery( '.topscore_menu ul li.data' ).find( 'a' ).live( 'click', function( e ){
                e.preventDefault();
                if( jQuery( this ).attr( 'state' ) != 'openperiod' ){
                    jQuery.highscore.filterByDate = true;
                    jQuery.highscore.filterByDateType = jQuery( this ).attr( 'content' );
                    jQuery.highscore.loadData( jQuery( this ), false );
                    jQuery.highscore.removeActiveState();
                    jQuery( this ).attr( 'state', 'openperiod' );
                }
             });
        },
        dateFilter: function( element, xml, type ){
            if( typeof( jQuery( element ).attr( 'content' ) ) != "undefined" ) {
                var currentTime = new Date();
                var i = 1;
                jQuery( xml ).find( 'score' ).each( function(){
                    var MsgValues = {
                        usrid       : jQuery( this ).find( 'userid' ).text(),
                        username    : jQuery( this ).find( 'username' ).text(),
                        standing    : jQuery( this ).attr( 'standing' ),
                        score       : jQuery( this ).find( 'highscore' ).text(),
                        date        : jQuery( this ).find( 'timestamp' ).text(),
                        datediff    : getTimeDiff( jQuery( this ).find( 'timestamp' ).text() ),
                        counter     : i,
                        topscore    : i == 1 ? '<img src="/images/topscore_medaille.jpg"/>' : '&nbsp;',
                        cssclass    : i == 1 ? 'first' : '',
                        cssusername : i == 1 ? 'username' : ''
                    };

                    jQuery.highscore.templateDefaultData = jQuery.highscore.templateData;

                    var bAddSeconds = false;
                    var hour = MsgValues.datediff.split( " " );

                    if( type == "day" && jQuery.highscore.dateNOW == MsgValues.date.substr( 0, 10 ) ){
                        for ( var key in MsgValues ) {
                            jQuery.highscore.templateDefaultData = jQuery.highscore.templateDefaultData.replace( new RegExp("##" + key + "##", "gi"), MsgValues[key] );
                        }

                        jQuery( '#' + jQuery( element ).attr( 'rel' ) ).find( 'ul' ).append( jQuery.highscore.templateDefaultData );
                        i++;
                    }
                    else if( type == "month" && jQuery.highscore.dateNOW.substr( 0, 6 ) == MsgValues.date.substr( 0, 6 ) ){
                        for ( key in MsgValues ) {
                            jQuery.highscore.templateDefaultData = jQuery.highscore.templateDefaultData.replace( new RegExp("##" + key + "##", "gi"), MsgValues[key] );
                        }

                        jQuery( '#' + jQuery( element ).attr( 'rel' ) ).find( 'ul' ).append( jQuery.highscore.templateDefaultData );
                        i++;
                    }
                    else if( type == "year" && jQuery.highscore.dateNOW.substr( 0, 4 ) == MsgValues.date.substr( 0, 4 ) ){
                        for ( key in MsgValues ) {
                            jQuery.highscore.templateDefaultData = jQuery.highscore.templateDefaultData.replace( new RegExp("##" + key + "##", "gi"), MsgValues[key] );
                        }

                        jQuery( '#' + jQuery( element ).attr( 'rel' ) ).find( 'ul' ).append( jQuery.highscore.templateDefaultData );
                        i++;
                    }
                });

                if( i == 1 )
                    jQuery( '#' + jQuery( element ).attr( 'rel' ) ).find( 'ul' ).append( 'Il n&#039;y a pas de highscore pour ce jeu en ce moment.' );

                jQuery( element ).parents( '.highscorewrapper' ).removeClass( 'ajaxprogress' );
            }
        },
        myTopScore: function( xml ){
            var bFound = false;

            var myScoreHTML = jQuery( '#myscore' ).html();

            jQuery( xml ).find( 'score' ).each( function(){
                if( jQuery( this ).find( 'userid' ).text() == usrid && !bFound ){
                    var MsgValues = {
                        usrid       : jQuery( this ).find( 'userid' ).text(),
                        standing    : jQuery( this ).attr( 'standing' ),
                        topscore    : jQuery( this ).find( 'highscore' ).text()
                    };

                    for ( var key in MsgValues ) {
                        myScoreHTML = myScoreHTML.replace( new RegExp("##" + key + "##", "gi"), MsgValues[key] );
                    }

                    bFound = true;
                }
            });

            if( !bFound ){
                var MsgValues = {
                    usrid       : jQuery.highscore.userid,
                    standing    : "geen",
                    topscore    : 0
                };
            }

            for ( var key in MsgValues ) {
                myScoreHTML = myScoreHTML.replace( new RegExp("##" + key + "##", "gi"), MsgValues[key] );
            }

            jQuery( '#myscore' ).slideDown( 900 );
            jQuery( '#myscore' ).html( myScoreHTML );
        },
        createHighscoreOverview: function( batchID, fileType ){
             var file = batchID + hex_md5( batchID ) + fileType;
             jQuery.ajax({
                type: "GET",
                url: "/media/xml/highscores/" + file + "?q=" + ( Math.floor( Math.random() * 11 ) ),
                dataType: "xml",
                beforeSend: function(){
                    jQuery( 'div[rel=data-'+batchID+']' ).addClass( 'ajaxprogress' );
                },
                error: function( XMLHttpRequest, textStatus, errorThrown ){

                },
                success: function( xml ) {
                    var i=1;
                    jQuery( xml ).find( 'score' ).each( function(){
                        if( i <= 5 ){
                            var usrid = jQuery( this ).find( 'username' ).text();
                            jQuery( 'div[rel=data-'+batchID+']' ).append( '<div class="highscore_games_list"><img src="/media/image/avatar/'+( usrid % 16 )+'/small.jpg" onerror="this.src=\'images/highscores_avatar.jpg\';" alt="" style="position: absolute; height: 68px; width: 45px;">\
                                <strong class="highscore_games_list_name">'+ i +'. '+ jQuery( this ).find( 'username' ).text() +'</strong>\
                                <strong class="highscore_games_list_score">'+ ( i == 1 ? '<img src="images/medaille.jpg" alt="" />' : '' )+' Score: '+ jQuery( this ).find( 'highscore' ).text() +'</strong>\
                                <strong class="highscore_games_list_time">'+ getTimeDiff( jQuery( this ).find( 'timestamp' ).text() ) +'</strong></div>' );
                        }
                        i++;
                    });

                    jQuery( 'div[rel=data-'+batchID+']' ).removeClass( 'ajaxprogress' );
                }
             });
        }
    }
});

/**
 * jQuery.gameMessages - Game message plugin for Jaludo's speeleiland.nl
 * Written by Ronnie Visser (r.visser@vivens.com)
 * Date: 2010-04-16
 *
 * @author Ronnie Visser
 * @version 1.4
 *
 **/

jQuery.fn.extend({
    initMessageLoad: function( xmlMessage, xmlWalkthrough, gameID ) {
        return this.each(function() {
            jQuery.gameMessages.init( xmlMessage, xmlWalkthrough, gameID );
        });
    },
    reloadMessages: function( file, container ){
        //return this.each( function() {
         //   alert('dfgy');
            jQuery.gameMessages.reloadMessages( file, container );
        //});
    }
});

jQuery.extend({
    gameMessages: {
        template: '',
        init:function( xmlMessage, xmlWalkthrough, gameID ){
            this.currentGameID = gameID;
            this.setClickEvent( xmlMessage, xmlWalkthrough );
            this.loadTemplateData();

            jQuery.gameMessages.loadComponentData( xmlWalkthrough, '#gamewalkthroughwrapper' );
            jQuery.gameMessages.loadComponentData( xmlMessage, '#gamereactionswrapper' );

            jQuery( document ).stopTime();
            jQuery(document).everyTime(60000, "gamemessages", function() {
                if( jQuery( 'input[name=reactionsloaded]' ).val() == "5" )
                    jQuery.gameMessages.loadComponentData( xmlMessage, '#gamereactionswrapper' );
                else
                    jQuery.gameMessages.queryMore( 'reactions', true );

                if( jQuery( 'input[name=walkthroughloaded]' ).val() == "5" )
                    jQuery.gameMessages.loadComponentData( xmlWalkthrough, '#gamewalkthroughwrapper' );
                else
                    jQuery.gameMessages.queryMore( 'walkthrough', true );
            }, 0 );

            jQuery( 'input[name=reactionsloaded]' ).val( 5 );
            jQuery( 'input[name=walkthroughloaded]' ).val( 5 );
        },
        reloadMessages: function( file, container ){
            jQuery( '#walkthroughmessage' ).val( '' );
            jQuery( '#reactionmessage' ).val( '' );

            jQuery( '#feedbackstoremessage' ).text( '' );
            jQuery( '#feedbackstoremessage' ).removeClass( 'info' );
            jQuery( '#feedbackstoremessage' ).hide();
            jQuery( '#feedbackstorewalkthrough' ).html( '' );
            jQuery( '#feedbackstorewalkthrough' ).removeClass( 'info' );
            jQuery( '#feedbackstorewalkthrough' ).hide();

            this.loadComponentData( file, container );
        },
        setClickEvent: function( xmlMessage, xmlWalkthrough ){
            jQuery.gameMessages.activeType = '#gamereaction';
            jQuery( '#gamepage_reactions_hdr' ).live( 'click', function( e ){
                e.preventDefault();
                jQuery( '#gamewalkthrough' ).hide();
                jQuery( '#gamereaction' ).show();
                jQuery.gameMessages.activeType = '#gamereaction';

                jQuery( this ).css( 'color', '#ffffff' );
                jQuery( '#gamepage_walkthroughs_hdr' ).css( 'color', '#A09DA4' );
            });

            jQuery( '#gamepage_walkthroughs_hdr' ).live( 'click', function( e ){
                e.preventDefault();
                jQuery( '#gamewalkthrough' ).show();
                jQuery( '#gamereaction' ).hide();

                jQuery.gameMessages.activeType = '#gamewalkthrough';
                jQuery( this ).css( 'color', '#ffffff' );
                jQuery( '#gamepage_reactions_hdr' ).css( 'color', '#A09DA4' );
            });

            jQuery( '.gamepage_view_more_reactions_button' ).live( 'click', function( e ){
                e.preventDefault();
                jQuery.gameMessages.queryMore( jQuery( this ).attr( 'rel' ), false );
            });

            jQuery( 'a[action=sendappreciation]' ).live( 'click', function( e ){
                e.preventDefault();
                var aData = jQuery( this ).attr( 'rel' ).split( "-" );
                var eParent = jQuery( this ).parents( '.gamepage_reactions' );
                jQuery.gameMessages.sendAppreciation( aData[ 0 ], aData[ 1 ], eParent );
            });

            jQuery( 'a[rel^=reply-]' ).live( 'click', function( e ){
                e.preventDefault();
                var aData = jQuery( this ).attr( 'rel' ).split( "-" );
                jQuery.gameMessages.reply( aData[ 1 ] );
            });
        },
        setAppriciationEvent: function(){
            jQuery( 'a[action=sendappreciation]' ).live( 'click', function( e ){
                e.preventDefault();
                var aData = jQuery( this ).attr( 'rel' ).split( "-" );
                var eParent = jQuery( this ).parents( '.gamepage_reactions' );
                jQuery.gameMessages.sendAppreciation( aData[ 0 ], aData[ 1 ], eParent );
            });
        },
        loadComponentData: function( file, container ){
            jQuery.ajax({
                type: "GET",
                url: "/media/xml" + file + "?q="+( Math.floor( Math.random() * 11 ) ),
                dataType: "xml",
                success: function(xml) {
                    var i = 1;
                    var sTmp = '';
                    jQuery(xml).find('message').each(function(){
                        var MsgValues = {
                            msgid       : jQuery( this ).find( 'msgid' ).text(),
                            username    : jQuery( this ).find( 'username' ).text(),
                            content     : jQuery( this ).find( 'content' ).text(),
                            positive    : jQuery( this ).find( 'positive' ).text(),
                            negative    : jQuery( this ).find( 'negative' ).text(),
                            timestamp   : jQuery( this ).find( 'timestamp' ).text(),
                            sDateDiff   : getTimeDiff( jQuery( this ).find( 'timestamp' ).text() ),
                            gameurl     : jQuery( this ).find( 'gameurl' ).text(),
                            owner       : ( jQuery.user.currentuser == jQuery( this ).find( 'usrid' ).text() ? "display:none;" : "" ),
                            counter     : i,
                            comm        : '',
                            avatar      : '/media/avatar/userdata' + ( jQuery( this ).find( 'usrid' ).text() % 16 ) + '/'+ jQuery( this ).find( 'usrid' ).text() +'/medium.jpg?q='+ ( Math.floor( Math.random() * 11 ) )
                        };
                        var sTemplate = jQuery.gameMessages.template;
                        for (var key in MsgValues) {
                            sTemplate = sTemplate.replace( new RegExp("##" + key + "##", "g"), MsgValues[key] );
                        }

                        sTmp = sTmp + sTemplate;

                        i = i + 1;
                    });

                    jQuery( container ).html( sTmp );
                }
            });
        },
        loadTemplateData: function( callBackFn ){
            jQuery.get(
                '/templates/site/block/reaction.tpl.php',
                {},
                function (data) {
                    jQuery.gameMessages.template = data;
                    if( typeof callBackFn == 'function' ){
                        callBackFn.call( this );
                    }
                }
            );
        },
        loadProfileTemplateData: function( callBackFn ){
            jQuery.get(
                '/templates/site/block/profilegamereaction.tpl.php',
                {},
                function (data) {
                    jQuery.gameMessages.template = data;
                    if( typeof callBackFn == 'function' ){
                        callBackFn.call( this );
                    }
                }
            );
        },
        queryMore: function( display, interval ){
            displayID = display == "reactions" ? 1 : 2;
            var start = jQuery( 'input[name='+display+'loaded]' ).val();
            var queryString = interval ? "&type="+displayID+"&start=0&limit="+ start : "&type="+displayID+"&start="+ start;

            jQuery.ajax({
                type: "GET",
                url: "/rpc.php?command=loadnextmessages&_format=purexml&gameid="+ jQuery.gameMessages.currentGameID + queryString,
                dataType: "xml",
                beforeSend: function(){
                    jQuery( '#' +display+ '-load-indicator' ).show();
                },
                error: function( XMLHttpRequest, textStatus, errorThrown ){
                    jQuery( '#' +display+ '-load-indicator' ).fadeOut( 500 );
                },
                success: function( xml ) {
                    var i = 1;
                    var sTmp = '';
                    jQuery(xml).find('item').each(function(){
                        var MsgValues = {
                            msgid       : jQuery( this ).find( 'msgid' ).text(),
                            username    : jQuery( this ).find( 'username' ).text(),
                            content     : jQuery( this ).find( 'content' ).text(),
                            positive    : jQuery( this ).find( 'positive' ).text(),
                            negative    : jQuery( this ).find( 'negative' ).text(),
                            timestamp   : jQuery( this ).find( 'timestamp' ).text(),
                            owner       : ( jQuery.user.currentuser == jQuery( this ).find( 'usrid' ).text() ? "display:none;" : "" ),
                            sDateDiff   : getTimeDiff( jQuery( this ).find( 'timestamp' ).text() ),
                            gameurl     : jQuery( this ).find( 'gameurl' ).text(),
                            counter     : i,
                            comm        : '',
                            avatar      : '/media/avatar/images/' + ( jQuery( this ).find( 'usrid' ).text() % 16 ) + '/small.jpg'
                        };

                        var sTemplate = jQuery.gameMessages.template;
                        for (var key in MsgValues) {
                            sTemplate = sTemplate.replace( new RegExp("##" + key + "##", "g"), MsgValues[key] );
                        }

                        sTmp = sTmp + sTemplate;

                        i = i + 1;
                    });

                    if( !interval ){
                        jQuery( '#game'+ display +'wrapper' ).append( sTmp );
                        current = jQuery( 'input[name='+ display +'loaded]' ).val();
                        var next = ( Number( current ) + 5 );
                        jQuery( 'input[name='+ display +'loaded]' ).val( next );
                    }
                    else
                        jQuery( '#game'+ display +'wrapper' ).html( sTmp );

                    jQuery( '#' +display+ '-load-indicator' ).fadeOut( 500 );
                }
            });
        },
        profileReactions: function( command, bInit, callbackFN ){
            jQuery( 'input[name='+command+'loaded]' ).val( '1' );
            if( bInit )
                this.setAppriciationEvent();

            this.loadTemplateData( this.profileMessageLoader( command, true, callbackFN ) );

            jQuery( '#'+command ).live( 'click', function(e){
                e.preventDefault();
                jQuery.gameMessages.profileMessageLoader( command, false, callbackFN );
            });
        },
        profileMessageLoader: function( command, bStart, callBackFN ){
            var start = jQuery( 'input[name='+command+'loaded]' ).val();
            jQuery.ajax({
                type: "GET",
                url: "/rpc.php?command="+command+"&_format=purexml&default="+bStart+"&start="+ start+ "&q=" + ( Math.floor( Math.random() * 11 ) ),
                dataType: "xml",
                beforeSend: function(){
                    jQuery( '#' +command+ '-load-indicator' ).show();
                },
                error: function( XMLHttpRequest, textStatus, errorThrown ){
                    jQuery( '#' +command+ '-load-indicator' ).fadeOut( 500 );
                },
                success: function( xml ) {
                    var i = 1;
                    var sTmp = '';
                    jQuery(xml).find('item').each(function(){

                        var MsgValues = {
                            msgid       : jQuery( this ).find( 'msgid' ).text(),
                            username    : jQuery( this ).find( 'username' ).text(),
                            content     : jQuery( this ).find( 'content' ).text(),
                            positive    : jQuery( this ).find( 'positive' ).text(),
                            negative    : jQuery( this ).find( 'negative' ).text(),
                            timestamp   : jQuery( this ).find( 'timestamp' ).text(),
                            sDateDiff   : getTimeDiff( jQuery( this ).find( 'timestamp' ).text() ),
                            owner       : ( jQuery.user.currentuser == jQuery( this ).find( 'usrid' ).text() ? "display:none;" : "" ),
                            gameurl     : jQuery( this ).find( 'gameurl' ).text(),
                            gametitle   : jQuery( this ).find( 'gametitle' ).text(),
                            counter     : i,
                            comm        : command,
                            avatar      : '/media/avatar/images/' + ( jQuery( this ).find( 'usrid' ).text() % 16 ) + '/small.jpg'
                        };

                        var sTemplate = jQuery.gameMessages.template;
                        for (var key in MsgValues) {
                            sTemplate = sTemplate.replace( new RegExp("##" + key + "##", "g"), MsgValues[key] );
                        }

                        sTmp = sTmp + sTemplate;
                        if( typeof callBackFN == 'function' ){
                            callBackFN.call( this );
                        }

                        i = i + 1;
                    });

                    if( bStart ){
                        jQuery( 'input[name='+ command +'loaded]' ).val( '2' );
                    }else{

                        current = jQuery( 'input[name='+ command +'loaded]' ).val();
                        var next = ( Number( current ) + 5 );
                        jQuery( 'input[name='+ command +'loaded]' ).val( next );
                    }

                    jQuery( '#game'+ command +'wrapper' ).append( sTmp );
                    jQuery( '#' +command+ '-load-indicator' ).fadeOut( 500 );
                }
            });
        },
        sendAppreciation: function( msgid, dir, eParent ) {
            jQuery.ajax({
                type: "POST",
                url: "/rpc.php",
                dataType: "xml",
                data: {
                    'command'   : 'sendappreciation',
                    '_format'   : 'xml',
                    'msgid'     : msgid,
                    'dir'       : dir,
                    'type'      : jQuery( this.activeType ).find( 'input[name=type]' ).val()
                },
                success: function( xml ) {
                    if( jQuery(xml).find('reply').attr( "status" ) != "ERROR" ){
                        var updateElement = jQuery( eParent ).find( 'a[rel=score-'+dir+']' );
                        var currentScore = jQuery( updateElement ).text();
                        jQuery( updateElement ).text( Math.floor( parseInt( currentScore ) + 1 ) );
                        jQuery( eParent ).find( 'div[rel=appriciationfeedback]' ).addClass( 'feedback info' );
                        jQuery( eParent ).find( 'div[rel=appriciationfeedback]' ).html( 'Ton vote a été enregistré.' );
                        jQuery.gameMessages.showMessage( eParent );
                    }
                }
            });
        },
        showMessage: function( eParent ){
            jQuery( eParent ).find( 'div[rel=appriciationfeedback]' ).fadeOut( 5000 )
        },
        reply: function( username ) {
            jQuery('#walkthroughmessage').val("@"+username+" ");
            jQuery('#walkthroughmessage').focus();
            jQuery('#reactionmessage').val("@"+username+" ");
            jQuery('#reactionmessage').focus();
        },
        loadVotingXML: function( sXMLPath ){
            this.voteXML;
            jQuery.ajax({
                type: "GET",
                url: "/media/xml/voting/" + sXMLPath + "?q="+( Math.floor( Math.random() * 11 ) ),
                dataType: "xml",
                success: function( xml ) {
                    jQuery( xml ).find('game').each(function(){
                        var xmlBatchID = jQuery( this ).find( 'batchid' ).text();
                        var nScore = jQuery( this ).find( 'batchid' ).next().text();
                        jQuery( 'span[id='+xmlBatchID+'-average]' ).html( nScore );
                    });
                }
            });
        }
    }
});

/**
 * jQuery.User - User plugin for Jaludo's speeleiland.nl
 * Written by Ronnie Visser (r.visser@vivens.com)
 * Date: 2010-05-16
 *
 * @author Ronnie Visser
 * @version 1.0
 *
 **/
jQuery.fn.extend({
    check: function() {
        return this.each(function() {
            jQuery.user.init( this );
        });
    },
    completeComponents: function(){
        return this.each(function() {
            jQuery.user.finishComponents( this );
        });
    },
    myGames: function(){
        return this.each( function(){
            jQuery.user.initMyGames( this );
        });
    }
});

jQuery.extend({
    user: {
        init : function( element ){
            var displayType = "";
            if( typeof( loadType ) == "undefined" )
                displayType = "default";
            else
                displayType = "gamepage";

            jQuery.ajax({
                type: "GET",
                url: "/rpc.php?command=checklogin&_format=xml&q=" + ( Math.floor( Math.random() * 11 ) ),
                dataType: "xml",
                error: function( XMLHttpRequest, textStatus, errorThrown ){
                    jQuery( element ).load( "/templates/site/block/usernotloggedin.tpl.php" );
                },
                success: function( xml ) {

                    jQuery( xml ).find( 'reply' ).each( function(){
                       if( jQuery( this ).find( 'content' ) ){
                           jQuery.user.currentuser = jQuery( this ).find( 'message' ).text();
                           jQuery( element ).html( jQuery( this ).find( 'content' ).text() );
                           jQuery.component.init( displayType, jQuery( this ).find( 'message' ).text() );
                       }
                    });
                }
            });

            this.toggleGamesBlock();
        },
        setBirthDate: function(){
            var birthDate = jQuery( '#birthday').val();
            var birthMonth = jQuery( '#birthmonth').val().length == "1" ? "0"+jQuery( '#birthmonth').val() : jQuery( '#birthmonth').val();
            var birthYear = jQuery( '#birthyear').val();
            jQuery( '#linkedPicker' ).val( birthDate +'-'+ birthMonth +'-'+ birthYear );
        },
        hasPM: function( nUserId ){
            if( nUserId == "" )
                nUserId = jQuery.user.currentuser;
                
            jQuery.ajax({
                type: "GET",
                url: "/rpc.php?command=checkforpm&_format=xml&userid="+ nUserId +"&q=" + ( Math.floor( Math.random() * 11 ) ),
                dataType: "xml",
                success: function( xml ) {    
                    jQuery( xml ).find( 'reply' ).each( function(){             
                       if( jQuery( xml ).find( 'reply' ).attr( 'status' ) == "OK" ){
                           var nPMId = jQuery( this ).find( 'message' ) .text();
                           jQuery( 'body' ).addClass( 'ajaxcover' );
                           jQuery( '#dialog' ).dialog({
                                open : function(){
                                    jQuery( '#dialog' ).load( '/showpm.php?usrid='+ nUserId +'&pmid=' + nPMId, function() {
                                        jQuery( '#flashobj' ).find( 'embed[rel=flash]' ).css( 'visibility', 'hidden');
                                        new AjaxForm( '/rpc.php', 'feedback', 'ajaxprogress' );
                                    }); 
                                },
                                beforeclose: function(event, ui){
                                    jQuery( '#flashobj' ).find( 'embed[rel=flash]' ).css( 'visibility', 'visible' );
                                    jQuery( 'body' ).removeClass( 'ajaxcover' );
                                    jQuery( '#gamepage_post_reactions_submit' ).removeAttr( 'disabled' );
                                    jQuery( '#gamepage_post_walkthrough_submit' ).removeAttr( 'disabled' );
                                },
                                width: '500',
                                dialogClass: 'dialog-pm',

                                resizable: false
                            });
                            jQuery( '#dialog' ).dialog('open');                        
                       }
                    });
                }
            });
        },
        toggleGamesBlock: function(){
            jQuery( '#gamepage_toggle_favorite_games' ).live( 'click', function(){

                var state = jQuery( this ).attr( 'state' );

                if( state == "open" ){
                    jQuery( this ).text( 'Openen' );
                    jQuery( this ).attr( 'state', 'closed' );
                } else {
                    jQuery( this ).text( 'Sluiten' );
                    jQuery( this ).attr( 'state', 'open' );
                }
                jQuery( '#gamepage_own_games_box_bg' ).slideToggle( 250 );
            });
        },
        saveSorting: function( sorting ){
            jQuery.ajax({
                type: "GET",
                url: "/rpc.php?command=savefavoritegamesorting&_format=xml&sort="+ sorting +"&q=" + ( Math.floor( Math.random() * 11 ) ),
                dataType: "xml",
                beforeSend: function(){
                    jQuery( '#profile_main_container' ).addClass( 'ajaxprogress' );
                },
                success: function( xml ) {
                    jQuery( '#profile_main_container' ).removeClass( 'ajaxprogress' );
                }
            });
        },
        initMyGames: function( element ){
            this.removeGame( element );
            this.attachGame( element );
            jQuery( '#changemygames' ).live( 'click', function( e ){
                e.preventDefault();
                jQuery.ajax({
                    type: "GET",
                    url: "/rpc.php?command=gotofavorites&_format=xml&q=" + ( Math.floor( Math.random() * 11 ) ),
                    dataType: "xml",
                    success: function( xml ) {
                        jQuery( xml ).find( 'reply' ).each( function(){

                            if( jQuery( xml ).find( 'reply content' ).text() == "" || jQuery( xml ).find( 'reply content' ).text() == " " ){
                                window.location = '/favorites.php';
                            }else{
                                jQuery( 'body' ).addClass( 'ajaxcover' );
                                    jQuery( '#dialog' ).dialog({
                                        open : function( e, u ){
                                            jQuery( '#dialog' ).load( '/register.php?destination=/favorites.php', function() {
                                                jQuery( '#flashobj' ).find( 'embed[rel=flash]' ).css( 'visibility', 'hidden');
                                                new AjaxForm( '/rpc.php', 'feedback', 'ajaxprogress' );
                                            });
                                        },
                                        beforeclose: function(event, ui){
                                            jQuery( '#flashobj' ).find( 'embed[rel=flash]' ).css( 'visibility', 'visible' );
                                            jQuery( 'body' ).removeClass( 'ajaxcover' );
                                            jQuery( '#gamepage_post_reactions_submit' ).removeAttr( 'disabled' );
                                            jQuery( '#gamepage_post_walkthrough_submit' ).removeAttr( 'disabled' );
                                        },
                                        width: '500',
                                        dialogClass: 'dialog-' + jQuery( '#login' ).attr( 'id' ),

                                        resizable: false
                                    });
                                    jQuery( '#dialog' ).dialog('open');
                                    }
                            });
                        }
                    });
            });
        },
        removeGame: function( element ){
            jQuery( element ).find( 'ul#favgames li img' ).live( 'click', function( e ) {
                var clicked = this;
                e.preventDefault();
                jQuery.ajax({
                    type: "GET",
                    url: "/rpc.php?command=removemygame&gameid="+ jQuery( clicked ).attr( 'rel' ) +"&_format=xml",
                    dataType: "xml",
                    beforeSend: function(){
                        jQuery( element ).addClass( 'ajaxprogress' );
                    },
                    success: function( xml ) {
                        jQuery( element ).removeClass( 'ajaxprogress' );
                        jQuery( clicked ).parents( 'li').slideUp( 500 );
                    }
                });
            });
        },
        attachGame: function( element ){
            jQuery( '#social_favorite_games' ).live( 'click', function( e ){
                e.preventDefault();
                var clicked = this;
                jQuery.ajax({
                    type: "GET",
                    url: "/rpc.php?command=addtomygames&gameid="+ jQuery( clicked ).attr( 'rel' ) +"&_format=xml&q=" + ( Math.floor( Math.random() * 11 ) ),
                    dataType: "xml",
                    beforeSend: function(){
                        jQuery( element ).addClass( 'ajaxprogress' );
                    },
                    error: function(){
                        jQuery( element ).removeClass( 'ajaxprogress' );
                    },
                    success: function( xml ) {
                        jQuery( element ).removeClass( 'ajaxprogress' );
                        if( jQuery( xml ).find( 'reply' ).attr( 'status' ) == "ERROR" ){
                            jQuery( element ).find( '#favoritegamefeedback' ).css( 'display', 'block' );
                            jQuery( element ).find( '#favoritegamefeedback' ).removeClass( 'info' );
                            jQuery( element ).find( '#favoritegamefeedback' ).addClass( 'error' );
                            jQuery( element ).find( '#favoritegamefeedback' ).text( jQuery( xml ).find( 'message' ).text() );
                            jQuery( '#addtomygames' ).find( '#attachgameid' ).val( jQuery( clicked ).attr( 'rel' ) );

                            if( jQuery( xml ).find( 'content' ).text() == "notloggedin" ){
                                showLogin( 'addtomygames' );
                                jQuery( element ).find( '#favoritegamefeedback' ).slideUp( 500 );
                                jQuery( element ).find( '#favoritegamefeedback' ).text( '' );
                            }
                        } else {
                            jQuery( element ).find( '#favoritegamefeedback' ).removeClass( 'error' );
                            jQuery( element ).find( '#favoritegamefeedback' ).addClass( 'info' );
                            jQuery( element ).find( '#favoritegamefeedback' ).css( 'display', 'block' );
                            jQuery( element ).find( '#favoritegamefeedback' ).text( jQuery( xml ).find( 'message' ).text() );
                            jQuery.user.reloadGames( element );
                        }

                        //setTimeout( jQuery( element ).find( '#favoritegamefeedback' ).fadeOut( 500 ), 1000 );
                    }
                });
            });
        },
        removeGameFavorite: function(){
            jQuery( '.itemlist' ).find( '.delete img' ).live( 'click', function( e ) {
                var clicked = this;
                e.preventDefault();

                jQuery.ajax({
                    type: "GET",
                    url: "/rpc.php?command=removemygame&gameid="+ jQuery( clicked ).attr( 'rel' ) +"&_format=xml",
                    dataType: "xml",
                    beforeSend: function(){
                        jQuery( '.itemlist' ).addClass( 'ajaxprogress' );
                        jQuery( 'table' ).css( 'z-index', '1' );
                    },
                    success: function( xml ) {
                        jQuery( '.itemlist' ).removeClass( 'ajaxprogress' );
                        jQuery( clicked ).parents( 'tr').hide();
                    }
                });
            });
        },
        attachGameFavorite: function(){
            jQuery( 'img[rel^=attachfavorite]' ).live( 'click', function( e ){
                e.preventDefault();
                var clicked = this;

                var aRelation = jQuery( clicked ).attr( 'rel' ).split( "-" );
                jQuery.ajax({
                    type: "GET",
                    url: "/rpc.php?command=addtomygames&gameid="+ aRelation[ 1 ] +"&_format=xml&q=" + ( Math.floor( Math.random() * 11 ) ),
                    dataType: "xml",
                    beforeSend: function(){
                        jQuery( '#profile_main_container' ).addClass( 'ajaxprogress' );
                    },
                    success: function( xml ) {
                        if( jQuery( xml ).find( 'reply' ).attr( 'status' ) == "ERROR" ){
                            jQuery( '.itemlist' ).find( '#favoritegamefeedback' ).css( 'display', 'block' );
                            jQuery( '.itemlist' ).find( '#favoritegamefeedback' ).text( jQuery( xml ).find( 'message' ).text() );
                        } else {
                            jQuery( '.itemlist' ).find( '#favoritegamefeedback' ).css( 'display', 'none' );
                            jQuery( '.itemlist' ).find( '#favoritegamefeedback' ).text( '' );
                            jQuery( '#tblFavorites tr:first-child' ).before( '<tr class="row" id="'+ aRelation[ 1 ] +'"><td class="delete"><img src="images/icon_delete_own_game.gif" alt="" rel="1" style="margin-top:5px;"/></td>\
                                <td class="title"><a href="'+jQuery( clicked ).attr( 'target' )+'">'+jQuery( clicked ).attr( 'alt' )+'</a></td>\
                                <td>0</td>\
                                <td>Vandaag</td>\
                                <td class="sort"><img src="/images/move-row.jpg" alt=""/></td></tr>' );
                        }

                        jQuery( '#profile_main_container' ).removeClass( 'ajaxprogress' );
                    }
                });
            });
        },
        reloadGames: function( element ){
            jQuery.ajax({
                type: "GET",
                url: "/rpc.php?command=reloadfavoritegames&_format=purexml&gameid="+ jQuery( 'input[name=parentid]' ).val() + '&q=' + ( Math.floor( Math.random() * 11 ) ),
                dataType: "xml",
                beforeSend: function(){
                    jQuery( element ).addClass( 'ajaxprogress' );
                },
                error: function( xml ){
                    jQuery( element ).removeClass( 'ajaxprogress' );
                },
                success: function( xml ) {
                    var hasFavorite = false;
                    jQuery( element ).removeClass( 'ajaxprogress' );
                    jQuery( element ).find( 'ul' ).html( '' );
                    jQuery( xml ).find( 'reply item' ).each( function(){
                        hasFavorite = true;
                        var gameID = jQuery( this ).find( 'game' ).text();
                        var title = jQuery( this ).find( 'title' ).text();
                        var url = jQuery( this ).find( 'url' ).text();

                        jQuery( element ).find( 'ul' ).append( '<li><img src="images/icon_delete_own_game.gif" rel="' + gameID + '"> <a href="' + url + '">' + title + '</a></li>' );
                    });

                    if( !hasFavorite ){
                        jQuery( xml ).find( 'reply' ).each( function(){
                            jQuery( element ).find( 'ul' ).prepend( '<li style="width:100%;">' + jQuery( xml ).find( 'reply' ).text() + '</li>' );
                        });
                    }
                }
            });
        }
    }
});

/**
 * jQuery.UsernameCheck - User plugin for Jaludo's speeleiland.nl
 * Written by Henk Walgemoed (h.walgemoed@vivens.com)
 * Date: 2010-05-02
 *
 * @author Henk Walgemoed
 * @version 1.0
 *
 **/
jQuery.fn.UsernameCheck = function() {
    jQuery.ajax({
        type: "GET",
        url: "/rpc.php",
        dataType: "xml",
        data: {
                'command'   : 'checkusername',
                '_format'   : 'purexml',
                'username'  : jQuery('#username').val()
            },
        success: function(xml) {
            var usernames = jQuery( xml ).find("username");
            if (usernames.length == 0) {
                jQuery('#usernameextra').hide();
            } else {
                jQuery().ErrorMsg({
                    div: 'usernameextra',
                    msg: 'Dette brugernavn eksisterer allerede.'
                });
            }
            jQuery('#altusernames').html("");
            if (usernames.length == 0) {
                //jQuery('<div></div>').html('Nom d&#039;utilisateur disponible').appendTo('#altusernames');
            } else {
                jQuery('#altusernames').html("");
                jQuery( xml ).find( 'reply' ).each( function( ){
                    jQuery( this ).find( "item" ).each( function( ){
                        var username = jQuery( this ).find( 'username' ).text();
                        jQuery('<div class=\"altusername\"></div>').html(username).appendTo('#altusernames');
                    });
                });
            }
        } // #succes
    }); // #ajax
}

jQuery.fn.hideRegistration = function( options ) {
    var defaults = { };
    options = jQuery.extend( defaults, options );
    jQuery('#registration_form').hide();
    jQuery("#existing_user").attr("checked", "checked");
}

jQuery.fn.checkIsRegisteredEmail = function( options ) {
    var defaults =
    {
        bReturn : "0",
        email : ""
    };
    options = jQuery.extend( defaults, options );
    jQuery.ajax({
        type: "GET",
        url: "/rpc.php",
        dataType: "xml",
        data: {
            'command'   : 'isregisteredemail',
            '_format'   : 'xml',
            'email'     : options.email
        },
        success: function(xml) {
            if( jQuery(xml).find('reply').attr( "status" ) == "OK" ){
               return true;
            } else {
                return false;
            }
        } // #succes
    }); // #ajax
}

jQuery.fn.ErrorMsg = function( options ) {
    var defaults =
    {
        div : "",
        msg : ""
    };
    
    jQuery("#" + options.div ).next(".testresult").remove();
    jQuery("#" + options.div ).after("<span class=\"testresult\"><span></span></span>");
    jQuery("#" + options.div ).next(".testresult").addClass("shortPass").find("span").text( options.msg );
}

jQuery.fn.ClearErrorMsg = function( options ) {
    var defaults =
    {
        div : ""
    };
    
    jQuery("#" + options.div ).next("span").remove();
}

jQuery("#registerbutton").live("click",function () {
    jQuery("#usernameextra").hide();
    jQuery("#passwordextra").hide();
    jQuery("#passwordcheckextra").hide();
    jQuery("#genderextra").hide();
    jQuery("#calendarextra").hide();
    jQuery("#termsextra").hide();
    jQuery().ClearErrorMsg({
        div: 'usernameextra'
    });
    jQuery().ClearErrorMsg({
        div: 'usernameextra'
    });
    jQuery().ClearErrorMsg({
        div: 'regpassword'
    });
    jQuery().ClearErrorMsg({
        div: 'regpasswordcheck'
    });
    jQuery().ClearErrorMsg({
        div: 'genderextra'
    });
    jQuery().ClearErrorMsg({
        div: 'calendarextra'
    });
    jQuery().ClearErrorMsg({
        div: 'termsextra'
    });
});

jQuery("#registerbutton").live("change",function () {
    jQuery('#linkedPicker').datepick('setDate', new Date(
            parseInt(jQuery('#birthyear').val(), 10),
            parseInt(jQuery('#birthmonth').val(), 10) - 1,
            parseInt(jQuery('#birthday').val(), 10))
    );
});




function updateLinked(dates) {
    jQuery('#birthmonth').val(dates.length ? dates[0].getMonth() + 1 : '');
    jQuery('#birthday').val(dates.length ? dates[0].getDate() : '');
    jQuery('#birthyear').val(dates.length ? dates[0].getFullYear() : '');
}

function echeck(str) {
    var at="@"
    var dot="."
    var lat=str.indexOf(at)
    var lstr=str.length
    var ldot=str.indexOf(dot)
    if (str.indexOf(at)==-1){
       return false
    }

    if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
       return false
    }

    if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
        return false
    }

     if (str.indexOf(at,(lat+1))!=-1){
        return false
     }

     if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
        return false
     }

     if (str.indexOf(dot,(lat+2))==-1){
        return false
     }

     if (str.indexOf(" ")!=-1){
        return false
     }

     return true
}



function redirect( sLoc, newwindow ) {
    newwindow = ( newwindow == null) ? "0" : "1";

    if ( newwindow == "1" ) {
        window.open(sLoc);
    } else {
        document.location.href = sLoc;
    }
}

/**
 * jQuery.loadAvatar - Avatar plugin for Jaludo's speeleiland.nl
 * Written by Henk Walgemoed (h.walgemoed@vivens.com)
 * Date: 2010-05-02
 *
 * @author Henk Walgemoed
 * @version 1.0
 *
 **/
jQuery.fn.loadAvatar = function( userid, sGuid ) {
    var so = new SWFObject( "/media/flash/avatar.swf", "avatar", "700", "500", "9,0,0,0", "#FFFFFF" );
    so.addParam( "quality", "high" );
    so.addParam( "wmode", "transparent" );
    so.addVariable( "userid", userid );
    so.addVariable( "sguid", sGuid );
    so.write( "avatar" );
}

/**
 * dialog plugin for Jaludo's speeleiland.nl
 * Written by Ronnie Visser (r.visser@vivens.com)
 * Date: 2010-04-14
 *
 * @author Ronnie Visser
 * @version 1.0
 *
 **/
jQuery( 'a[rel=dialog]' ).live( 'click', function( e ){

    var eClickedElement = jQuery( this );
    e.preventDefault();
    jQuery( 'body' ).addClass( 'ajaxcover' );
    var sClickID = jQuery(this).attr('id');
    jQuery( '#dialog' ).dialog({
        open : function( e, u ){

            jQuery( '#dialog' ).load( jQuery( eClickedElement ).attr( 'href' ), function() {
                new AjaxForm( '/rpc.php', 'feedback', 'ajaxprogress' );
                jQuery( '#flashobj' ).find( 'embed[rel=flash]' ).css( 'visibility', 'hidden');
                if ( sClickID == "register" || sClickID == "login" ) {
                    // Setting up password strength meter
                    jQuery("#regpassword").passStrength({
                        userid:    "#username"
                    });
                    if ( sClickID == "register" ) {
                        jQuery('#new_user').attr('checked','checked');
                        jQuery().RegisterScreenSetup();
                    }
                }
            });

        },
        beforeclose: function(event, ui){
            jQuery( '#flashobj' ).find( 'embed[rel=flash]' ).css( 'visibility', 'visible' );
            jQuery( 'body' ).removeClass( 'ajaxcover' );
        },
        width: '500',
        dialogClass: 'dialog-' + jQuery( eClickedElement ).attr( 'id' ),

        resizable: false
    });

     jQuery( '#dialog' ).dialog('open');

});

/* Profile page */
jQuery.fn.avatarDefault = function( sGuid ) {
    jQuery.ajax({
        type: "GET",
        url: "/rpc.php",
        dataType: "xml",
        data: {
                'command'   : 'setdefaultavatar',
                '_format'   : 'xml',
                'guid'      : sGuid
            },
        success: function(xml) {
            jQuery().refreshAvatars();
            jQuery('#profile_default_avatar').attr("src","");
            jQuery( xml ).find( 'reply' ).each( function( ){
                var imageloc = jQuery( this ).find( 'content' ).text();
                jQuery('#profile_default_avatar').attr("src",imageloc);
            });

        } // #jQuery().succes
    }); // #ajax
}

jQuery.fn.avatarCustom = function( sGuid ) {
    jQuery.ajax({
        type: "GET",
        url: "/rpc.php",
        dataType: "xml",
        data: {
                'command'   : 'setcustomavatar',
                '_format'   : 'xml',
                'guid'      : sGuid
            },
        success: function(xml) {
            jQuery().refreshAvatars();
            jQuery('#profile_default_avatar').attr("src","");
            jQuery( xml ).find( 'reply' ).each( function( ){
                var imageloc = jQuery( this ).find( 'content' ).text();
                jQuery('#profile_default_avatar').attr("src",imageloc);
            });

        } // #jQuery().succes
    }); // #ajax
}

jQuery.fn.refreshAvatars = function() {
    jQuery().getavatars();
    //jQuery( '#users' ).check();
}

jQuery.fn.removeAvatar = function( sGuid) {
    jQuery.ajax({
        type: "GET",
        url: "/rpc.php",
        dataType: "xml",
        data: {
                'command'   : 'removeavatar',
                '_format'   : 'xml',
                'guid'      : sGuid
            },
        success: function(xml) {
           jQuery().refreshAvatars();
           jQuery('#profile_default_avatar').attr("src","");
            jQuery( xml ).find( 'reply' ).each( function( ){
                var imageloc = jQuery( this ).find( 'content' ).text();
                jQuery('#profile_default_avatar').attr("src",imageloc);
            });
        } // #succes
    }); // #ajax
}

jQuery.fn.getavatars = function() {
    jQuery.ajax({
        type: "GET",
        url: "/rpc.php",
        dataType: "xml",
        data: {
                'command'   : 'getavatars',
                '_format'   : 'purexml'
            },
        success: function(xml) {
            jQuery('#profile_avatar_blocks').html("");
            jQuery( xml ).find( 'reply' ).each( function( ){
                jQuery( this ).find( "item" ).each( function( s ){
                    var html = jQuery( this ).find( 'html' ).text();
                    jQuery(html).appendTo('#profile_avatar_blocks');
                });
            });

        } // #succes
    }); // #ajax
    
    jQuery.ajax({
        type: "GET",
        url: "/rpc.php",
        dataType: "xml",
        data: {
                'command'   : 'getcustomavatars',
                '_format'   : 'purexml'
            },
        success: function(xml) {
            jQuery('#profile_custom_avatar_blocks').html("");
            jQuery( xml ).find( 'reply' ).each( function( ){
                jQuery( this ).find( "item" ).each( function( s ){
                    var html = jQuery( this ).find( 'html' ).text();
                    jQuery(html).appendTo('#profile_custom_avatar_blocks');
                });
            });

        } // #succes
    }); // #ajax
    
    jQuery( '#users' ).check();
}

jQuery.fn.extend({
    initComponents: function( displayType, userid ) {
        //return this.each(function() {
            jQuery.component.init( displayType, userid );
        //});
    },
    initfavoriteGames: function(){
        return this.each(function() {
            jQuery.component.loadFavoriteGames();
        });
    }
});

/**
 * jQuery.component - component plugin for Jaludo's speeleiland.nl
 * Written by Ronnie Visser (r.visser@vivens.com)
 * Date: 2010-05-24
 *
 * @author Ronnie Visser
 * @version 1.0
 *
 **/
jQuery.extend({
    component: {
        init : function( displayType, userid ){
            if( displayType == "gamepage" ){
                //this.highscore( userid );
                this.gamereaction();
                this.loadFavoriteGames();
                this.increasePlayAmountifFavorite();
            }
            
            this.hasPM( userid );
        },
        highscore: function( userid, message ){
            if( userid != " " ){        
                jQuery( '#highscorewrapper' ).load( '/user/highscore.php?gameid='+game_id, function(){});
            }else{
                jQuery( '#highscorewrapper' ).addClass( 'highscore-notloggedin' );
                jQuery( '#highscorewrapper' ).append( '<div id="highscore-notloggedin"></div>' );
                jQuery( '#highscore-notloggedin' ).text( message );
                setTimeout( "jQuery( '#highscore-notloggedin' ).hide();jQuery( '#highscorewrapper' ).removeClass( 'highscore-notloggedin' );", 4000 );    
                setTimeout( "jQuery( '#highscorewrapper' ).html( '' );jQuery( '#highscorewrapper' ).load( '/user/highscore.php?gameid='+game_id, function(){});", 5000 );    
            }
            
        },
        gamereaction: function(){
            jQuery( '#gamereactionswrapper' ).load( '/user/gamereactions.php?gameid='+game_id, function(){
                //callback
            });
        },
        loadFavoriteGames: function(){
            jQuery.user.reloadGames( jQuery( 'div[rel=favoritegames]' ) );
        },
        hasPM: function( nUserId ){
            jQuery.user.hasPM( nUserId );
        },
        increasePlayAmountifFavorite: function(){
            jQuery.ajax({
                type: "GET",
                url: "/rpc.php",
                dataType: "xml",
                data: {
                        'command'   : 'increaseplayamount',
                        '_format'   : 'xml',
                        'gameid'      : game_id
                    },
                success: function(xml) {
                }
            });
        }
    }
});


/**
 *  Function s build by Jaludo's own programmes
 *
 *
 **/

var divName = 'dek';
var offX = 16;
var offY = 16;
var imgserv = 'http://simg.jaludo.com/';

/*function mouseX(evt) {if (!evt) evt = window.event; if (evt.pageX) return evt.pageX; else if (evt.clientX)return evt.clientX + (document.documentElement.scrollLeft ?  document.documentElement.scrollLeft : document.body.scrollLeft); else return 0;} function mouseY(evt) {if (!evt) evt = window.event; if (evt.pageY) return evt.pageY; else if (evt.clientY)return evt.clientY + (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop); else return 0;} function follow(evt) {if (document.getElementById) {var obj = document.getElementById(divName).style; obj.visibility = 'visible'; obj.left = (parseInt(mouseX(evt))+offX) + 'px';  obj.top = (parseInt(mouseY(evt))+offY) + 'px';}} document.onmousemove = follow;*/

function popup(msg)
{
   var content="<img src='"+msg+"' alt='' style='border: 2px inset #C0C0C0; height: 123px; width: 200px;' />";
   document.getElementById('dek').innerHTML = content;
}


function kill()
{
   var content= "";
   document.getElementById('dek').innerHTML = content;
   clearTimeout(t);
}


function reaction_options_view(id)
{
    document.getElementById("reaction_more_options_"+id).style.display = "block";
    document.getElementById("reaction_rating_"+id).style.display = "none";
}

function reaction_options_hide(id)
{
    document.getElementById("reaction_more_options_"+id).style.display = "none";
    document.getElementById("reaction_rating_"+id).style.display = "block";
}

var resizeFactor = 5; // IMPORTANT: must be an even number!!
var prevSliderValue = 0;
jQuery(document).ready(function(){
    // Load game page zoom slider
    jQuery("#game-zoom-placeholder").slider({

        value: prevSliderValue,
        range: "min",
        animate: true,
        orientation: "horizontal",
        slide: function(event, ui) {
            zoomObject(ui.value);
        },
        change: function(event, ui) {
            zoomObject(ui.value);
        },
        stop: function(event, ui) {/* pageTracker._trackEvent('Zoom', 'slider', jQuery("h1").html()); */},
        start: function(event, ui) {}
    });
});

function gameZoom(zoomMode){
    var zoom = jQuery("#game-zoom-placeholder").slider("value");

    prevSliderValue = zoom;

    if(zoomMode)
        zoom += resizeFactor;
    else
        zoom -= resizeFactor;

    jQuery("#game-zoom-placeholder").slider("value", zoom);
}

function zoomObject(pos){

    jQuery('#dropdown').slideUp(100);
    if ( document.getElementById('dropdown_menu') ) {
        document.getElementById('dropdown_menu').className = 'active';
    }
    pos += 100;

    var newWidth = Math.ceil( pos*startGameWidth/100 );
    var newHeight = Math.ceil( pos*startGameHeight/100 );

    MainContentWidth = newWidth + 169;

    if(MainContentWidth <= startMainGameBoxWidth)
    {
        MainContentWidth = startMainContentWidth;
        NavMarginRight = 6;
        SearchFormPos = 648;
        GameBox = 926;
        game_bottomPos = 14;
    }
    else
    {
        MainContentWidth = MainContentWidth + 54;
        NavMarginRight = 6 + Math.floor((MainContentWidth-startMainContentWidth)/10);
        SearchFormPos = MainContentWidth-332;
        GameBox = MainContentWidth-54;
        game_bottomPos = Math.floor((newWidth-728)/2);
    }

    jQuery("#content").css({'width': (MainContentWidth)+'px'});
    jQuery("#main").css({'width': (MainContentWidth)+'px'});
    jQuery("#header").css({'width': (MainContentWidth)+'px'});
    jQuery("#nav-top").css({'width': (MainContentWidth-6)+'px'});
    jQuery("#nav-top li a").css({'margin-right': (NavMarginRight)+'px'});
    jQuery("#search_bar form").css({'margin-left': (SearchFormPos)+'px'});
    jQuery("#search_bar").css({'width': (MainContentWidth)+'px'});
    jQuery("#game_box").css({'width': (GameBox)+'px'});
    jQuery("#flashobj").css({'width': (newWidth)+'px','height': (newHeight)+'px'});
    jQuery("#game_bottom").css({'padding-left': (game_bottomPos)+'px'});
}

/**
 *  END
 *
 **/

jQuery(document).ready(function(){ 
    
    jQuery("#regpassword").live( 'focus', function () {
        jQuery().ClearErrorMsg({
            div: 'passwordextra'
        });
    });               
    
    jQuery("#username").live( 'focusout', function () {
        jQuery("#username").live( 'focus', function () {
            jQuery().ClearErrorMsg({
                div: 'usernameextra'
            });
        });
        if (jQuery('#username').val() != "" ) {
            jQuery().UsernameCheck();
        }
    });
    
    jQuery(".altusername").live("click",function () {
        jQuery("#username").live( 'focus', function () {
            jQuery().ClearErrorMsg({
                div: 'usernameextra'
            });
        });
        jQuery("#username").val( jQuery(this).text() );
        jQuery().UsernameCheck();
        jQuery("#username").focus();
    });

    jQuery(function()
    {
        if ( jQuery('.date-pick').length > 0 ) {
            jQuery('.date-pick').datePicker(
                {
                    startDate: '01/01/1910',
                    endDate: (new Date()).asString()
                }
            );
        }
    });

    jQuery("#regpasswordcheck").live( 'blur', function () {
        jQuery().ClearErrorMsg({
            div: 'regpasswordcheck'
        });
        jQuery('#passwordcheckextra').hide();
        if (jQuery("#regpassword").length > 0 && jQuery("#regpasswordcheck").length > 0 ) {
            if (jQuery("#regpassword").val() != jQuery("#regpasswordcheck").val() ) {
                jQuery().ErrorMsg({
                    div: 'regpasswordcheck',
                    msg: 'Advarsel: Adgangskoderne er ikke ens.'
                });
                
            }
        }
    });

    jQuery("#existing_user").attr("checked", "checked");


    jQuery("#new_user").live("click",function () {
        if ( jQuery('#email').val() != "" ) {

            jQuery.ajax({
                type: "GET",
                url: "/rpc.php",
                dataType: "xml",
                data: {
                        'command'   : 'isregisteredemail',
                        '_format'   : 'xml',
                        'email'     : jQuery('#email').val()
                    },
                success: function(xml) {
                    if( jQuery(xml).find('reply').attr( "status" ) == "ERROR" ){
                        jQuery("#popup_step_between").html("<img id=\"registration_next_step\" style='cursor: pointer' src='/images/registration/popup_next_button.jpg' border='0'/>");
                        jQuery('#submiterror').hide();
                    } else {
                        jQuery().ErrorMsg({
                            div: 'submiterror',
                            msg: 'Beklager, denne e-mail-adresse er allerede brugt.'
                        });
                    }
                } // #succes
            }); // #ajax
        } else {
            jQuery().RegisterScreenSetup();
        }
    });

    jQuery.fn.RegisterScreenSetup = function() {
        jQuery("#popup_step_between").html("<img id=\"registration_next_step\" style='cursor: pointer' src='/images/registration/popup_next_button.jpg' border='0'/>");
        jQuery('#submiterror').hide();
        jQuery('#password').hide();
    }

    jQuery("#registration_next_step").live("click",function () {
        if (jQuery('#email').val() == "" || echeck(jQuery('#email').val() ) == false ) {
            jQuery().ErrorMsg({
                div: 'submiterror',
                msg: ''
            });
        } else {
            jQuery('#regemail').val( jQuery('#email').val() );
            jQuery('#login_form').hide();
            jQuery('#registration_form').show();

        }
    });

    jQuery("#existing_user").live("click",function () {
        jQuery("#popup_step_between").html("<input class=\"popup_inlogbutton\" type=\"image\" value=\"Login !\" src=\"/images/registration/popup_login_button.jpg\" /><a rel=\"dialog\" id=\"forgotpassword\" href=\"/forgotpassword.php\">Jeg har glemt min adgangskode.</a>");
        jQuery('#submiterror').hide();
        jQuery('#password').show();
    });

    jQuery( '#profile_main_topscores_ftr' ).live('click', function( ){
        jQuery('.profile_main_topscores_tbl_cnt').show();
        jQuery('#profile_main_topscores_ftr').hide();
    });

    /**
     * functionality for game messages for Jaludo's speeleiland.nl
     * Written by Ronnie Visser (r.visser@vivens.com)
     * Date: 2010-04-11
     *
     * @author Ronnie Visser
     * @version 1.0
     *
     **/
    jQuery( '.gamepage_reactions' ).live('mouseover mouseout', function(event){
        if (event.type == 'mouseover') {
            jQuery( this ).find( '.gamepage_reactions_options' ).show();
            jQuery( this ).find( '.gamepage_reactions_options_notactive' ).hide();
        }else{
            jQuery( this ).find( '.gamepage_reactions_options' ).hide();
            jQuery( this ).find( '.gamepage_reactions_options_notactive' ).show();
        }
    });

    jQuery( '.profile_avatar_block_content' ).live( 'click', function( e ){
        e.preventDefault();
        var aGiudInfo = jQuery( this ).attr( 'rel' ).split( '-' );
        if ( aGiudInfo[ 0 ] == "custom" ) {
            jQuery().avatarCustom( aGiudInfo[ 1 ] );
        } else {
            jQuery().avatarDefault( aGiudInfo[ 1 ] );
        }
        
    });

    jQuery( '.profile_avatar_delete' ).live( 'click', function( e ){
        e.preventDefault();
        var aGiudInfo = jQuery( this ).attr( 'rel' ).split( '-' );
        jQuery().removeAvatar( aGiudInfo[ 1 ] );
    });

    /**
    profile page - ajax loader */
    jQuery( 'a[rel=ajax]' ).live( 'click', function( e ){
        e.preventDefault();
        jQuery( 'a[rel=ajax]' ).each( function(){
            jQuery( this ).removeClass( 'active' );
        });
        jQuery( this ).addClass( 'active' );

        var eClicked = this;

        jQuery( '#profile_main_content' ).html( '' );
        jQuery( '#profile_main_content' ).css({
            height: '200px'
        });
        jQuery( '#profile_main_content' ).addClass( 'itemlistwrapper ajaxprogress' );
        jQuery( '#profile_main_content' ).html( '<div class="ajaxswirl-globe"><!-- --></div>' );

        var section = ( jQuery.url.attr("file") == jQuery( eClicked ).attr( 'href' ).substr( 1 ) ? " #profile_main_container" : "" );
        jQuery.ajax({
            url: jQuery( eClicked ).attr( 'href' ),
            dataType: 'html',
            context: '#profile_main_container',
            success: function( htmlBody ){
                jQuery( '#profile_main_content' ).html( jQuery( htmlBody ).find( '#profile_main_container' ).html() );
            }});

    });
    
    jQuery( '#birthday #birthmonth #birthyear' ).live( 'change', function(){
        var nBirthDay = jQuery( '#birthday' ).val(); 
        var nBirthMonth = jQuery( '#birthmonth' ).val(); 
        nBirthDay = nBirthDay.length == 1 ? "0"+nBirthDay : nBirthDay;
        nBirthMonth = nBirthMonth.length == 1 ? "0"+nBirthMonth : nBirthMonth;
        var nBirthYear = jQuery( '#birthyear' ).val(); 
        jQuery( '#linkedPicker' ).val( nBirthDay +'-'+ nBirthMonth +'-'+ nBirthYear );
    }); 
    
    if( jQuery( '.highscore-notloggedin' ).length == 1 ){
        setTimeout( "jQuery( '.highscore-notloggedin' ).fadeIn( 1000 )", 13000 );
    }

    //Disable message submit btn
   // jQuery( '' ).each( function(){

    //});
});

function showLogin( sAction ){
    jQuery( 'body' ).addClass( 'ajaxcover' );
    jQuery( '#dialog' ).dialog({
        open : function( e, u ){
            if( sAction != "" )
                sAction = "?action=" + sAction;

            jQuery( '#dialog' ).load( '/register.php' + sAction, function() {
                jQuery( '#flashobj' ).find( 'embed[rel=flash]' ).css( 'visibility', 'hidden');
                new AjaxForm( '/rpc.php', 'feedback', 'ajaxprogress' );
            });
        },
        beforeclose: function(event, ui){
            jQuery( '#flashobj' ).find( 'embed[rel=flash]' ).css( 'visibility', 'visible' );
            jQuery( 'body' ).removeClass( 'ajaxcover' );
            jQuery( '#gamepage_post_reactions_submit' ).removeAttr( 'disabled' );
            jQuery( '#gamepage_post_walkthrough_submit' ).removeAttr( 'disabled' );
        },
        width: '500',
        dialogClass: 'dialog-' + jQuery( '#login' ).attr( 'id' ),

        resizable: false
    });
    jQuery( '#dialog' ).dialog('open');
}

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

function openBlockedPopUp(){
    jQuery( 'body' ).addClass( 'ajaxcover' );
    jQuery( '#dialog' ).dialog({
        open : function( e, u ){
            jQuery( '#dialog' ).load( 'blocked.php', function() {
                jQuery( '#flashobj' ).find( 'embed[rel=flash]' ).css( 'visibility', 'hidden');
                new AjaxForm( '/rpc.php', 'feedback', 'ajaxprogress' );
            });
        },
        beforeclose: function(event, ui){
            jQuery( '#flashobj' ).find( 'embed[rel=flash]' ).css( 'visibility', 'visible' );
            jQuery( 'body' ).removeClass( 'ajaxcover' );
            jQuery( '#gamepage_post_reactions_submit' ).removeAttr( 'disabled' );
            jQuery( '#gamepage_post_walkthrough_submit' ).removeAttr( 'disabled' );
        },
        width: '500',
        dialogClass: 'dialog-' + jQuery( '#login' ).attr( 'id' ),

        resizable: false
    });
    jQuery( '#dialog' ).dialog('open');
}
