/* Copyright (c) 2007-2010 SPIL GAMES.  DO NOT COPY THIS CODE. */
;SPI.getUserPoints = function(callback, username) {
    SPI.highscore.init();
	if (username === undefined) {
		SPI.highscore.UserLevel(callback);
	} else {
		SPI.highscore.getUserLevel(function(data){
		   	var tmp = 0;
			try {
		   		tmp = data.hyscor.level || 0;
		   	} catch(e) {};
			callback.call(this, tmp);
		}, username);
	}
};

SPI.getUserAwards = function(callback, username) {
	SPI.achievements.init();
	if (username === undefined) {
		SPI.achievements.UserAwardsCount(callback);
	} else {
		SPI.achievements.getAchievementsCountForUser(function(data){
			var tmp = 0;
			try{
				tmp = data.hyscor.resultset.total || 0;
			}catch(e){};
			callback.call(this, tmp);
		},username);
	}
};

SPI.getUserGalery = function(callback,username) {
  if (username === undefined) {
    SPI.myGallery.getCountForUser(callback,false);
  }else{
    SPI.myGallery.getCountForUser(callback,username);
  };
};


SPI.getUserGames = function(callback,username) {
      if (username === undefined) {
       SPI.myGames.getCountForUser(callback,false);
      } else {
        SPI.myGames.getCountForUser(callback,username);
      };
};
	
SPI.checkUserLevel = function(userLevels, userPoints) {
    var level = 0, currentLevel = 0, previousLevel = 0, currentPoints = 0, previousPoints = 0, pointsLeft = 0, nextLevel = 0;

    if( userPoints >= userLevels[userLevels.length-1] ) {
        return {'level': userLevels.length-1, 'levelFrom': userLevels[userLevels.length-1], 'points': userPoints, 'pointsLeft': 0, 'nextLevel': userLevels.length-1, 'nextLevelFrom': userLevels[userLevels.length-1]};
    }
    for( var i=userLevels.length-1; i>0; i-- ) {
        level = i;
        currentLevel = i;
        currentPoints = userLevels[currentLevel];

        previousLevel = i-1;
        previousPoints = userLevels[previousLevel];

        if( userPoints == currentPoints ) {
            userLevel = currentLevel;
            nextLevel = userLevel + 1;
            pointsLeft = userLevels[nextLevel] - userPoints;
            if( userLevels[nextLevel] == undefined ) { pointsLeft = 0; nextLevel = -1; }
            return {'level': userLevel, 'points': userPoints, 'pointsLeft': pointsLeft, 'nextLevel': nextLevel, 'nextLevelFrom': userLevels[nextLevel] };
        }
        if( userPoints < currentPoints && userPoints >= previousPoints ) {
            userLevel = previousLevel;
            nextLevel = userLevel + 1;
            pointsLeft = userLevels[nextLevel] - userPoints;
            return {'level': userLevel, 'levelFrom': userLevels[userLevel], 'points': userPoints, 'pointsLeft': pointsLeft, 'nextLevel': nextLevel, 'nextLevelFrom': userLevels[nextLevel] };
        }
    }
    return {'level': 1, 'levelFrom': 0, 'points': 0, 'pointsLeft': userLevels[2], 'nextLevel': 2, 'nextLevelFrom': userLevels[2] };
};

SPI.fillRightStatusBoxPart = function(username, _public){
    SPI.getUserGalery(username,function(data){
      $('.generatedcontent_insert_number').text(data.gamatar.resultset.total);
    },username);
    SPI.getUserPoints(function(userPoints) {
        var user = SPI.checkUserLevel( userLevels, userPoints );
        $('.points_insert_number').text(userPoints);
    }, username);

	//if (username === undefined || _public) {
		SPI.getUserAwards(function(awards){
		    $('.awards_insert_number').text(awards);
		}, username);
	//}
};

;;
/**
 * jQuery geoip plugin
 *
 * @author nez
 */
SPI.geoip = (function() {

    var config = {settings: {
            url: '/lc/pb/1/country',
            geoiprule_url: '/geoip/%1$s.json',
            timeout: 7000,
            cookieName: '_SPI_geoip',
            cookieDisplayedName: '_SPI_geoip_displayed',
            cookieRules: {
                path: '/',
                expires: 365
            }
        }
    };

    var that = {};
    var redirectTo = '-1'; // -1 means "do not redirect"
    var ruleDomain = null;

    // gets redirect domain from cookie
    var getRedirectCookie = function() {
        redirectTo = $.cookie(config.settings.cookieName) || null;
        return redirectTo;
    };

    // checks if popup can be displayed
    var canPop = function() {
        return !(getRedirectCookie() || $.cookie(config.settings.cookieDisplayedName));
    };

    that.init = function() {
        try {
            if( canPop() === true ) {
                checkUserLocation(function(data){
                    if( data && data.locatar ) {
                        checkRules( data.locatar.country_code, function(data){
                            if( data.domain && data.domain != '' ) {
                                ruleDomain = data.domain;
                                showGeoIpBox(data);
                            }
                        });
                    }
                });
            } else if(redirectTo && redirectTo != '-1') {
                SPI.geoip.redirectMe(redirectTo);
            }
        } catch(e){}
    };
    // sets redirect cookie
    var setRedirectCookie = function(value) {
        $.cookie( config.settings.cookieName, value, config.settings.cookieRules );
    };

    // sets redirect cookie
    that.dontAskAgain = function() {
        setRedirectCookie('-1');
    };

    // sets cookie to show the Box only once per session.
    that.setDisplayed = function() {
        $.cookie(config.settings.cookieDisplayedName, 1, {path: '/'});
    };

    // gets redirect rule - if exists(ajax request)
    var checkRules = function( country_code, callback ) {
        $.ajax({
            global: false,
            cache: true,
            timeout: config.settings.timeout,
            url: SPI.sprintf(config.settings.geoiprule_url, country_code),
            type: 'GET',
            dataType: 'json',
            success: handleRuleResponse,
            error: function(xml, mesg, error) { handleRuleResponse.call(this, {}, ''); },
            after_call: callback
        });
    };

    var handleRuleResponse = function(data, mesg) {
        this.after_call(data);
    };

    // redirects user & sets cookie if needed
    that.redirectMe = function(domain, set_cookie) {
        if(domain != null) {
            window.top.location.href = domain;
        } else {
            if (set_cookie) {
                setRedirectCookie(ruleDomain);
            }
            window.top.location.href = ruleDomain;
        }
    };

    // gets info about users location (Locatar service)
    var checkUserLocation = function(callback) {
        $.ajax({
            global: false,
            cache: true,
            timeout: config.settings.timeout,
            url: config.settings.url,
            type: 'GET',
            dataType: 'json',
            success: handleResponse,
            error: function(xml, mesg, error) { handleResponse.call(this, {"locatar":{}}, ''); },
            after_call: callback,
            data: {
                outputtype: 'json'
            }
        });
    };

    // response handler
    var handleResponse = function(data, mesg) {
        // If there was an error, mimic that there is no result...
        if (data.locatar && data.locatar.errorcode !== undefined) {
            data = {"locatar":{}};
        }
        this.after_call(data);
    };
    return that;
})();

;/**
 * jQuery avatars plugin (avatars picker)
 *
 * @author nez
 */
SPI.avatars = (function() {
    var config = {settings: {
            itemsPerPage: 20,
            maxPages: 4,
			li_id: 'avatar',
/* FIXME:  useravatars_limit should not be hardcoded
   For some reason on IE6 SPI._settings.avatars.useravatars_limit is not read correctly
*/
/*			useravatars_limit: SPI._settings.avatars.useravatars_limit,*/
			useravatars_limit: 10,
 			timeout: 7000,
            dummy_big: '/img/userprofile/dummy_big.gif',
            dummy_small: '/img/userprofile/dummy_small.gif'
        }
    };
    SPI.getAndUpdateConfig('avatars', config);

    var that = {};
    var saveClicked = false;

    that.avatar = '';
	that.userAvatarsLength = 0;

    //vars for avatar uploader
    var maxx = 150;
    var maxy = 175;
    var _cropObj = null;
    var _objectstohide = [];
	var _jcropObj = null;
	var _setSelectArr = null;

    that.init = function( items, callback ) {

        var callback = callback || null;

        that.items = items.concat();

        that.selectedAvatarId = null;
        
        loadUserAvatar();

        $('div#avatarslist ul li a').live('click', function(){
            $('div#avatarslist ul li.active').removeClass('active');
            var li_item = $(this).parent('li:first');
            li_item.addClass('active');
            var avatar_id = li_item.attr('avatarid');
            $('div#avatarslist ul li a.delprogress[avatarid='+avatar_id+']').show();
            selectAvatar(avatar_id);
            if( saveClicked == false && avatar_id != '' && avatar_id != 'DEFAULT' && avatar_id != 'avatarid_'+that.avatar ) {
                saveClicked = true;
                var save_id = avatar_id.replace(/^[^_]+_/i, '');
                setAsAvatar( save_id );
            }
            return false;
        });

        // GET GAMATAR DATA
        // load USER CONTENT (avatars)
        getUserAvatars(function(data){
            if( data.gamatar && data.gamatar.resultset && data.gamatar.resultset.result && data.gamatar.resultset.result.length>0 ) {
                var temp = null, item = null;
                var itemz = data.gamatar.resultset.result;
                if( itemz.length > 0 ) {
                    that.userAvatarsLength = itemz.length;
                    for( var i in itemz ) {
                        item = itemz[i];
                        that.items.unshift( {id: 0, gamatarid: item.id, user: 1} );
                    }
                }
            }
            that.renderList();
            if( callback != null && typeof callback =='function') {
                callback.call(this);
            }
        });

    };

    // response handler
    var handleResponse = function(data, mesg) {

		// If there was an error, mimic that there is no result...
		if (data.gamatar && data.gamatar.errorcode !== undefined) {
			data = {"gamatar":[]};
		}
        this.after_call(data);
    };

    var getUserAvatars = function(callback) {
        $.ajax({
			global: false,
			cache: false,
			timeout: config.settings.timeout,
			url: SPI.sprintf(config.settings.avatar_url_list, SPI._settings.global.site_id),
            type: 'GET',
            dataType: 'json',
            success: handleResponse,
            error: function(xml, mesg, error) { if( mesg=='timeout') { that.renderList(); } else { handleResponse.call(this, {"gamatar":[]}, ''); } },
            after_call: callback,
            data: {
                username: $.profilar.forService().username,
                hash: $.profilar.forService().hash,
                /*pagenr: 1,
                pagesize: config.settings.useravatars_limit,*/
				outputtype: 'json'
            }
        });
    };

    var setDummyAvatar = function() {
        $('#userAvatar').attr('src', config.settings.dummy_big);
        $("#avatarnormal").attr('src', config.settings.dummy_small).show();
        $("#avatardummy").hide();
        that.selectedAvatarId = null;
    };

    var checkIfCanUpload = function() {
        if( userLevel >= config.settings.min_upload_level ) {
            var message = '';
            if( that.userAvatarsLength >= config.settings.useravatars_limit ) {
                message = SPI._langStrings.avatars.user_avatars_limit_reached;
                $('div#uploader div.uploadavatar').hide();
                $('div#uploader div.sorrymessage').hide();
                $('div#uploader div.sorrymessage_limit').html(message).show();
            } else {
                $('div#uploader div.sorrymessage').hide();
                $('div#uploader div.sorrymessage_limit').hide();
                $('div#uploader div.uploadavatar').show();
            }
        } else {
                message = SPI.sprintf(SPI._langStrings.avatars.min_upload_level_message, config.settings.min_upload_level);
                $('div#uploader div.uploadavatar').hide();
                $('div#uploader div.sorrymessage').html(message).show();
                $('div#uploader div.sorrymessage_limit').hide();
        }
    };

    var removeAvatarFromList = function( id ) {
        var id = parseInt(id);
        if( id > 0 ) {
            if( that.items && that.items.length>0 ) {
                for(var i in that.items ) {
                    if( parseInt(that.items[i].gamatarid) == id && that.items[i].user == 1 ) {
                        that.items.splice(i,1);
                        that.userAvatarsLength--;
                        if( id == that.avatar ) {
                            // set actual avatar to EMPTY
                            clearUserAvatar(function(error){
                                if( error ) {}
                                else {
                                    setDummyAvatar();
                                }
                            });
                        //} else if( id == parseInt( $('div#avatarselected div.picture1').attr('id').replace(/^avatarid_/i,'') ) || $('div#avatarselected div.picture1').attr('id') == 'DEFAULT' ) {
                        } else {
                            if( id == that.selectedAvatarId || that.selectedAvatarId == null ) {
                                loadUserAvatar();
                            }
                        }
                        //checkIfCanUpload();
                        break;
                    }
                }
            }
        }
    };

    that.renderList = function( page ) {

        // TODO No avatar uploader yet.
        //checkIfCanUpload();
        if( $('div#avatarslist div.ul_container ul').length == 0 ) {
            $('div#avatarslist div.ul_container').append('<ul></ul>');
        }
        $('div#avatarslist ul').empty();
        var page = page || 1;

        var icons = that.items;

    	if (icons.length == 0) { return; }

    	var sitesQuantity = Math.ceil(icons.length/config.settings.itemsPerPage);
        var remove = '';
        for (var i=(page*config.settings.itemsPerPage)-config.settings.itemsPerPage; i<(page*config.settings.itemsPerPage) && i<icons.length; i++) {
            var additional_class = '';
            if ((i+1) % 5 == 0) {
                additional_class = ' last';
            }
            var icon = '<a class="avatar" href="#"><img src="' + SPI.sprintf(SPI._settings.global.avatar_url_big, icons[i].gamatarid) + '" alt="" border="0" width="142" height="142" />'+
                        '<div class="button_group">'+
                        '<span class="button_left"><img src="/img/button_left.png" alt="" /></span>'+
                        '<span class="button_middle">'+SPI._langStrings.avatars.set_as_avatar+'</span>'+
                        '<span class="button_right"><img src="/img/button_right.png" alt="" /></span>'+
                        '</div>'+
            '</a>';
            remove = icons[i].user == 1 ? '<a class="removeAvatar closebtn" avatarid="'+icons[i].gamatarid+'" title="' + config.langStrings.avatar_remove +'"></a>' : '';
            indicator = '<a class="delprogress" style="display: none;" avatarid="'+icons[i].gamatarid+'" title="' + config.langStrings.avatar_remove +'"></a>';
            $('div#avatarslist ul').append('<li class="'+additional_class+'" id="'+config.settings.li_id+"_"+i+'" avatarid="'+icons[i].gamatarid+'">'+ remove + indicator + icon + '</li>');
            $("div#avatarslist ul li a").ifixpng();
        }

        var paging = SPI.paginatorString(icons.length, page, config.settings.itemsPerPage, config.settings.maxPages, that.renderList, {next: config.langStrings.next, prev: config.langStrings.prev, separator: config.langStrings.separator} );
		$(".pagination").empty();
        if (paging != '') { $("#pagination_top").append(paging); $("#pagination_bottom").append(paging.clone(true)); }

        if( that.selectedAvatarId != null ) {
            //$('div#avatarslist ul li#'+that.selectedAvatarId).addClass('active');
            $('div#avatarslist ul li[avatarid='+that.selectedAvatarId+']').addClass('active');
        }

        $('div#avatarslist ul li a.removeAvatar').click(function(){
           var avatarId = parseInt( $(this).attr('avatarid') );
           if( confirm( SPI._langStrings.avatars.confirm_delete+'' ) ) {
                removeAvatar(avatarId, function(data){
                    if( data === true ) {
                        removeAvatarFromList( avatarId );
                        that.renderList();
                    } else {
                        $('div#avatarslist ul li a.delprogress[avatarid='+avatarId+']').hide();
                    }
                });
           }
           return false;
        });
        $('li[avatarid='+that.avatar+']').addClass('active'); // girls concept => active=selected
        attachAvatarHovers();
    };

    var removeAvatar = function(id, callback) {
        if( id > 0 ) {
            $.ajax({
    			global: false,
    			cache: false,
    			beforeSend: function() {
                    $('div#avatarslist ul li a.delprogress[avatarid='+id+']').show();
                },
    			timeout: config.settings.timeout,
    			url: SPI.sprintf(config.settings.avatar_url_delete, id),
                type: 'POST',
                dataType: 'json',
                success: handleDeleteResponse,
                error: function(xml, mesg, error) { handleDeleteResponse.call(this, {"gamatar":[]}, ''); },
                after_call: callback,
                data: {
                    username: $.profilar.forService().username,
                    hash: $.profilar.forService().hash,
    				outputtype: 'json'
                }
            });
        }
    };

    var handleDeleteResponse = function(data, mesg) {
        var delSuccess = false;
		if( data.gamatar && data.gamatar.errorcode == 0 ) { // success
            delSuccess = true;
        }
        this.after_call( delSuccess );
    };

    var selectAvatar = function( id ) {
        var id = parseInt(id);
        if( id != that.selectedAvatarId ) {
            var imageTemplateBig = '<img src="' + SPI.sprintf(SPI._settings.global.avatar_url_big, id) + '" border="0" width="%1$s" height="%1$s" alt="" style="display:none;" />';
            var imageTemplateSmall = '<img src="' + SPI.sprintf(SPI._settings.global.avatar_url_small, id) + '" border="0" width="%1$s" height="%1$s" alt="" style="display:none;" />';
            var image1 = SPI.sprintf(imageTemplateBig, 150);
            var image2 = SPI.sprintf(imageTemplateSmall, 50);
            var image3 = SPI.sprintf(imageTemplateSmall, 20);
            $('div#avatarselected div.picture1').empty().attr('id', 'avatarid_'+ id).append(''+image1);
            $('div#avatarselected div.picture1 img').fadeIn();
            $('div#avatarselected div.picture2').empty().append(''+image2);
            $('div#avatarselected div.picture2 img').fadeIn();
            $('div#avatarselected div.picture3').empty().append(''+image3);
            $('div#avatarselected div.picture3 img').fadeIn();
        }
        that.selectedAvatarId = id;
    };

    var loadUserAvatar = function() {
        var id = $.profilar.getPref('avatar');
        if( id != '' ) {
            that.avatar = parseInt(id);
            var imageTemplateBig = '<img src="' + SPI.sprintf(SPI._settings.global.avatar_url_big, id) + '" border="0" width="%1$s" height="%1$s" alt="" style="display:none;" />';
            var imageTemplateSmall = '<img src="' + SPI.sprintf(SPI._settings.global.avatar_url_small, id) + '" border="0" width="%1$s" height="%1$s" alt="" style="display:none;" />';
            var image1 = SPI.sprintf(imageTemplateBig, 150);
            var image2 = SPI.sprintf(imageTemplateSmall, 50);
            var image3 = SPI.sprintf(imageTemplateSmall, 20);

            $('div#avatarselected div.picture1').empty().attr('id', 'DEFAULT').append(''+image1);
            $('div#avatarselected div.picture1 img').fadeIn();
            $('div#avatarselected div.picture2').empty().append(''+image2);
            $('div#avatarselected div.picture2 img').fadeIn();
            $('div#avatarselected div.picture3').empty().append(''+image3);
            $('div#avatarselected div.picture3 img').fadeIn();
        } else {
            setDummyAvatar();
        }
    };

    var clearUserAvatar = function(callback) {
        $.profilar.setPref('avatar', '');
        $.profilar.submitPref(function(errors){
            if( typeof callback == "function" ) {
                callback.call(this, false);
            }
        });
     };

    var setAsAvatar = function(id) {
        var avatar_id = parseInt(id);
        if( avatar_id>0 ) {
            avatar_id = '' + avatar_id;
            $.profilar.setPref('avatar', avatar_id );
            $.profilar.submitPref(function(errors) {
                if (errors) {
                    SPI.flashMessage.set(config.langStrings.error_connection, true);
                } else {
                    SPI.flashMessage.set(config.langStrings.avatar_saved);
                }
                window.top.location.href=config.settings.redirect_url;
            });
        }
    };

    // avatar uploader functions

    // calculates new image width and height to feet image into edit frame
    that.calculateDim = function (x,y){
        ratio = x / y;
        if (x > maxx || y > maxy) {
            x1 = maxx;
            y1 = Math.ceil(maxx/ratio);
            y2 = maxy;
            x2 = Math.ceil(maxy*ratio);
            if (x1<=maxx && y1<=maxy) {
                newx = x1;
                newy = y1;
            } else {
                newx = x2;
                newy = y2;
            };
        } else {
            newx = x;
            newy = y;
        };
        // new image dimmensions
        return [newx,newy];
    };

    // onchange callback function from Jcrop - set image mask coords in SPI.avaters object
    that.setCropMask = function(mask){
        _cropObj = mask;
    };

    // ajax callback for cropAvatar function
    that.cropAvatarHandler = function(data){
        $('a#cropavatar').click(function(){SPI.avatars.cropAvatar();});
        if (data.type == 0){
            SPI.avatars.init( avatarsArray, function(){ SPI.avatars.hidePopup(); $('li[avatarid='+data.message.id+'] a.avatar').click()} );
        }else SPI.avatars.showCropError();
        $('.cropIndicator').css('display','none');
        return false;
    };

    // send crop request to imageupload_controller
    that.cropAvatar = function(){
        $('.cropIndicator').css('display','block');
        $('a#cropavatar').unbind('click');

        // url for imageupload controller, action resizeimage
        url = SPI.sprintf('/ir/%d/%d/%d/%d/%d',_id,_cropObj.x,_cropObj.y,_cropObj.w,_cropObj.h);
        $.ajax({
            global: false,
            cache: false,
            type: 'POST',
            url: url,
            dataType: 'json',
            success: SPI.avatars.cropAvatarHandler,
            error: SPI.avatars.showCropError
        });
        return false;
    };

    // ajax callback for avatarFileUpload function
    that.avatarUploadHandler = function(data, status){
        if (data.type==0){
            // no errors response
            // set image into preview frame
            newDim = SPI.avatars.calculateDim(data.message.width,data.message.height);
            _newDim = newDim;
            _id = data.message.id;
            imgPrev = SPI.sprintf(SPI._settings.global.avatar_url_big,data.message.id);
            $('.avatarImagePreview p,.avatarImagePreview img').css('display','none');
            $('.avatarImagePreview').append('<div class="avatarImageHolder" style="width:'+newDim[0]+'px;height:'+newDim[1]+'px;"></div>');
            $('div.avatarImageHolder').css('margin-top',Math.ceil((175 - newDim[1])/2)+10+'px');
            $('div.avatarImageHolder').append('<img class="avatarPreview" width="'+newDim[0]+'" height="'+newDim[1]+'" src="'+imgPrev+'">');
            crpsize = Math.floor(Math.min(newDim[0],newDim[1])*0.8);
            crpx = Math.round((newDim[0] - crpsize)/2);
            crpy = Math.round((newDim[1] - crpsize)/2);
            // coords of default mask
            _setSelectArr = [ crpx, crpy, crpx+crpsize, crpy+crpsize ];
            // Jcrop init
            _jcropObj = $.Jcrop('div.avatarImagePreview img.avatarPreview',{
                //lock ration
                aspectRatio: 1,
                // max selection size
                maxSize: [data.message.width,data.message.height],
                // only corner handles
                sideHandles: false,
                //no keyUp functions
                keySupport: false,
                //disable possibility to remove crop mask
                allowSelect:false,
                minSize: [5,5],
                minSelect:[5,5],
                //true image dimmensions used to rescale crop mask inside Jcrop
                trueSize:[data.message.width,data.message.height],
                //callback function when user moves mask
                onChange:SPI.avatars.setCropMask,
                //set default mask
                setSelect:  _setSelectArr
            });
            $('.avatarUpload').hide();
            $('.avatarCrop').show();
        }else{
            // erros from imageupload_controller
            // File to big
            if (data.type==413) that.avatarUploadErrorHandler(413); else
            // not PNG, GIF, JPG
            if (data.type==1 && data.message == 'Incorrect file') that.avatarUploadErrorHandler(1); else{
                // Nginix 413 error
                resp = data+'';
                if(resp.indexOf('413')) that.avatarUploadErrorHandler(413);else {
                    //all other errors 500,503 etc....
                    that.avatarUploadErrorHandler(0);
                }
            }

        };
    };

    that.resetCrop = function(){
        //clean popup for next upload
        $('div.avatarCrop').hide();
        $('div.avatarUpload').show();
        $('input#avatarFile').before('<input type="file" name="avatar" id="avatarFile">').remove();
        $('div.avatarImagePreview *').not('p').not('span').not('br').not('img.uploadIndicator').remove();
        $('div.avatarImagePreview p').show();
        $('div.avatarImagePreview img').css('display','none');
    };

    // display error field for image upload
    that.showUploadError = function(msg){
        $('.uploadFileInfo').hide();
        $('.uploadFileError').html(msg);
        $('.uploadFileError').show();
    };

    // hide error field for image upload
    that.hideUploadError = function(msg){
        $('.uploadFileInfo').show();
        $('.uploadFileError').html('').hide();
    };

    // display error field for image crop
    that.showCropError = function(){
        $('.uploadFileInfo').hide();
        $('.uploadFileError').html('pierdut').show();
    };

    // hide error field for image crop
    that.hideCropError = function(msg){
        $('.cropFileInfo').show();
        $('.cropFileError').html('').hide();
    };

    // append correct msg for error code
    that.avatarUploadErrorHandler = function(e){
        switch (e){
            case 413:
                that.showUploadError(SPI._langStrings.avatars.au_error_file_to_big);
                break;
            case 1:
                that.showUploadError(SPI._langStrings.avatars.au_error_incorrect_file);
                break;
            default:
                that.showUploadError(SPI._langStrings.avatars.au_error_connection);
                break ;
        };
    };

    //  upload button function
    that.avatarFileUpload = function(){
        that.hideUploadError();
        $(".avatarImagePreview img").ajaxStart(function(){
            $(this).css('display','block');
            $('a#uploadavatar').unbind('click');
        }).ajaxComplete(function(){
            $(this).css('display','none');
            $('a#uploadavatar').click(function(){SPI.avatars.avatarFileUpload();return false;});
        });

        // ajax upload of file field from plugin
        $.ajaxFileUpload({
            url:'/iu/',
            secureuri:false,
            //input file element id
            fileElementId:'avatarFile',
            dataType: 'json',
            success:SPI.avatars.avatarUploadHandler,
            error:function(){SPI.avatars.avatarUploadErrorHandler(0)}
        });
        return false;
    };

    // show upload popup
    that.raisePopup = function(){
        //cleanup
		that.hideUploadError();
		that.hideCropError();
        that.resetCrop();
        //calculate popup position (centered in height)
        var myWidth = 0, myHeight = 0;
        if( typeof( window.innerWidth ) == 'number' ) {
            //Non-IE
            myWidth = window.innerWidth;
            myHeight = window.innerHeight;
        } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
            //IE 6+ in 'standards compliant mode'
            myWidth = document.documentElement.clientWidth;
            myHeight = document.documentElement.clientHeight;
        } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
            //IE 4 compatible
            myWidth = document.body.clientWidth;
            myHeight = document.body.clientHeight;
        };

        //only for loggedin users
        if ($.profilar.loggedIn()){
            newmargin = Math.round((parseInt(myHeight) - 225)/2);
            if (newmargin < 0) newmargin = 0;
            //all things that has to be hidden when popup is shown
            _objectstohide = $('object:visible').add('#flashobj_mc').add('#gameiframe_js');
            $(_objectstohide).each(function(){$(this).css('visibility','hidden')});
            $('div.avataruploadWrapper').css('margin-top',newmargin+'px');
            $('div#avataruploadshadow').css('display','block');
        };
    };

    that.hidePopup = function(){
        that.resetCrop();
        $('div#avataruploadshadow').css('display','none');
        $(_objectstohide).each(function(){$(this).css('visibility','visible')});
    };

    return that;
})();
;/**
 * Cookie based last played games system.
 *
 * Requires jQuery >=1.2.6 and SPI.gamesCookieProxy!
 *
 * @author Radek Jeruzal
 * @author Rafał Jońca (new paginator, fixes, converting to SPI object)
 *
 */
SPI.myGames = (function() {
    var config = {settings: {
            game_url: '/gamedata/%s.json',
            timeout: 7000,
            li_id: 'mygame',
            splitter: '.',
            maxGames: 100,
            gamesPerPage: 25,
            gamesPerPageShort: 15,
            maxPages: 5
        }
    };

    var localData = {
        games: null,//mygamesArray
        targetUser:null,
        currentRender: null,
        currentPage: null
    };

	var that = {};

	//load games and return games array
    var loadGames = function(data) {
        try {
            if (data == null || data == '') {
                data = [];
            } else {
                data = data.split(config.settings.splitter);
                for (var i=0;i<data.length;++i) {
                    data[i] = parseInt(data[i]);
                }
            }
        } catch (e) {
            data = [];
        }
        return data;
    };

    SPI.getAndUpdateConfig('myGames', config);
    //var cookieApi = new SPI.gamesCookieProxy({cookieName: config.settings.cookieName});

    that.init = function(callback,params,targetuser){
        if (localData.targetuser || localData.games){
            callback.call(this,params);
            return;
        };
        localData.targetuser = targetuser;
        //for logged in user
        if (localData.targetuser == null){
            if( $.profilar.loggedIn() ) {
                $.profilar.loadPref(function() {
                   localData.games = loadGames($.profilar.getPref('mygames'));
                   callback.call(this,params);
                }, ['mygames']);
            } else {
                callback.call(this,params);
            }
        }else{
            $.profilar.loadExternalPrefs([localData.targetuser],function(data,errors) {
               targetUsertmpgames = data[0].mygames || '';
               localData.games = loadGames(targetUsertmpgames);
               callback.call(this,params);
            }, ['mygames']);
        };
        return;
    };




    var loadGame = function(gameId, ndx, currentpage) {
        SPI.gameCache.getGame( gameId,function(obj) {
            if (obj == null || obj['is_available'] === false){
                if(currentpage!=-1){
					var html = SPI.render(config.templates.faves_error, {gameId: gameId});
				} else {
					var html = config.langStrings.notAvailable;
				}
				$("#"+config.settings.li_id+"_"+ndx).html(html);
            }else{
                obj.new_one = obj['new'];
		        obj.gameId = gameId;
                var a = $(SPI.render((currentpage==-1?config.templates.home:config.templates.faves), obj)).ntooltip({
                    extraClass: 'pretty',
                    showBody: "| ",
                    fancyImages: SPI._settings.tooltipFancyImagesArray
                }).spiIeh();
                $("#"+config.settings.li_id+"_"+ndx).empty().append(a);
            };
        });
    };

    var loadGameMyProfile = function(gameId, ndx, currentpage) {
        SPI.gameCache.getGame( gameId,function(obj) {
            if (obj == null || obj['is_available'] === false){
                var obj = new Object();
                obj.gameId = gameId;
                obj.active = false;
                gameMyProfileFillTemplateFields("#"+config.settings.li_id+"_"+ndx+"_"+currentpage, obj);
            }else{
                if (obj.id) {
                    obj.active = true;
                } else {
                    obj.active = false;
                }
                obj.new_one = obj['new'];
                obj.gameId = gameId;
                gameMyProfileFillTemplateFields("#"+config.settings.li_id+"_"+ndx+"_"+currentpage, obj);
            };
        });
    };

    var fixOnclick = function(gamelink) {
    	var g = {};
        if (gamelink.indexOf('onclick')) {
            g.onclick = gamelink.match('onclick="(.*?)"');
            g.href = gamelink.replace(/\s*onclick=".*?"\s*/,'');
        }
        g.href = g.href.replace('<a href="', '').replace('"', '');
        return g;
    };

    var gameMyProfileFillTemplateFields = function(placeholder, game) {
        var currentPage = localData.currentPage;

        if (currentPage > 1) {
            var endsGames =
                localData.games.length -
                ((currentPage-1)*config.settings.gamesPerPage);

            // last game on the current page
            if (endsGames == 1) {
                --currentPage;
            }
        }

        // Set delete button
        $(placeholder + " .gameDelete").click(
            (
                function(gameId, currentPage) { 
                    return function (e) {
                        if(confirm(SPI._langStrings.myGames.removeConfirmation)) {
                            SPI.myGames.removeFromMyGames(gameId);
                            SPI.myGames.renderAtMyfavesPage(currentPage);
                        }
                        e.preventDefault();
                    };
                }
            )(game.gameId, currentPage)).show();

        if (game.active) {
            // Set link
            var g = fixOnclick(game.gamelink);
            gameLink = g.href;
            var onclick_body = g.onclick;
            // New label
            if (game.new_one) {
                $(placeholder +" gameNew").show();
            }
        } else {
            game.title = config.langStrings.gameNotFound;
            game.game_description = config.langStrings.gameNotFound;
            game.subcategory_name = config.langStrings.gameNotFoundDescription;
            game.rating2 = 0;
            game.thumbnail = '/img/userprofile/gameNotFound.gif';
            var gameLink = "javascript:void(0);";
        };

        // Game thumb
        $(placeholder +" .gameTitle").html(game.title).show();

        $(placeholder +" .gameThumb").attr("src", game.thumbnail).show();

        // Set link and show item
        var gameItem = $(placeholder +" .profileGameItem").attr("href", gameLink).css("display", "block");
        if (onclick_body) {
            gameItem.click(
                new Function(onclick_body[1])
            );
        }

        // Tooltip and ellipsis
        $(placeholder +" .tooltipDescription").html(game.game_description);
        $(placeholder +" .tooltipSubcategory").html(game.subcategory_name);
        $(placeholder +" .tooltipRatingValue").html(game.rating2);
        $("#favorite-list-myprofile li#"+placeholder).dEllipsis({
            overflowElement:'a span.gameTitleOverflow',
            textElement:'a span.gameTitle',
            shortSteps: true,
            wrapInWidth: true
        });
        $('#favorite-list-myprofile li#'+placeholder+'.ttR').dTooltip({
            eventHandler:'a.profileGameItem',
            displayDiv: 'tltright',
            content:'.tltcontent',
            track:true,
            position:'right',
            x: -216,
            y: 5,
            drawItemCallback: 'drawNeboxItem'
        });
        $('#favorite-list-myprofile li#'+placeholder+'.ttL').dTooltip({
            eventHandler:'a.profileGameItem',
            displayDiv: 'tltleft',
            content:'.tltcontent',
            track:true,
            position:'left',
            x: 10,
            y: 5,
            drawItemCallback: 'drawNeboxItem'
        });
        $('#favorite-list-myprofile li#'+placeholder+' img').attr('alt','').attr('title','');
        $('#favorite-list-myprofile li#'+placeholder+' a').attr('alt','').attr('title','');
        // /Tooltip

        // Remove indicator
        $(placeholder +" .indicator_fav").remove();
    };

    var loadGameUserProfile = function(gameId, ndx, currentpage) {
        SPI.gameCache.getGame( gameId,function(obj) {
            if (obj == null || obj['is_available'] === false){
				var html = $(SPI.render((config.templates.userprofile_error), {game_Id:gameId,error:config.langStrings.notAvailable}));
				$("#"+config.settings.li_id+"_"+ndx).html(html);
            }else{
        	// clever tooltip after ajax
           obj.new_one = obj['new'];
		   obj.gameId = gameId;
           // clever tooltip after ajax
           var a = $(SPI.render((config.templates.userprofile), obj)).ntooltip({
                extraClass: 'pretty',
                showBody: "| ",
                fancyImages: SPI._settings.tooltipFancyImagesArray
            }).spiIeh();
           $("#"+config.settings.li_id+"_"+ndx).empty().append(a);
        };
        });
    };


    that.hasGames = function() {
        return; //cookieApi.loadGames().length > 0;
    };

    that.renderMyGames = function(page) {
    	if (games.length == 0) {
			return;
    	}

    	$("ol#favorite-list").empty();

        var sitesQuantity = Math.ceil(games.length/config.settings.itemsPerPage);

        // Real assigning.
        for (var i=(page*config.settings.itemsPerPage)-config.settings.itemsPerPage; i<(page*config.settings.itemsPerPage) && i<games.length; i++) {
            $('ol#favorite-list').append('<li id="'+config.settings.li_id+"_"+i+'">'+config.langStrings.loading+'</li>');
            loadGame(games[i], i, page);
        }

    	// Display pagination
        var paging = SPI.paginatorString(games.length, page, config.settings.itemsPerPage, config.settings.maxPages, that.renderMyGames, config.langStrings);
		$("#paging_center").empty();
        if (paging != '') {
            $("#paging_center").append(paging);
        }

		return false;
    };

    that.convertGames = function() {
        var savedgames = $.cookie(config.settings.cookieName) || '';
        if( savedgames != '' ) {
            $.profilar.setPref('mygames', savedgames );
            $.profilar.submitPref(function(errors) {
                if (errors) {} else {
                    $.cookie(config.settings.cookieName, null);
                }
            });
        };
    };

    that.renderAtHomePage = function() {
        if( $.profilar.loggedIn() ) {
                localData.currentRender = 'renderAtHomePage';
                localData.currentPage = 0;
                var games = localData.games;

            	if(games.length == 0) {
            	    $('#favorite_box .moreIn').hide();
                   	return;
        		};

                if (games.length < 7){
                    $('#favorite_box .moreIn').css('display','none');
                };
        		// Remove the default text.
                $('.no-faves-text').remove();

                // Real assigning.
                for (var i=0; i<config.settings.itemsAtHomePage && i<games.length; i++) {
                    $('#favorite_box ol').append('<li id="'+config.settings.li_id+"_"+i+'">'+config.langStrings.loading+'</li>');
                    loadGame(games[i], i, -1);
                };
        } else {
            $('.no-faves-text').text( config.langStrings.not_logged_in ).show();
        };
    };

    var myGames;
    var allMyGames;

    var showMyGame = function(gameId, gamePos) {
        var game = myGames[gameId];

        var cssDescriptor = '#profileGameFrame'+gamePos;

        //show delete link
        var deleteHref =
            "javascript:if(confirm('"+SPI._langStrings.myGames.removeConfirmation+"')){SPI.myGames.removeFromMyGames("+
            game.gid+");"+
            "SPI.myGames.renderAtMyprofilePage();}";
        $(cssDescriptor+" .gameDelete").attr("href", deleteHref);
        $(cssDescriptor+" .gameDelete").show();

        if (!game.active) {
            game.title = config.langStrings.gameNotFound;
            game.game_description = config.langStrings.gameNotFound;
            game.subcategory_name = config.langStrings.gameNotFoundDescription;
            game.rating2 = 0;
            game.thumbnail = '/img/userprofile/gameNotFound.gif';
            game.isNew = false;
            var gameLink = "javascript:void(0);";
        } else {
             var g = fixOnclick(game.gamelink);
             gameLink = g.href;
             var onclick_body = g.onclick;
        }

        //fill in tooltip
        $(cssDescriptor+" .tooltipDescription").html(
            game.game_description
        );
        $(cssDescriptor+" .tooltipSubcategory").html(
            game.subcategory_name
        );
        $(cssDescriptor+" .tooltipRatingValue").html(
            game.rating2
        );

        cssDescriptor += " .profileGameItem";

        //set game link
        $(cssDescriptor).attr("href", gameLink);

        if (game.thumbnail != "") {
            //set thumbnail
            $(cssDescriptor+" .gameThumb").attr("src", game.thumbnail);
        }


        //set title
        $(cssDescriptor+" .gameTitle").html(game.title);
        //set new label
        if (game.isNew) {
            $(cssDescriptor+" .gameNew").show();
        }

        //show the game
        $(cssDescriptor).show();
        if (onclick_body) {
            $(cssDescriptor).click(
                new Function(onclick_body[1])
            );
        }
    };

    var showMyGames = function() {
        var showedGames = 0;
        var finished    = false;

        //show the games in the same order as profilar suggested
        for (var i = 0; (i < allMyGames.length) && !finished; ++i) {
            var gameId = allMyGames[i];

            //search the given game
            for (var j = 0; j < myGames.length; ++j) {
                if (myGames[j].gid == gameId) {
                    showMyGame(j, showedGames++);

                    if (showedGames >= 2) {
                        finished = true;
                        break;
                    }
                }
            }
        }

        $("#myFavGamesBox li").dEllipsis({
            overflowElement:'a span.gameTitleOverflow',
            textElement:'a span.gameTitle',
            shortSteps: true,
            wrapInWidth: true
        });
    };

    that.renderAtMyprofilePage = function() {
        //clear all the box
        $("#myFavGamesBox .gameDelete").hide();
        $("#myFavGamesBox .profileGameItem").hide();
        $("#myFavGamesBox .gameNew").hide();

        myGames    = new Array();
        allMyGames = localData.games;

        var games       = localData.games;
        var gamesToLoad = Math.min(games.length, 2);
        var n           = gamesToLoad;

        //run {n} asynchronous requests
        for (var i = 0; i < n; ++i) {
            SPI.gameCache.getGame(games[i], (function(gid){
                return function(game) {
                    if (game != null && game['is_available'] === true) {
                        game.active = true;
                    } else {
                        game        = {};
                        game.gid    = gid;
                        game.active = false;
                    }

                    myGames.push(game);

                    //no more games to load
                    if (--gamesToLoad == 0) {
                        showMyGames();
                    }
                }
            })(games[i]));
        }
        $(".moreLinkFavorites").text(SPI.sprintf($(".moreLinkFavorites").text(), allMyGames.length));
    };

    that.renderAtUserprofilePage = function() {
        localData.currentRender = 'renderAtUserprofilePage';
        localData.currentPage = 0;
        $('.myfavesmorelink').hide();
        var games = localData.games;
        if(games.length == 0) {
            $('#usersfaves').empty();
            for(i=1;i<=5;i++){
                $('#usersfaves').append('<li class="no-myfaves-empty"></li>');
            };
            //$('#usersfaves').append('<li class="no-myfaves-text">'+SPI._langStrings.myfaves.no_faves_yet+'</li>');
            $('.myfavesmorelink').hide();
            return;
        };

        $('#usersfaves').empty();
        // Remove the default text.
        $('.no-faves-text').remove();

        // Real assigning.
        for (var i=0; i<5 && i<games.length; i++) {
            $('#usersfaves').append('<li id="'+config.settings.li_id+"_"+i+'">'+config.langStrings.loading+'</li>');
            loadGameUserProfile(games[i], i, -1);
        };
    };

    that.renderAtMyfavesPage = function(page) {
        localData.currentRender = 'renderAtMyfavesPage';
        localData.currentPage = page || 1;
        if(!page) {
            page = localData.currentPage;
        }
        var gamesPerPage = config.settings.gamesPerPage;
        var games = localData.games;

        // No fav games? Show invitation bar and less games placeholders.
        if(games.length == 0) {
            gamesPerPage = config.settings.gamesPerPageShort;
            $("#middlePinkBoxSmall").addClass("pinkShort");
            localData.targetuser ? $("#additionalBox").hide() : $("#additionalBox").show();
        };

        // Build placeholders for games
        $('#favorite-list-myprofile').empty();
        for (i = 0; i < gamesPerPage; i++) {
            var tt_class = "ttL";
            if ((i+1) % 5 == 0){
                tt_class = 'lastInRow ttR';
            } else if ((i + 1) % 5 == 4){
                tt_class = 'ttR';
            } else {
                tt_class = 'ttL';
            }
            var empty_html = $(SPI.render(config.templates.myprofile_empty, {li_id: config.settings.li_id, ndx: i+"_"+page, ttclass: tt_class}));
            $('#favorite-list-myprofile').append(empty_html);
        };

        // Hide some data in empty placeholders
        $("#favorite-list-myprofile .gameDelete").hide();
        $("#favorite-list-myprofile .profileGameItem").hide();
        $("#favorite-list-myprofile .gameNew").hide();

        // No fav games? Leaving.
        if(games.length == 0) {
            return;
        };

        // Real assigning.
        pageGames = games.slice((parseInt(page)-1)*gamesPerPage,(parseInt(page)-1)*gamesPerPage + gamesPerPage);
        while(pageGames.length == 0 || page <=0){
            page --;
            pageGames = games.slice((parseInt(page)-1)*gamesPerPage,(parseInt(page)-1)*gamesPerPage + gamesPerPage);
        };

        localData.currentPage = page;

        for (var i=0; i<pageGames.length; i++) {
            $("#"+config.settings.li_id+"_"+i+"_"+page).append($("#"+config.templates.myprofile_indicator).html());
            loadGameMyProfile(pageGames[i], i, page);
        };

        // Display pagination
        var paging = SPI.paginatorString(games.length, page, gamesPerPage, config.settings.maxPages-1, that.renderAtMyfavesPage, config.langStrings);
        $(".pagination").empty();
        if (paging != '') {
            $("#pagination_top").append(paging);
            $("#pagination_bottom").append(paging.clone(true));
            var totalPages = Math.ceil(games.length / gamesPerPage);
            $("#pagination_pages_top, #pagination_pages_bottom").html(SPI.sprintf(SPI._langStrings.sf_global.pagination_counter,page,totalPages));
        };
    };

    that.isAdded = function(gameid) {
        return $.inArray(gameid, localData.games) != -1;
    };

    that.addToMyGames = function(title, gameid) {
			var mygames = localData.games;
			if ($.inArray(gameid, mygames) != -1) {
				alert(SPI.sprintf(config.langStrings.alreadyInMyGames, title));

				return;
			} else {
				// add new mygame to (array)mygames
				mygames.unshift(gameid);
				// if more games than max, throw away the last one
				if (mygames.length > config.settings.maxGames) {
					mygames = mygames.slice(0, config.settings.maxGames);
				}
				localData.games = mygames;
				mygames = mygames.join(config.settings.splitter);
				// save (array)mygames to profilar
				$.profilar.setPref('mygames', mygames );
				$.profilar.submitPref(function(errors) {
					if (errors) {
						alert('2'+config.langStrings.error_html);
						return;
					}
                });
				alert(SPI.sprintf(config.langStrings.addedToMyGames, title));
                $('#game-add').hide();
                $('#game-added').show();
            };
    };

    that.removeFromMyGames = function(gameid, gamename) {
        if (localData.targetuser == null){
            var mygames = localData.games;
            if ($.inArray(gameid, mygames) == -1) {
                return;
            } else {
                mygames.splice($.inArray(gameid, mygames),1);
                localData.games = mygames;
                mygames = mygames.join(config.settings.splitter);
                // save (array)mygames to profilar
                $.profilar.setPref('mygames', mygames );
                $.profilar.submitPref(function(errors) {
                    if (errors) {
                        alert(config.langStrings.error_html);
                        return;
                    }
                });
                if (gamename) {
                    alert(SPI.sprintf(
                        config.langStrings.removedFromMyGamesWithName,
                        gamename
                    ));
                } else {
                    alert(SPI._langStrings.myGames.removedFromMyGames);
                }
            };
        };
    };

    that.getCountForUser = function(username,callback){
        if( $.profilar.loggedIn() ) {
            $.profilar.loadPref(function() {
               var games = loadGames($.profilar.getPref('mygames'));
               callback.call(this, games);
            }, ['mygames']);
        } else {
            callback.call(this);
        };
    };

	return that;
})();
;/**
 * Spil Games Ajax high score - SPI plugin
 * @author: Rafał Jońca and nez
 *
 * Usage: SPI.highscore.init(options);
 *
 */
SPI.highscore = (function($){
    var config = {settings: {
        timeout: 3000,
        ajaxCacheGeneral: true,
        ajaxCacheUser: true,
        ajaxCacheUserHighscore: true,
        highscorebox_title_length: 16,
		usernameLenght: 14,
		anonymousIcon: '/img/userprofile/dummy_small.gif'
    }};

    var that = {};
    var currentView;
    var userScores = [];
    var currentScore = {};
    var canClick = true;
	var maxItemsToShow = 10;
	var lastGeneralCopy = {};
	var firstpositionPoints = 0;
    var tenthPositionPoints = 0;
    var userBest = {
        score: 0,
        position: 0
    };

	var calculateFarPosition = function(score, forActualScore) {
        var forActualScore = forActualScore || false;
		var position = 0;

		for (var i in lastGeneralCopy) {
			if (parseInt(score) > parseInt(lastGeneralCopy[i].score)) {
				position = parseInt(lastGeneralCopy[i].position);
				break;
			} else if (parseInt(score) == parseInt(lastGeneralCopy[i].score)) {
				position = parseInt(lastGeneralCopy[i].position) + (forActualScore ? 0 : 0);
				// Break if the next one is different
                var j = parseInt(i) + 1;
				if (lastGeneralCopy[j] !== undefined && parseInt(score) != parseInt(lastGeneralCopy[j].score)) break;
			}
		}
		if (position <= maxItemsToShow) {
			if (lastGeneralCopy.length <= maxItemsToShow) {
				position = maxItemsToShow+1;
			} else if (typeof(lastGeneralCopy.length) != 'undefined') {
				position = parseInt(lastGeneralCopy[lastGeneralCopy.length-1].position)+1;
			}
		}
		if (position > 100) {
			position = '' + position + '+';
		}
		return position;
	};

    /*
    var updateLoginBarAndMaxToShow = function(kind) {
		var loginBar = $('#highscore_box div.loginbar');
		loginBar.empty();

		switch (kind) {
			case 'normal_logged':
				maxItemsToShow = 10;
				break;
			case 'unlock_logged':
				maxItemsToShow = 10;
				break;
			case 'normal_guest':
				maxItemsToShow = 8;
				loginBar.append('<p id="ha_hs_normal_guest">'+config.langStrings.not_logged_in_info + '</p>' );
				var login = $(SPI.render(config.templates.login_trigger, {above_text: config.langStrings.not_logged_info, did: 'ha_highscore_login'}));
				$('a.login', login).hover(function() {$(this).next().addClass('hover');},function() {$(this).next().removeClass('hover');});
				loginBar.append(login);
				break;
			case 'unlock_guest':
				maxItemsToShow = 9;
				var login = $(SPI.render(config.templates.login_trigger, {above_text: config.langStrings.not_logged_warning, did: 'ha_highscore_login'}));
				$('a.login', login).hover(function() {$(this).next().addClass('hover');},function() {$(this).next().removeClass('hover');});
				loginBar.append(login);
				break;
		}
    };
    */


    var calculateFinalArray = function(general, user, callback) {
        var users = [],
            items = [],
            skip11 = false;

		if (general.hyscor[currentView] !== undefined && general.hyscor[currentView].result) {
			lastGeneralCopy = general.hyscor[currentView].result.concat();
		} else {
			lastGeneralCopy = {};
		}

        if( general.hyscor && general.hyscor[currentView] && general.hyscor[currentView].result.length > 0 ) {
            items = general.hyscor[currentView].result.splice(0, maxItemsToShow);
            for( var i in items ) {
                items[i].avatar_url = config.settings.noimage;
                items[i].current = false;
                if( items[i].authenticated == '1' ) {
                    users.push( items[i].username );
                }
            }
        }

        if( users.length>0 ) {
            $.profilar.loadExternalPrefs( users, function(data, errors) {
                    for( var j in items ) {
                        for( var k in data ) {
                            if( data[k].username && data[k].username.toLowerCase() == items[j].username.toLowerCase() && data[k].avatar && data[k].avatar != '' && data[k].avatar != undefined ) {
                                items[j].avatar_url = SPI.sprintf( SPI._settings.global.avatar_url_small, data[k].avatar ) || config.settings.noimage;
                            }
                            items[j].current = ($.profilar.forService().username.toLowerCase() == items[j].username.toLowerCase());
                            if( items[j].current ) {
                                skip11 = true;
                            }
                        }
                    }
                    if( skip11 == false && user && user.hyscor && user.hyscor[currentView] && user.hyscor[currentView].result.length > 0 ) {

                        var currentUser = user.hyscor[currentView].result[0];
                        currentUser.current = true;
                        var useravatar = $.profilar.getPref('avatar');
                        if( useravatar != '' ) {
                            useravatar = SPI.sprintf( SPI._settings.global.avatar_url_small, useravatar );
                        } else {
                            useravatar = config.settings.noimage;
                        }
                        currentUser.avatar_url = useravatar;
                        items.push( currentUser );
                    }

                    if( items.length > maxItemsToShow+1 ) {
                        items = items.splice(0,maxItemsToShow+1);
                    }

                    // NEZ
                    var myitems = items.concat();
                    var timestampUser = 0;
                    var timestampServer = 0;
                    var timeDelta = 0;

                    if( userScores.length > 0 ) {

                        var userScoresCopy = userScores.concat();

                        for( var i in myitems ) {
                            timestampServer = parseInt( myitems[i].timestamp );

                            if( myitems[i].current == true ) {

                                var currentScore = myitems[i];

                                for( var j in userScoresCopy ) {
                                    timestampUser = parseInt( userScoresCopy[j].timestamp );
                                    timeDelta = Math.abs( timestampUser-timestampServer );

                                    if( currentScore.score == userScoresCopy[j].score && timeDelta <= 10 ) {
                                        // already cached - skip
                                        userScoresCopy.splice(j, 1);
                                    }
                                }
                            }
                        }
                        if( userScoresCopy.length > 0 ) {
                            for( var k in userScoresCopy ) {
                                myitems.push( userScoresCopy[k] );
                            }

                            myitems.sort( sortByScore );
                            updatePositions( myitems );
                            myitems = myitems.splice(0,maxItemsToShow+1);
                            if( myitems.length > maxItemsToShow && myitems[maxItemsToShow].current != true ) {
                                myitems.pop();
                            } else {
                                if( myitems.length > maxItemsToShow ) {
                                for( i=0; i<maxItemsToShow; i++ ) {
                                    if( myitems[i].current == true ) {
                                        myitems.pop();
                                        break;
                                    }
                                }
                                }
                            }
                        }
                    }
                    myitems.sort( sortByScore );
                    updatePositions( myitems );
                    callback.call(this, myitems);

                }, ['avatar']);
        } else {


            if( user && user.hyscor && user.hyscor[currentView] && user.hyscor[currentView].result.length > 0 ) {

                var currentUser = user.hyscor[currentView].result[0];
                currentUser.current = true;
                currentUser.avatar_url = SPI.sprintf( SPI._settings.global.avatar_url_small, $.profilar.getPref('avatar')) || config.settings.noimage;
                items.push( currentUser );
            }

            // NEZ
            var myitems = items.concat();
            var timestampUser = 0;
            var timestampServer = 0;
            var timeDelta = 0;
            if( userScores.length > 0 ) {

                var userScoresCopy = userScores.concat();

                for( var i in myitems ) {
                    timestampServer = parseInt( myitems[i].timestamp );

                    if( myitems[i].current == true ) {

                        var currentScore = myitems[i];

                        for( var j in userScoresCopy ) {
                            timestampUser = parseInt( userScoresCopy[j].timestamp );
                            timeDelta = Math.abs( timestampUser-timestampServer );

                            if( currentScore.score == userScoresCopy[j].score && timeDelta <= 10 ) {
                                // already cached - skip
                                userScoresCopy.splice(j, 1);
                            }
                        }
                    }
                }
                if( userScoresCopy.length > 0 ) {
                    for( var k in userScoresCopy ) {
                        myitems.push( userScoresCopy[k] );
                    }

                    myitems.sort( sortByScore );
                    updatePositions( myitems );
                    myitems = myitems.splice(0,maxItemsToShow+1);
                    if( myitems.length > maxItemsToShow && myitems[maxItemsToShow].current != true ) {
                        myitems.pop();
                    } else {
                        if( myitems.length > maxItemsToShow ) {
                            for( i=0; i<maxItemsToShow; i++ ) {
                                if( myitems[i].current == true ) {
                                    myitems.pop();
                                    break;
                                }
                            }
                        }
                    }
                }
            }
            myitems.sort( sortByScore );
            updatePositions( myitems );
            callback.call(this, myitems);

        }
    };

    // get best score for the CURRENT (logged in) user
    var getUserBest = function(items) {
        if( items && items.length>0 ) {
            for(var i in items) {
                if( items[i].current == true ) {
                    var position;
                    if (i == maxItemsToShow) {
                        position = calculateFarPosition(items[i].score);
                    } else {
                        position = items[i].position;
                    }
                    return {score: items[i].score, position: position };
                }
            }
        }
        return {score: 0, position: 0};
    };

    var getUserActual = function(items, score) {
        if( items && items.length>0 ) {
            for(var i in items) {
                if( items[i].current == true && items[i].score == score ) {
                    var position;
                    if (i == maxItemsToShow) {
                        position = calculateFarPosition(items[i].score, true);
                    } else {
                        position = items[i].position;
                    }
                    return {score: items[i].score, position: position };
                }
            }
        }

        //score
        var farPosition = calculateFarPosition(score, true);
        return {'score': score, position: farPosition};

        //return {score: 0, position: 0};
    };

    // response handler
    var handleResponseGeneral = function(data, mesg) {

        // set cache back
        config.settings.ajaxCacheGeneral = true;

		// If there was an error, mimic that there is no result...
		if (data.hyscor && data.hyscor.errorcode !== undefined) {
			data = {"hyscor":[]};
		}
        this.after_call(data);
    };

    var getGeneralHighscores = function(callback) {
        $.ajax({
			global: false,
			cache: config.settings.ajaxCacheGeneral,
			timeout: config.settings.timeout,
			url: SPI.sprintf(config.settings.url, SPI._settings.global.site_id, config.settings.gameId),
            type: 'GET',
            dataType: 'json',
            success: handleResponseGeneral,
            error: function(xml, mesg, error) { if( mesg == 'timeout' ) { that.renderHighScores(); } else { handleResponseGeneral.call(this, {"hyscor":[]}, ''); } },
            after_call: callback,
            data: {
                group: currentView,
                order: config.settings.order,
                authenticated: '1',
				outputtype: 'json'
            }
        });
    };

    // response handler
    var handleResponseUser = function(data, mesg) {

        // set cache back
        config.settings.ajaxCacheUser = true;

		// If there was an error, mimic that there is no result...
		if (data.hyscor && data.hyscor.errorcode !== undefined) {
			data = {"hyscor":[]};
		}
        this.after_call(data);
    };

    var getUserHighscore = function(callback) {
        $.ajax({
			global: false,
			cache: config.settings.ajaxCacheUser,
			timeout: config.settings.timeout,
			url: SPI.sprintf(config.settings.url, SPI._settings.global.site_id, config.settings.gameId),
            type: 'GET',
            dataType: 'json',
            success: handleResponseUser,
            error: function(xml, mesg, error) { handleResponseUser.call(this, {"hyscor":[]}, ''); },
            after_call: callback,
            data: {
                group: currentView,
                order: config.settings.order,
                authenticated: '1',
				outputtype: 'json',
                username: $.profilar.forService().username,
                hash: $.profilar.forService().hash
            }
        });
    };

    that.getUserLevel = function(callback, targetUser) {
	var getData = { outputtype: 'json' };

	if (targetUser) {
	   getData.targetuser = targetUser;
        } else {
	    getData.username = $.profilar.forService().username;
	    getData.hash = $.profilar.forService().hash;
	}

        $.ajax({
			global: false,
			cache: config.settings.ajaxCacheUser,
			timeout: config.settings.timeout,
			url: config.settings.gamelevelurl,
            type: 'GET',
            dataType: 'json',
            success: function(data){callback.call(this,data)},
            error: function(xml, mesg, error) { handleResponseUser.call(this, {"hyscor":[]}, ''); },
            after_call: callback,
            data: getData
        });
    };


    that.init = function(settings){
        SPI.getAndUpdateConfig('highscore', config, settings);
        currentView = config.settings.defaultView;

        $('div#highscore_box div.viewbar a').live('click', function(){
            if( canClick === true ) {
                canClick = false;
				currentView = ''+ $(this).attr('href').replace(/[^#]*#/g,'');
				$('div#highscore_box div.viewbar a').removeClass('active');
                $('div#highscore_box div.viewbar a').unbind('click');
				that.renderHighScores();
            }
            return false;
        });
        if($.profilar.loggedIn()) $(".highscore_login_info").hide();

	};

	var saveUserScore = function( userscore, timestamp ) {
	    if( userscore>0 ) {
	        var uavatar = $.profilar.getPref('avatar') != '' ? SPI.sprintf( SPI._settings.global.avatar_url_small, $.profilar.getPref('avatar') ) : config.settings.noimage;
            var score = {
                'notLogged': false,
                'position':      1,
                'timestamp':     timestamp+'',
                'username':      $.profilar.get('username'),
                'current':       true,
                'authenticated': 1,
                'score':         userscore,
                'gamelevel':     '',
                'country':       '',
                'avatar_url':    uavatar
            };
            currentScore = score; // for blinking/animation
            userScores.push( score );
            userScores.sort( sortByScore );
        }
    };

    var saveNotLoggedScore = function( userscore, timestamp ) {
	    if( userscore>0 ) {
	        var uavatar = config.settings.anonymousIcon;
            var score = {
                'notLogged': true,
                'position':      1,
                'timestamp':     timestamp+'',
                'username':      config.langStrings.guest,
                'current':       true,
                'authenticated': 1,
                'score':         userscore,
                'gamelevel':     '',
                'country':       '',
                'avatar_url':    uavatar
            };
            currentScore = score; // for blinking/animation
            userScores.push( score );
            userScores.sort( sortByScore );
        }
    };

    var sortByScore = function(a, b) {
        var x = parseInt(a.score);
        var y = parseInt(b.score);
        return (y-x);
    };

    var updatePositions = function( resultsRef ) {
        if( resultsRef.length > 0 ) {
            for( i=0; i<resultsRef.length; i++ ) {
                resultsRef[i].position = i+1;
            }
        }
    };

    var handleNewScore = function(data, mesg) {
		if (data.hyscor && data.hyscor.errorcode !== undefined) {
			return;
		}
        saveUserScore(this.score, data.hyscor.time);

        that.renderHighScores(true, this.score);
    };

    var handleNotLoggedScore = function(data, mesg) {
		if (data.hyscor && data.hyscor.errorcode !== undefined) {
			return;
		}
        saveNotLoggedScore(this.score, data.hyscor.time);
        that.renderHighScores(true);
    };

    that.newScoreCallback = function(score) {
        currentView = 'daily';
        if( score > 0 ) {
            $.ajax({
    			cache: false,
    			timeout: 3000,
    			url: config.settings.timeurl,
                type: 'GET',
                dataType: 'json',
                success: handleNewScore,
                error: function(xml, mesg, error) { handleNewScore.call(this, {"hyscor":[]}, ''); },
                data: { outputtype: 'json' },
                'score': score
            });
        }
    };

    that.notLoggedScoreCallback = function(score) {
        currentView = 'daily';
        if( score > 0 ) {
            $.ajax({
    			cache: false,
    			timeout: 3000,
    			url: config.settings.timeurl,
                type: 'GET',
                dataType: 'json',
                success: handleNotLoggedScore,
                error: function(xml, mesg, error) { handleNewScore.call(this, {"hyscor":[]}, ''); },
                data: { outputtype: 'json' },
                'score': score
            });
        }
    };

    that.drawHighscores = function(scores, unlock) {
        $('div#highscore_box div.highscore_box_content').removeClass('highscore_indicator').empty();
        $('div#highscore_box div.viewbar a.'+currentView).addClass('active');
        var noresults = false;

        if( scores.length > 0 ) {

            $('#highscore_box div.highscore_box_content').append('<ol></ol>');
            var li = '', userscore = '';
            var alreadyOrange = false;
            var j = 1;
            var cuser = '';
            var scoreCheck = true;

            for( var i in scores ) {
                cuser = '';

                if( scoreCheck === true && scores[i].current == true && currentScore.score && currentScore.score > 0 && scores[i].score == currentScore.score ) {
                    cuser = ' cuser="1"';
                    scoreCheck = false;
                }

                if( scores[i].current == true && !alreadyOrange ) {
                    extraClass = ' class="current"';
                    alreadyOrange = true;
                } else {
                    extraClass = '';
                }
				if (i == maxItemsToShow) {
					liData = {
						liExtra: extraClass + cuser,
						position: calculateFarPosition(scores[i].score),
						userLink: (scores[i].notLogged != true && scores[i].authenticated == 1 ? SPI.sprintf(config.settings.userprofile_link, scores[i].username): ''),
						avatarUrl: scores[i].avatar_url,
						username: scores[i].username,
						userNameCutted: SPI.cutStringPlease(scores[i].username, config.settings.usernameLenght),
						score: scores[i].score,
						date: SPI.formatDate( scores[i].timestamp, SPI._langStrings.relative_date_plain )

					};
					$('#highscore_box ol').append(SPI.render(config.templates.game_my_highscore, liData));

				} else {
					liData = {
						liExtra: extraClass + cuser,
						position: scores[i].position || '',
						userLink: (scores[i].notLogged != true && scores[i].authenticated == 1 ? SPI.sprintf(config.settings.userprofile_link, scores[i].username): ''),
						avatarUrl: scores[i].avatar_url,
						username: scores[i].username,
						userNameCutted: SPI.cutStringPlease(scores[i].username, config.settings.usernameLenght),
						score: scores[i].score,
						date: SPI.formatDate( scores[i].timestamp, SPI._langStrings.relative_date_plain )
					};

					$('#highscore_box ol').append(SPI.render(config.templates.game_highscore_li, liData));
				}

                j++;
            }

            $('#highscore_box ol li:even').addClass('odd');
			$('#highscore_box ol li:odd').addClass('even');

        } else {
            noresults = true;
        };

		if( noresults  ) {
			var ecl = '';
			if( !$.profilar.loggedIn() ) {
				ecl = ' not_logged';
			}
			$('#highscore_box div.highscore_box_content').append('<div class="noitems' + ecl + '">' + config.langStrings.no_results + '</div>');
		}

        that.animateCurrentScore(unlock);

        canClick = true;
    };

    that.renderHighScores = function(unlock, unlockedscore) {

        $('div#highscore_box div.viewbar a').removeClass('active');
        $('div#highscore_box div.highscore_box_content').html('&nbsp;').addClass('highscore_indicator');
		//$('#ha_hs_bottom').removeClass('bottom_small_orange');
		//$('#highscore_box').removeClass('hs_orange_bottom');

		/*
		if ($.profilar.loggedIn()) {
			if (unlock) {
				updateLoginBarAndMaxToShow('unlock_logged');
			} else {
				updateLoginBarAndMaxToShow('normal_logged');
			}
		} else {
			if (unlock) {
				updateLoginBarAndMaxToShow('unlock_guest');
			} else {
				updateLoginBarAndMaxToShow('normal_guest');
			}
		}*/

        getGeneralHighscores(function(general) {
            if ($.profilar.loggedIn()) {
                getUserHighscore(function(user) {
                    calculateFinalArray(general, user, function(items) {
                        that.drawHighscores(items, unlock);

                        // INIT GAMEBAR
                        if( currentView == 'daily' ) {
                            // get firstposition points
                            if( items && items[0] ) { firstpositionPoints = parseInt(items[0].score); }

                            //get tenth position points
                            if (items && items[9]) {
                                tenthPositionPoints = parseInt(items[9].score);
                            }

                            userBest = getUserBest(items.concat());

                            SPI.gameBar.initData('highscore', { tenthPlace: (tenthPositionPoints + 1), 'firstplace': (firstpositionPoints+1), points: userBest.score, position: userBest.position, newpoints: 0, newposition: 0 });
                        }
                        if( unlock == true ) {
                            userActual = getUserActual( items.concat(), unlockedscore);

                            if( userActual.score > firstpositionPoints ) {
                                firstpositionPoints = userActual.score;
                            }
                            SPI.gameBar.unlock('highscore', { 'firstplace': (firstpositionPoints+1), newpoints: userActual.score, newposition: userActual.position });
                        }
                    });
                });
            } else {
                    calculateFinalArray(general, null, function(items) {
                        that.drawHighscores(items, unlock);

                        // INIT GAMEBAR
                        if( currentView == 'daily' ) {
                            // get firstposition points
                            if( items && items[0] ) { firstpositionPoints = parseInt(items[0].score); }

                            //get tenth position points
                            if (items && items[9]) {
                                tenthPositionPoints = parseInt(items[9].score);
                            }

                            SPI.gameBar.initData('highscore', { tenthPlace: (tenthPositionPoints + 1), 'firstplace': (firstpositionPoints+1) });
                        }
                        if( unlock == true ) {

                            userActual = getUserActual( items.concat(), unlockedscore);

                            if( userActual.score > firstpositionPoints ) {
                                firstpositionPoints = userActual.score;
                            }
                            SPI.gameBar.unlock('highscore', { 'firstplace': (firstpositionPoints+1), newpoints: userActual.score, newposition: userActual.position });

                            //console.log( 'itemz NLI: ',items );
                        }
                });
            }
        });
    };

    that.animateCurrentScore = function(unlock) {
        if ($('#highscore_box .my_highscore_top[cuser=1]').length > 0) {
            $('#highscore_box .my_highscore_top[cuser=1]').addClass('my_highscore_top_anim')
                .animate({opacity: 0.2}, 150)
                .animate({opacity: 1}, 100)
                .animate({opacity: 0.2}, 100)
                .animate({opacity: 1}, 100)
                .animate({opacity: 0.2}, 100)
                .animate({opacity: 1}, 100)
                .animate({opacity: 0.2}, 100)
				.animate({opacity: 1}, 100)
                .animate({opacity: 0.2}, 350, function(){
                        $('#highscore_box .my_highscore_top[cuser=1]').removeClass('my_highscore_top_anim').css('opacity','');
                    });
        } else {
            if( $('#highscore_box ol li[cuser=1]').hasClass('current') ) {
                $('#highscore_box ol li[cuser=1]')
                    .animate({opacity: 0.5}, 150)
                    .animate({opacity: 1}, 100)
                    .animate({opacity: 0.5}, 100)
                    .animate({opacity: 1}, 100)
					.animate({opacity: 0.5}, 100)
					.animate({opacity: 1}, 100)
                    .animate({opacity: 0.5}, 100)
                    .animate({opacity: 1}, 350, function(){
                        $('#highscore_box ol li[cuser=1]').css('opacity','');
                    });
            } else {
                $('#highscore_box ol li[cuser=1]').addClass('current')
                    .animate({opacity: 0.5}, 150)
                    .animate({opacity: 1}, 100)
                    .animate({opacity: 0.5}, 100)
                    .animate({opacity: 1}, 100)
                    .animate({opacity: 0.5}, 100)
                    .animate({opacity: 1}, 100)
                    .animate({opacity: 0.5}, 100)
                    .animate({opacity: 1}, 100)
                    .animate({opacity: 0.2}, 350, function(){
                        $('#highscore_box ol li[cuser=1]').removeClass('current').css('opacity','');
                    });
            }
        }
        currentScore = {};
    };

    that.UserLevel = function(callback) {
        if ($.profilar.loggedIn()) {
            that.getUserLevel(function(data) {
                try{
                    tmp = data.hyscor.level || 0;
                }catch(e){
                    tmp = 0;
                }
                callback.call(this,tmp);
            });
        }else{
            callback.call(this,0);
        }
    };


    var handleResponseUserHighscores = function(data, mesg) {
		if (data.hyscor && data.hyscor.errorcode !== undefined) {
			data = {"hyscor":[]};
		}
        this.after_call(data);
    };

    var getAllUserHighscores = function(username, callback) {
        var targetusername = username || $.profilar.forService().username;

        $.ajax({
			global: false,
			cache: config.settings.ajaxCacheUserHighscore,
			timeout: config.settings.timeout,
			url: SPI.sprintf( config.settings.userhighscoresurl, SPI._settings.global.site_id ),
            type: 'GET',
            dataType: 'json',
            success: handleResponseUserHighscores,
            error: function(xml, mesg, error) { handleResponseUserHighscores.call(this, {"hyscor":[]}, ''); },
            after_call: callback,
            data: {
				outputtype: 'json',
				//username: $.profilar.forService().username,
				//hash: $.profilar.forService().hash,
				targetuser: targetusername,
                pagesize: 50
            }
        });
    };

    var drawHighscoresItems = function(aitems) {
        var temp = [];
        try {
            temp = aitems.hyscor.resultset.result;
        } catch(e) {}
        var items = temp.concat();
        var myitems = [];

        if( items.length > 0 ) {
            $('div#highscores div.noresults').hide();
            $('div#highscores div.results').empty().show();
            $('div#highscores div.results').append('<ul></ul>');
            var tempdiv = '';
            for( var i in items ) {
                tempdiv = '';//'<div class="image noresult"></div>' + '<div class="infotext">&#160;</div>';
                $('div#highscores div.results ul').append('<li id="hsid_' + i + '" class="noresult indicator'+(i%2==0?' even':' odd')+'">'+tempdiv+'</li>');
                myitems.push( {loggedIn:items[i].loggedIn,game_id: items[i].itemid, score: items[i].score, timestamp: items[i].timestamp } );
            }
            var listlength = 7;
            if( items.length < listlength ) {
                var emptycontent = '<div class="image noresult"></div>' +
                                   '<div class="infotext">' + SPI._langStrings.highscore.hsbox_nohighscoresyet + '</div>';
                for( var z=items.length; z<listlength; z++ ) {
                    $('div#highscores div.results ul').append('<li id="hsid_' + z + '" class="noresult'+(z%2==0?' even':' odd')+'">'+emptycontent+'</li>');
                }
            }
        } else {
            $('div#highscores div.results').empty().hide();
            $('div#highscores div.noresults').show();
        }
        if( myitems.length>0 ) {
            for( var j in myitems ) {
                getGameForHighscore(j, myitems[j]);
            }
        }
    };

     var drawHighscoresItemsProfile = function(aitems,hsrcallback) {
        var temp = [];
        try {
            temp = aitems.hyscor.resultset.result;
        } catch(e) {}
        var items = temp.concat();
        items = items.slice(0,10);
        var myitems = [];

        if( items.length > 0 ) {
            $('div#myhighscores div.noresults').hide();
            $('div#myhighscores div#userhighscores').show();
            $('div#myhighscores div#userhighscores').empty();
            $('div#myhighscores div#userhighscores').append('<ul></ul>');
            var tempdiv = '';
            for( var i in items ) {
                $('div#myhighscores div#userhighscores ul').append('<li id="hsid_' + i + '" class="tooltip'+(i%2==0?'':' pink')+'"></li>');
                myitems.push( {loggedIn:items[i].loggedIn,game_id: items[i].itemid, score: items[i].score, timestamp: items[i].timestamp } );
            };
            if (items.length <6){
              i++;
              for (i;i<5;i++){
                $('div#myhighscores div#userhighscores ul').append('<li id="hsid_' + i + '" class="'+(i%2==0?'':'pink')+'"></li>');
              };
            };
        }
        if( myitems.length>0 ) {
            for( var j in myitems ) {
                getGameForHighscoreProfile(j, myitems[j]);
            };
            if (myitems.length>5) hsrcallback.call(this,false);else {$('#userhighscores').css('border','1px solid #FFF');hsrcallback.call(this,true)}
        }
    };

    var getGameForHighscore = function(li_id, item ) {
        SPI.gameCache.getGame( item.game_id, function(data) {
            handleBoxHighscore(data, li_id, item);
        });
    };

    var getGameForHighscoreProfile = function(li_id, item) {
        SPI.gameCache.getGame( item.game_id, function(data) {
            handleBoxHighscoreProfile(data, li_id, item);
              $('#userhighscores ul').dTooltip({
                drawItemCallback: 'drawPopularItem',
                eventHandler: 'li.tooltip',
                y: -10,
                ellipsis:{
                  overflowElement:'span.tooltipOverflow',
                  textElement:'span.dtooltip',
                  shortSteps: true,
                  textEnd: '... )'
                }
              });
        });
    };


    var handleBoxHighscore = function( game, li_id, item ) {
        //return;//if( li_id != '2' && li_id != 3) return;
        $('div#highscores div.results ul li[id=hsid_'+li_id+']').removeClass('indicator').removeClass('noresult');
        if( game == null ) {
            return;
        }

        var tooltipinfo = SPI.escape( game.description );
        var tooltipinfo2 = '<span class="time" style="display:none;">' +
                           '<span class="highscoresbox_time">'+
                           SPI.formatDate( item.timestamp, SPI._langStrings.relative_date_plain, true ) +
                           '</span>' +
                           '</span>';

        var div = '';
        div = '<div class="image" title="'+tooltipinfo+'" style="position: relative;">'+
                      game.url +
                      '<span class="cropper">' +
                          '<img src="' + game.thumbnail + '" width="43" height="32" alt="' + SPI.escape(game.title+'') + '" />' +
                          '<span class="rounder">&nbsp;</span>' +
                      '</span>' +
                      '</a>' +
                      tooltipinfo2 +
              '</div>' +
              '<div class="infotext" title="'+tooltipinfo+'">'+
                  '<span class="gametitle">' +
                  game.url +
                  SPI.cutStringPlease(game.title, config.settings.highscorebox_title_length ) +
                  '</a>' +
                  '</span>' +
                      tooltipinfo2 +
              '</div>' +
              '<div class="gamescore">' + SPI.number_format(item.score) + '</div>';

        $('div#highscores div.results ul li[id=hsid_'+li_id+']').empty().append( div );
        var classname = li_id % 2 == 0 ? 'even' : 'odd';
        $('div#highscores div.results ul li[id=hsid_'+li_id+']').addClass( classname );

        spiApplyTooltip2( $('div#highscores div.results ul li[id=hsid_'+li_id+'] div.infotext'), '| ' );
        spiApplyTooltip2( $('div#highscores div.results ul li[id=hsid_'+li_id+'] div.image'), '| ' );
    };

    var handleBoxHighscoreProfile = function( game, li_id, item ) {
        $('div#myhighscores #userhighscores ul li[id=hsid_'+li_id+']').removeClass('indicator');
        if( game == null ) {
            return;
        };
        injectElement = '<div class="overflowElement">'+game.gamelink+'>'+game.title+'</a><p class="score">'+SPI.number_format(item.score)+'</p><img class="tooltipHidden" title="'+SPI.escape(game.title+'')+'" alt="'+SPI.escape(game.title+'')+'" src="'+game.thumbnail+'"/><a href="#" class="tooltipHidden">'+game.subcategory_name+'</a><span class="tooltipHiddenRating">'+game.rating2+'</span></div></li>';
        $('div#myhighscores #userhighscores ul li[id=hsid_'+li_id+']').empty().append( injectElement );
        if( li_id % 2 != 0 ) {
            $('div#myhighscores #userhighscores ul li[id=hsid_'+li_id+']').addClass('pink');
        }
    };

    that.renderHighScoresBox = function(user) {
        var username = user || null;
        getAllUserHighscores(username, function(items) {
            drawHighscoresItems( items )
        });
    };

    that.renderHighScoresBoxProfile = function(hsrcallback,user) {
        var username = user || null;
        getAllUserHighscores(username, function(items) {
            drawHighscoresItemsProfile( items ,hsrcallback)
        });
    };
    return that;
})(jQuery);
;/**
 * Spil Games Ajax achievements - SPI plugin
 * @author:
 *
 * Usage: SPI.achievements.init(options);
 *
 */
SPI.achievements = (function($){
    var config = {settings: {
        timeout: 7000,
        awardsbox_gametitle_length: 30,
        awardsbox_awardtitle_length: 75,
        achievementItemsPerPage: 32,
        gamerPointsOverviewItemsPerPage: 5,
		latest_limit: 7,
		animationCycleTimes: 30,
		latest_li: 'latawa_'
    }};

	var that = {};
	var userAwards = [];
	var userAwardsCount = 0;
	var allAwardsCount = 0;
	var achievementUsername = null;

    that.init = function(settings){
        SPI.getAndUpdateConfig('achievement', config, settings);
	};

	that.renderAchievements = function() {
        getAchievements(function(general) {
            if ($.profilar.loggedIn()) {
                getUserAchievements(function(user) {
                     calculateFinalArray(general, user, function(items) {
						that.drawAchievements(items);
						allAwardsCount = items.length;
                        userAwardsCount = userAwards.length;
                        updateViewBar('normal_logged');
						SPI.gameBar.initData('achievement', {won: userAwardsCount, of: allAwardsCount});
                     });
                });
            } else {
                calculateFinalArray(general, null, function(items) {
                        that.drawAchievements(items);
						allAwardsCount = items.length;
						updateViewBar('normal_guest');
						SPI.gameBar.initData('achievement', {won: 0, of: allAwardsCount});
                });
            }
        });
    };

    var updateViewBar = function(kind) {
		// Update h4 in tab.
		switch (kind) {
			case 'normal_logged':
			case 'unlock_logged':
				$('.gameawards_awards h4').text(SPI.sprintf(config.langStrings.award_count_info, userAwardsCount, allAwardsCount ));
				$('.gameawards_login_info').hide();
				break;
			case 'normal_guest':
				$('.gameawards_awards h4').text(SPI.sprintf(config.langStrings.award_count_info, userAwardsCount, allAwardsCount ));
				$('.gameawards_login_info').show().find('p:eq(0)').show().end().find('p:eq(1)').hide();
				break;
			case 'unlock_guest':
				$('.gameawards_awards h4').text(SPI.sprintf(config.langStrings.award_count_info, userAwardsCount, allAwardsCount ));
				$('.gameawards_login_info').show().find('p:eq(1)').show().end().find('p:eq(0)').hide();
				break;
		}
    };

    // response handler
    var handleResponse = function(data, mesg) {
		// If there was an error, mimic that there is no result...
		if (data.hyscor && data.hyscor.errorcode !== undefined) {
			data = {"hyscor":[]};
		}
		// LIMIT ACHIVEMENTS TO 5
		if( data.hyscor.resultset && data.hyscor.resultset.result && data.hyscor.resultset.result.length > 5 ) {
            data.hyscor.resultset.result = data.hyscor.resultset.result.splice(0,5);
        }
        this.after_call(data);
    };

    var getAchievements = function(callback) {
        $.ajax({
			global: false,
			cache: true,
			timeout: config.settings.timeout,
			url: SPI.sprintf(config.settings.url, 0, config.settings.gameId),
            type: 'GET',
            dataType: 'json',
            success: handleResponse,
            error: function(xml, mesg, error) { if( mesg=='timeout') { that.renderAchievements(); } else { handleResponse.call(this, {"hyscor":[]}, ''); } },
            after_call: callback,
            data: {
				outputtype: 'json',
				locale: SPI._settings.global.lang_id
            }
        });
    };

    var handleResponseUser = function(data, mesg) {
		// If there was an error, mimic that there is no result...
		if (data.hyscor && data.hyscor.errorcode !== undefined) {
			data = {"hyscor":[]};
		}
        this.after_call(data);
    };

    var getUserAchievements = function(callback) {
        $.ajax({
			global: false,
			cache: true,
			timeout: config.settings.timeout,
			url: SPI.sprintf(config.settings.url, SPI._settings.global.site_id, config.settings.gameId),
            type: 'GET',
            dataType: 'json',
            success: handleResponseUser,
            error: function(xml, mesg, error) { handleResponseUser.call(this, {"hyscor":[]}, ''); },
            after_call: callback,
            data: {
				outputtype: 'json',
                username: $.profilar.forService().username,
                hash: $.profilar.forService().hash,
                locale: SPI._settings.global.lang_id
            }
        });
    };

    that.getAchievementsCountForUser = function(callback, targetUser)  {
		var getData = {
			outputtype: 'json',
			//icondata:'0',
			pagesize:'1',
			pagenr:'1',
			outputtype: 'json'
		};
		if (targetUser) {
			getData.targetuser = targetUser;
        } else {
			getData.username = $.profilar.forService().username;
			getData.hash = $.profilar.forService().hash;
		}

        $.ajax({
			global: false,
			cache: true,
			timeout: config.settings.timeout,
			url: SPI.sprintf(config.settings.url, SPI._settings.global.site_id, 0),
            type: 'GET',
            dataType: 'json',
            success: handleResponseUser,
            error: function(xml, mesg, error) { handleResponse.call(this, {"hyscor":[]}, ''); },
            after_call: callback,
            data: getData
        });
    };

    var calculateFinalArray = function(general, user, callback) {
        var items = [];

        if( general.hyscor && general.hyscor.resultset && general.hyscor.resultset.result && general.hyscor.resultset.result.length>0 ) {
            items = general.hyscor.resultset.result.splice(0, 5);
        }

		// sort by difficulty
		if (items.length > 1) {
			for (var i = items.length-2; i >= 0;  i--) {
				for (var j = 0; j <= i; j++) {
					if (parseInt(items[j+1].difficulty) < parseInt(items[j].difficulty)) {
						var tempValue = items[j];
						items[j] = items[j+1];
						items[j+1] = tempValue;
					}
				}
			}
		}

        if( user != null ) {
            // LOGGED IN
            if( user.hyscor && user.hyscor.resultset && user.hyscor.resultset.result && user.hyscor.resultset.result.length>0 ) {

                for( var i in user.hyscor.resultset.result ) {
					for (var z in items ) {
						if (items[z].tag == user.hyscor.resultset.result[i].tag) {
							userAwards.push( user.hyscor.resultset.result[i].tag );
						}
					}
                }
            }
        }

        callback.call(this, items);
    };

    var getDifficulty = function(difficulty_level, points ) {
        var usePointsString = points != undefined;
        var retVal = '';

        var difficulty = {
            '_0' : config.langStrings.difficulty_easy,
            '_5' : config.langStrings.difficulty_medium,
            '_10': config.langStrings.difficulty_hard
        };

        if( usePointsString  ) {
            retVal = SPI.sprintf( config.langStrings.difficultyPoints, difficulty['_' + difficulty_level ], points )
        } else {
            retVal = SPI.sprintf( config.langStrings.difficulty, difficulty['_' + difficulty_level ] )
        }

        return retVal;
    };

	var getPoints = function(points, difficulty) {
        var useDifficultyString = difficulty !== undefined;

        var _difficulty = {
            '_0' : config.langStrings.difficulty_easy,
            '_5' : config.langStrings.difficulty_medium,
            '_10': config.langStrings.difficulty_hard
        };

        if( useDifficultyString  ) {
            return SPI.sprintf( config.langStrings.points_with_difficulty, points, _difficulty['_' + difficulty ]);
        } else {
            return SPI.sprintf( config.langStrings.points, points );
        }
    };

	var isAchieved = function(awardTag) {
		if( userAwards.length>0 ) {
            for( var j in userAwards ) {
				if (userAwards[j].toLowerCase() == awardTag.toLowerCase()) {
					return true;
				}
			}
        }
		return false;
	};

	that.drawAchievements = function(achievements) {
        if( achievements.length > 0 ) {
            for(var i=0; i<achievements.length; i++ ) {
				var ed = $('#gameawa_'+i);

				ed.attr('tag', 'tag_' + achievements[i].tag);
				ed.attr('raise', achievements[i].raise);
				ed.find('img.thumb').attr('src', SPI.sprintf( config.settings.thumb_template, achievements[i].awardid ));
				ed.find('span.awardname').text(achievements[i].title);
                ed.find('span.awname').text(achievements[i].title);
				ed.find('span.desc').text(achievements[i].description);
				ed.find('span.points').text(getPoints(achievements[i].raise));
				ed.dEllipsis({
					overflowElement:'span.awardoverflow',
					textElement:'span.awardname',
					shortSteps: false,
					wrapInWidth: true
				});
				ed.dTooltip({
					eventHandler:'span.trigger',
					displayDiv: 'tltleft',
					content:'.tltcontent',
					track:true,
					position:'left',
					x: 10,
					y: 5,
					drawItemCallback: 'drawAchievementItem'
				});

				if (isAchieved(achievements[i].tag)) {
					ed.addClass('ga_active');
				}
            }
        }

		$('#tab_achievements_content').css('visibility', 'visible');
    };

    that.newAchievementCallback = function(tage) {
        if( userAwardsCount < allAwardsCount ) {
            userAwardsCount++;
        };

		var li = $('ul.gameawards_awardslist li[tag=tag_'+tage+']');

		updateViewBar('unlock_logged');
		SPI.gameBar.unlock('achievement', {won: userAwardsCount, of: allAwardsCount, points: li.attr('raise')});
		li.addClass('ga_just_won');

		var times = config.settings.animationCycleTimes;
		var opacityChanger = function(){
			if (times) {
				--times;
				$(this).animate({opacity: 1}, 500).animate({opacity: 0}, 500, opacityChanger);
			} else {
				updateViewBar('normal_logged');
				li.removeClass('ga_just_won').addClass('ga_active');
			}
        }

		$('img.icon', li).animate({opacity: 0}, 500, opacityChanger);

    };

    that.notLoggedAchievementCallback = function(tage) {
        /*
		if( userAwardsCount < allAwardsCount ) {
            userAwardsCount++;
        };
		*/

        var li = $('ul.gameawards_awardslist li[tag=tag_'+tage+']');

		updateViewBar('unlock_guest');
		SPI.gameBar.unlock('achievement', {won: userAwardsCount, of: allAwardsCount, points: li.attr('raise')});
		$('ul.gameawards_awardslist li[tag=tag_'+tage+']').addClass('ga_just_won');

		var times = config.settings.animationCycleTimes;
		var opacityChanger = function(){
			if (times) {
				--times;
				$(this).animate({opacity: 1}, 500).animate({opacity: 0}, 500, opacityChanger);
			} else {
				updateViewBar('normal_guest');
				$('ul.gameawards_awardslist li[tag=tag_'+tage+']').removeClass('ga_just_won');
			}
        }

		$('ul.gameawards_awardslist li[tag=tag_'+tage+'] img.icon').animate({opacity: 0}, 500, opacityChanger);
    };


    that.UserAwardsCount = function(callback) {
        if ($.profilar.loggedIn()) {
            that.getAchievementsCountForUser(function(data) {
                try{
                    tmp = data.hyscor.resultset.total || 0;
                }catch(e){
                    tmp = 0;
                }
                    callback.call(this,tmp);
            },$.profilar.forService().username);
        }else{
            callback.call(this,0);
        }
    };

    var handleResponseUserAchievements = function(data, mesg) {

	// If there was an error, mimic that there is no result...
	if (data.hyscor && data.hyscor.errorcode !== undefined) {
		data = {"hyscor":[]};
	}
        this.after_call(data, this.page);
    };

    var getAllUserAchievements = function(callback, page) {

        var sendData = {};
        if( achievementUsername == null ) {
            sendData = {
				pagesize: config.settings.achievementItemsPerPage,
				pagenr: page,
				locale: SPI._settings.global.lang_id,
				outputtype: 'json',
				username: $.profilar.forService().username,
				hash: $.profilar.forService().hash
            };
        } else {
            sendData = {
				pagesize: config.settings.achievementItemsPerPage,
				pagenr: page,
				locale: SPI._settings.global.lang_id,
				outputtype: 'json',
                targetuser: achievementUsername
            };
        }

        $.ajax({
			global: false,
			cache: true,
			timeout: config.settings.timeout,
			url: SPI.sprintf(config.settings.url, SPI._settings.global.site_id, 0),
            type: 'GET',
            dataType: 'json',
            success: handleResponseUserAchievements,
            error: function(xml, mesg, error) { handleResponseUserAchievements.call(this, {"hyscor":[]}, ''); },
            after_call: callback,
            data: sendData,
            'page': page
        });
    };

    var drawAchievementsItems = function(aitems, page) {
        var temp = [];
        try {
            temp = aitems.hyscor.resultset.result;
        } catch(e) {
            temp = [];
        }
        var items = temp.concat();

        var page = page || 1;

        if( items.length == 0 ) {
            $('div#myawards_content div.noresults').show();
            $('div#myawards_content div.results').empty().hide();
            return;
        }
        // else:
        var sitesQuantity = Math.ceil(that.userAchievementsLength/config.settings.achievementItemsPerPage);

        $('div#myawards_content div.noresults').hide();
        $('div#myawards_content div.results').empty();
		$("#paging_center1>span, #paging_center2>span").empty().parent().hide();

        $('div#myawards_content div.results').append('<ul id="aul_0"></ul>')

        for (var i=(page*config.settings.achievementItemsPerPage)-config.settings.achievementItemsPerPage , j=0; i<(page*config.settings.achievementItemsPerPage) && i<that.userAchievementsLength; i++, j++) {
            var cls = 'ttL';
            if( (j+1)%8 == 0 || (j+1)%7 == 0) {
                cls = ((j+1)%8 == 0) ? 'last_in_row ttR' : 'ttR';
            } else {
                cls = 'ttL';
            }

            insertString = '<li id="awid_' + i + '" class="'+cls+'"><div class="indicator"></div></li>';
            $('div#myawards_content div.results ul').append( insertString );
            getGameForAchievement(i, items[j]);
        }

        var onThisPage = j;

        var emptyItems = 8 - (onThisPage % 8);

        if( emptyItems != 0 ) {
            for(var k=0; k<emptyItems; k++, j++, i++) {
                var cls = ((j+1)%8==0 ? 'last_in_row' : '' );
                insertString = $(SPI.render(config.templates.myawards_li_empty, {liid: i, extraclass: cls }));
                $('div#myawards_content div.results ul').append( insertString );
            }
        }


		var paging = SPI.paginatorString(that.userAchievementsLength, page, config.settings.achievementItemsPerPage, config.settings.maxPages, function(page){
            getAllUserAchievements( function(items, page){
                drawAchievementsItems(items, page);
            }, page);
        }, { next: config.langStrings.next, prev: config.langStrings.prev});

		$("#paging_center1>span, #paging_center2>span").empty();

		if (paging != '') {
			$("#paging_center1>span").append(paging).parent().show();
			$("#paging_center2>span").append(paging.clone(true)).parent().show();
			var totalPages = Math.ceil(that.userAchievementsLength / config.settings.achievementItemsPerPage);
            $("#pagination_pages_bottom").show().html(SPI.sprintf(SPI._langStrings.sf_global.pagination_counter,page,totalPages));
		} else {
			$("#paging_center1>span, #paging_center2>span, #pagination_pages_bottom").hide();
		}
    };

    var drawAchievementsBoxItems = function(aitems, page) {
        var temp = [];
        try {
            temp = aitems.hyscor.resultset.result;
        } catch(e) {
            temp = [];
        }
        var items = temp.concat();
        var page = page || 1;

        $('.myAllAwards').html(SPI.sprintf($('.myAllAwards').html(),items.length));
        var sitesQuantity = Math.ceil(that.userAchievementsLength/config.settings.achievementItemsPerPage);

        $('div#myawards_content div.noresults').hide();
        $('div#myawards_content div.results').empty();

        var columns = 2;
        var uls = Math.ceil( config.settings.latest_limit / columns );
        for( i=0; i<uls; i++ ) {
            $('div#myawards_content div.results').append('<ul id="aul_'+ i +'"></ul>')
        };
        var selectedUl = 0;
        var insertString = '';

        for (var i=(page*config.settings.achievementItemsPerPage)-config.settings.achievementItemsPerPage , j=0; i<(page*config.settings.latest_limit) && i<that.userAchievementsLength; i++, j++) {
            if( j%columns == 0 && j!=0 ) { selectedUl++; }
            insertString = '<li id="awid_' + i + '" class="indicator"></li>';
            $('div#myawards_content div.results ul[id=aul_'+selectedUl+']').append( insertString );
            getGameForAchievement(i, items[j]);
        };
        if (i < config.settings.latest_limit){
          emptyItem = '<li id="awid_%d"><div class="thumb"><img height="38" width="38" src="/img/_/layout/ha/award_small_white.gif"/></div><span class="noaward">%s</span></li>';
          for (i,j;i<=config.settings.latest_limit;i++,j++){
            if( j%columns == 0 && j!=0 ) { selectedUl++; }
            insertString =SPI.sprintf(emptyItem,i,config.langStrings.emptyaward);
            $('div#myawards_content div.results ul[id=aul_'+selectedUl+']').append( insertString );
          };
        };
    };

    var getGameForAchievement = function(li_id, item ) {
        SPI.gameCache.getGame( item.itemid, function(data) {
            handleBoxAchievement(data, li_id, item);
        });
    };

    var handleBoxAchievement = function( game, li_id, item ) {
		var li, li_content, liData = {};

		li = $('#myawards_content div.results li[id=awid_'+li_id+']');
        li.removeClass('indicator');
        $('div.indicator', li).remove();


        if( game == null ) {
			return;
        }

		liData.thumbPath = SPI.sprintf( config.settings.thumb_template, item.awardid );
		liData.pointsWithDifficultyString = getPoints(item.raise);
		liData.awardTitle = SPI.cutStringPlease(item.title, 22);
		liData.gameTitle = SPI.cutStringPlease(game.title, 22);
		liData.gameUrl = game.gamelink.slice(0,game.gamelink.length-1);
		liData.desc = item.description;
        li_content = $(SPI.render(config.templates.myawards_li, liData));
        li.append(li_content);//.attr('title', liData.desc);

        var cls = $(li).className || 'ttL';

        if( $(li).hasClass('ttL') ) {
            $(li).dTooltip({
                eventHandler:'a',
                displayDiv: 'tltleft',
                content:'.tltcontent',
                track:true,
                position:'left',
                x: 10,
                y: 5,
                drawItemCallback: 'drawAchievementItem'
            });
        } else {
        	$(li).dTooltip({
                eventHandler:'a',
                displayDiv: 'tltright',
                content:'.tltcontent',
                track:true,
                position:'right',
                x: -216,
                y: 5,
                drawItemCallback: 'drawAchievementItem'
            });
        }
        $('img, a', li).attr('alt','').attr('title','');
        $(li).dEllipsis({
            overflowElement:'span.awardoverflow',
            textElement:'span.awardname',
            shortSteps: true,
            wrapInWidth: true
        });
    };

    that.renderUserAchievements = function(user) {
        achievementUsername = user || null;
        getAllUserAchievements(function(items) {
            that.userAchievementsLength = 0;
            try {
                that.userAchievementsLength = items.hyscor.resultset.total;
            } catch(e) {};
            drawAchievementsItems( items );
        }, 1);
    };

    that. renderUserAwardsBox = function(user) {
        achievementUsername = user || null;
        getAllUserAchievements(function(items) {
            that.userAchievementsLength = 0;
            try {
                that.userAchievementsLength = items.hyscor.resultset.total;
            } catch(e) {};
            drawAchievementsBoxItems( items );
        }, 1);
    };

	// Latest awards...
    var renderLatestRow = function(row, game, i) {
		var liData = {};
		liData.thumbPath = SPI.sprintf( config.settings.thumb_template, row.awardid );
		liData.pointsWithDifficultyString = getPoints(row.raise);
		liData.awardTitle = row.title;
		liData.gameTitle = game.title;
		liData.gameUrl = game.gamelink.slice(0,game.gamelink.length-1);
		liData.desc = row.description;

        var ed = $(SPI.render(config.templates.latest_li, liData));

		return ed;

    };

    var handleLatestAwards = function(data, mesg) {
		if (data.hyscor && data.hyscor.errorcode !== undefined) {
			data = {"hyscor":{resultset:{result:[]}}};
		}

		var latest = data.hyscor.resultset.result.splice(0, config.settings.latest_limit);
        if (latest.length == 0) {
            return;
        }
		if (data.hyscor.resultset.total > config.settings.latest_limit) {
			$('#moreAwards a').text(SPI.sprintf(config.langStrings.see_all_x_awards, data.hyscor.resultset.total));
		}

		// Parse and render...
		var i, ed, row;
		for (i=0; i<latest.length; ++i) {
			$('#'+ config.settings.latest_li + i).addClass("indicator").empty().append('<div class="indicator"></div>');

			SPI.gameCache.getGame(latest[i].itemid, function(_row, _i, _liid) {
				return function(game) {
					if (game) {
						$('#'+_liid).removeClass('indicator').empty().append(renderLatestRow(_row, game, _i))
							.dEllipsis({
								overflowElement:'span.awardoverflow',
								textElement:'span.awardname',
								shortSteps: true,
								wrapInWidth: true
							});
						if ($('#'+_liid).hasClass('ttR')) {
							$('#'+_liid).dTooltip({
								eventHandler:'span.trigger',
								displayDiv: 'tltright',
								content:'.tltcontent',
								track:true,
								position:'right',
								x: -216,
								y: 5,
								drawItemCallback: 'drawAchievementItem'
							});
						} else {
							$('#'+_liid).dTooltip({
								eventHandler:'span.trigger',
								displayDiv: 'tltleft',
								content:'.tltcontent',
								track:true,
								position:'left',
								x: 10,
								y: 5,
								drawItemCallback: 'drawAchievementItem'
							});
						}
					}
				}
			}(latest[i], i, config.settings.latest_li + i));
		}
    };

	that.renderLatestsAwards = function(targetUser) {
		var getData =  {
            pagesize: config.settings.achievementItemsPerPage,
            pagenr: 1,
			locale: SPI._settings.global.lang_id,
            outputtype: 'json'
        };

		if (targetUser) {
			getData.targetuser = targetUser;
		} else {
			getData.username = $.profilar.forService().username;
			getData.hash = $.profilar.forService().hash;
		}

        $.ajax({
			global: false,
			cache: true,
			timeout: config.settings.timeout,
			url: SPI.sprintf(config.settings.url, SPI._settings.global.site_id, 0),
            type: 'GET',
            dataType: 'json',
            success: handleLatestAwards,
            error: function(xml, mesg, error) { handleLatestAwards.call(this, {"hyscor":{resultset:{result:[]}}}, ''); },
            data: getData
        });
	};
	// ... latest end

    var getTargetuserAchievements = function(_username, _callback, _pagenumber) {

        var targetusername = _username || $.profilar.forService().username;
		var page = (_pagenumber > 0) ? _pagenumber : 0;

		var getData =  {
		    locale: SPI._settings.global.lang_id,
            outputtype: 'json',
		    targetuser: targetusername,
            pagesize: config.settings.gamerPointsOverviewItemsPerPage,
		    pagenr: page
        };

        $.ajax({
	    global: false,
	    cache: true,
	    timeout: config.settings.timeout,
	    url: SPI.sprintf(config.settings.url, SPI._settings.global.site_id, 0), // FAKE site_id (0)
            type: 'GET',
            dataType: 'json',
            success: handleResponseUserAchievements,
            error: function(xml, mesg, error) { handleResponseUserAchievements.call(this, {"hyscor":[]}, ''); },
            after_call: _callback,
		    page: page,
            data: getData
        });
    };

    var fillGamePointBox = function( game, li_id, item ) {
        $('div#gamepointbox div.results ul li[id=awid_'+li_id+']').removeClass('indicator');
        if( game == null ) {
            return;
        }
        var div = '';

		var row =  {
			date: SPI.formatAbsDate(item.timestamp),
			gamename: game.url + SPI.cutStringPlease(game.title, config.settings.awardsbox_gametitle_length ),
			gameurl: game.url.slice(0,game.url.length-1),
			gamedesc: SPI.escape(item.description+''),
			gametitle: SPI.addslashes(game.title+''),
			awardtitle: SPI.cutStringPlease(item.title, config.settings.awardsbox_awardtitle_length),
			awarddesc: item.description,
			points: item.raise,
			thumbnail: thumbPath = SPI.sprintf( config.settings.thumb_template, item.awardid ),
			diff: getDifficulty( item.difficulty )
		}

        var div = $(SPI.render(config.templates.gamepoint_li, row));

        $('div#gamepointbox div.results ul li[id=awid_'+li_id+']').append( div );
    };

    var loadGamePointsOverview = function(li_id, item ) {
        SPI.gameCache.getGame( item.itemid, function(data) {
            fillGamePointBox(data, li_id, item);
        });
    };

    return that;
})(jQuery);

;SPI.gameCache = (function($){
    var settings = {
        gamedata_url: '/gamesjson/game_%s.json',
        timeout: 7000
    };

	var that = {};
    var searchAjaxManagerGame = $.manageAjax({manageType: 'queue', maxReq: 2, global: false, blockSameRequest: true});

	var gamesCache = [];
	var callbackCache = {};

    var getGameFromCache = function(game_id) {
        for (var i=0; i<gamesCache.length; i++) {
            if (gamesCache[i].gid == game_id) return gamesCache[i];
        }
        return false;
    };

	var runCallbacks = function(game_id, data) {
		if (callbackCache['_'+game_id] !== undefined) {
			for (var i=0; i<callbackCache['_'+game_id].length; ++i) {
				callbackCache['_'+game_id][i](data);
			}
			delete callbackCache['_'+game_id];
		}
	};

    var handleGameResponse = function(data, mesg){
		if (data.gid !== undefined) {
			gamesCache.push(data);
		}

		this.after_call(data);
		runCallbacks(this.game_id, data);
    };

    // game error handler
    var handleGameError = function(xml, mesg, error) {
        this.after_call(null);
		runCallbacks(this.game_id, null);
    };

    that.getGame = function(game_id, callback) {
			var game = getGameFromCache(game_id);
			if (game !== false) {
				callback.call(this, game);
			} else {
				if (searchAjaxManagerGame.add({
					global: false,
					type: 'GET',
					cache: true,
					dataType: 'json',
					success: handleGameResponse,
					error: handleGameError,
					timeout: settings.timeout,
					url: SPI.sprintf(settings.gamedata_url, game_id),
					after_call: callback,
					game_id: game_id
					}) === false) {
					// False means it was already requested!
					if (callbackCache['_'+game_id] === undefined) {
						callbackCache['_'+game_id] = [];
					}
					callbackCache['_'+game_id].push(callback);
				}
			}
    };


	return that;
})(jQuery);
;/**
 * User gallery
 *
 * @author Collaborative work of SpilGames
 */

SPI.myGallery = (function() {
    var config = {settings: {
            empty_item: 'mygallery_empty_item_tpl',
            screen_url: '/gamedata/%s.json', // ?? FIXME
            timeout: 7000,
            li_id: 'profileImageFrame',
            splitter: '.',
            elements_per_page: 20
        }
    };

    var localData = {
        screens: null,
        targetUser:null,
        currentPage: null,
        sortBy: 'date',
        usernames: {},
        gids: {}
    };

    var that = {};
    SPI.getAndUpdateConfig('myGallery', config);

    var loadScreens = function(data) {
        try {
            if (data == null || data == '') {
                data = [];
            } else {
                data = data.split(config.settings.splitter);
                for (var i=0;i<data.length;++i) {
                    data[i] = parseInt(data[i]);
                }
            }
        } catch (e) {
            data = [];
        }
        return data;
    };

    that.init = function(callback, type, params, targetuser){
        that.target_tag   = type.target_tag;
        that.columns      = type.columns;
        that.show_title   = type.show_title;
        that.show_delete  = type.show_delete;
        that.show_picture = type.show_picture;
        that.show_avatar  = type.show_avatar;
        that.gamatarid    = type.params.gamatarid || 0;
        that.autopage     = true;
        that.public_flag  = type.public_flag != undefined ? type.public_flag : false;
        that.targetuser   = targetuser;
        that.type  = type.type;
        if (that.type == 'game' || that.type == 'user_game') {
            // game?
            that.target_details_href = SPI._settings.myGallery.mygallery_url_details_game;
        } else if (that.targetuser) {
            // user public?
            that.target_details_href = SPI._settings.myGallery.mygallery_url_details_public;
        } else {
            // user private
            that.target_details_href = SPI._settings.myGallery.mygallery_url_details;
        };
        getScreens(type, function(data){
            if( data.gamatar && data.gamatar.resultset && data.gamatar.resultset.result && data.gamatar.resultset.result.length>0 ) {
                var temp = null, item = null;
                var itemz = data.gamatar.resultset.result;
                that.totalItems = data.gamatar.resultset.total;
                if( itemz.length > 0 ) {
                    that.mygalleryLength = itemz.length;
                    that.items = itemz;
                }
            } else {
                that.items = {};
            }

            if( callback != null && typeof callback =='function') {
                callback.call(this, params);
            }
        }, targetuser);

        return;
    };

    that.getCountForUser = function(username,callback){
      data_param = {
          pagesize: 1,
          pagenr:1,
          outputtype: 'json'
      };
      if(typeof(username) == 'undefined'){
        data_param.username = $.profilar.forService().username;
        data_param.hash= $.profilar.forService().hash;
      }else{
        data_param.username = username;
      };
      url_param = SPI.sprintf(SPI._settings.myGallery.mygallery_url_list_user, SPI._settings.global.site_id);
      $.ajax({
        global: false,
        cache: false,
        timeout: 7000,
        url: url_param,
        type: 'GET',
        dataType: 'json',
        data: data_param,
        success: callback,
        error: function(xml, mesg, error) { success.call(this, {"gamatar":[]}, ''); },
        after_call: callback
      });
    };
    var getScreens = function(settings, callback, targetuser) {
        var data_param = {};
        var url_param;
        var order = 2;

        if (settings.params.sortby !== undefined) {
            localData.sortBy = settings.params.sortby;
        };

        if (targetuser != undefined) {
            data_param = {
                username: targetuser,
                outputtype: 'json',
                order: order
            };
            jQuery.extend(data_param, settings.params);
            url_param = SPI.sprintf(config.settings.mygallery_url_list_user, SPI._settings.global.site_id);
        } else if(settings.type=='user') {
            data_param = {
                username: $.profilar.forService().username,
                hash: $.profilar.forService().hash,
                outputtype: 'json',
                order: order
            };
            jQuery.extend(data_param, settings.params);
            url_param = SPI.sprintf(config.settings.mygallery_url_list_user, SPI._settings.global.site_id);

        } else if (settings.type=='game') {
            data_param = {
                outputtype: 'json',
                order: order
            };
            jQuery.extend(data_param, settings.params);
            url_param = SPI.sprintf(config.settings.mygallery_url_list_game, SPI._settings.global.site_id, settings.params.gameid);
        } else if (settings.type=='user_game') {
            data_param = {
                username: $.profilar.forService().username,
                hash: $.profilar.forService().hash,
                outputtype: 'json',
                order: order
            };
            jQuery.extend(data_param, settings.params);
            url_param = SPI.sprintf(config.settings.mygallery_url_list_game, SPI._settings.global.site_id, settings.params.gameid);
        }

        $.ajax({
            global: false,
            cache: false,
            timeout: config.settings.timeout,
            url: url_param,
            type: 'GET',
            dataType: 'json',
            success: handleResponse,
            error: function(xml, mesg, error) { if( mesg=='timeout') { /*that.renderList();*/ } else { handleResponse.call(this, {"gamatar":[]}, ''); } },
            after_call: callback,
            data: data_param
        });
    };
    // response handler
    var handleResponse = function(data, mesg) {
        // If there was an error, mimic that there is no result...
        if (data.gamatar && data.gamatar.errorcode !== undefined) {
            data = {"gamatar":[]};
        }
        this.after_call(data);
    };

    that.renderGalleryPage = function(page) {
        // Set sorting
        $(".anchor").removeClass("active");

        if (localData.sortBy !== undefined) {
            $("#sortby_" + localData.sortBy).parent().addClass("active");
        }

        // Render gallery page
        var target_tag   = that.target_tag;
        var columns      = that.columns;
        var show_title   = that.show_title;
        var show_delete  = that.show_delete;
        var show_picture = that.show_picture;

        localData.currentPage = page || 1;
        if(!page) {
            page = localData.currentPage;
        }
        var elements_per_page = config.settings.elements_per_page;
        $("#" + target_tag).empty();

        if(that.items.length > 0) {
            itemsPage = that.items.slice((parseInt(page)-1) * elements_per_page,(parseInt(page)-1) * elements_per_page + elements_per_page);
            while(itemsPage.length == 0 || page <=0){
                page --;
                itemsPage = that.items.slice((parseInt(page)-1) * elements_per_page,(parseInt(page)-1) * elements_per_page + elements_per_page);
            };
            localData.currentPage = page;

            renderEmptyElements(target_tag, config.settings.li_id, elements_per_page, columns, show_title);
            for (i = 0; i < (itemsPage.length); i++) {
                fillElement(config.settings.li_id + i, itemsPage[i], show_title, show_delete, show_picture, false, true);
                var deleteHref =
                    "javascript:if(confirm('"+SPI._langStrings.myGallery.removeConfirmation+"')){SPI.myGallery.removeFromMyGallery("+
                    itemsPage[i].id+");"+
                    "SPI.myGallery.renderGalleryPage("+page+");}";
                $("#"+config.settings.li_id+i+" .imageDelete").attr(
                    "href", deleteHref
                ).ifixpng();
            };

            that.scaleImages("#"+target_tag+" .imgWrapper img", ".imgWrapper", "fill");

            var trigger = 'div.profileImageItemNoEmpty';
            initTooltips(target_tag, trigger, "drawProfileGalleryPage");
            ellipseTitles(target_tag);
            refreshSkyBanner();
            
            var paging = SPI.paginatorString(that.items.length, page, elements_per_page, 4, that.renderGalleryPage, config.langStrings);
            $(".pagination").empty();
            if (paging != '') {
                $("#pagination_top").append(paging);
                $("#pagination_bottom").append(paging.clone(true));
                var totalPages = Math.ceil(that.items.length / elements_per_page);
                $("#pagination_pages_top, #pagination_pages_bottom").html(SPI.sprintf(SPI._langStrings.sf_global.pagination_counter,page,totalPages));
            } else {
                $("#pagination_top, #pagination_bottom, #pagination_pages_top, #pagination_pages_bottom").hide();
                $(".sorting").css('margin-bottom','20px');
            }
        } else {
            renderEmptyElements(target_tag, config.settings.li_id, elements_per_page, columns, false);
            that.targetuser ? $("#additionalBox").hide() : $("#additionalBox").show();
        }
    };

    that.thisIsMyPicture = function(gamatarid) {
        var thisPicBelongsTo = that.getUsernameForGamatarid(gamatarid);
        var iAm = 'nobody';
        if (that.items.length > 0) {
            iAm = that.items[0].username
        }
        return (iAm == thisPicBelongsTo);
    };

    that.renderGalleryDetailPage = function(page) {
        var target_tag   = that.target_tag;
        var columns      = that.columns;
        var show_title   = that.show_title;
        var show_delete  = that.show_delete;
        var show_picture = that.show_picture;
        var show_avatar  = that.show_avatar;

        localData.currentPage = page || 1;
        if(!page) {
            page = localData.currentPage;
        }
        var elements_per_page = 6;
        $("#" + target_tag).empty();

        if(that.items.length > 0) {
            var currentItemId;
            var currentTimeStamp;
            var currentImage;
            var tempautopage;

            currentItemId = that.items[0].itemid;
            currentTimeStamp = that.items[0].created;
            currentImage = 1;
            that.currentUser = that.items[0].username;

            for (i = 0; i < that.items.length; i++) {
                if (that.items[i].id == that.gamatarid) {
                    tempautopage = Math.ceil((i + 1) / elements_per_page);
                    currentItemId = that.items[i].itemid;
                    currentTimeStamp = that.items[i].created;
                    currentImage = i + 1;
                    that.currentUser = that.items[i].username;
                    if(i>0) {
                        var prevItemId = that.items[i-1].id;
                    } else {
                        var prevItemId = -1;
                    }
                    if(i<(that.items.length-1)) {
                        var nextItemId = that.items[i+1].id;
                    } else {
                        var nextItemId = -1;
                    }

                    break;
                }
            }
            if (that.autopage) {
                that.autopage = false;
                if (that.gamatarid != 0) {
                    page = tempautopage;
                } else {
                    // No gamgatar id provided in url
                    that.gamatarid = that.items[0].id;
                    var prevItemId = -1;
                    var nextItemId = that.items[1].id;;
                    // Fill preview image
                    $("#gallery_detail_preview_image").attr(
                        "src", sprintf(SPI._settings.myGallery.mygallery_url_big, that.items[0].id)
                    );
                }
            }

            itemsPage = that.items.slice((parseInt(page)-1) * elements_per_page,(parseInt(page)-1) * elements_per_page + elements_per_page);
            while(itemsPage.length == 0 || page <=0){
                page --;
                itemsPage = that.items.slice((parseInt(page)-1) * elements_per_page,(parseInt(page)-1) * elements_per_page + elements_per_page);
            };
            localData.currentPage = page;

            renderEmptyElements(target_tag, config.settings.li_id, elements_per_page, columns, show_title);
            for (i = 0; i < (itemsPage.length); i++) {
                fillElement(config.settings.li_id + i, itemsPage[i], show_title, show_delete, show_picture, show_avatar);
                if (!that.targetuser) {
                    var deleteHref =
                        "javascript:if(confirm('"+SPI._langStrings.myGallery.removeConfirmation+"')){SPI.myGallery.removeFromMyGallery("+
                        itemsPage[i].id+");"+
                        "SPI.myGallery.renderGalleryPage("+page+");}";
                    $("#"+config.settings.li_id+i+" .imageDelete").attr(
                        "href", deleteHref
                    ).ifixpng();
                }
            };

            that.scaleImages("#galleryGrid .imgWrapper img", ".imgWrapper", "fill");

            var trigger = 'div.profileImageItemNoEmpty';
            initTooltips(target_tag, trigger, "drawProfileGalleryPage");
            ellipseTitles(target_tag);

            // pagination
            var paging = SPI.paginatorString(that.items.length, page, elements_per_page, 4, that.renderGalleryDetailPage, config.langStrings);
            $(".pagination").empty();
            if (paging != '') {
                $("#image_pagination").append(paging);
            } else {
                $("#image_pagination").hide();
            }
            $("img#image_" + that.gamatarid).parent(".imgWrapper").addClass("selected");

            // title
            $(".picturePreviewTop div").text(sprintf($(".picturePreviewTop div").text(), currentImage, that.totalItems));
            var reportButton = SPI.render("pictureTitleReport", {title: that.items[currentImage-1].title});

            // Fill image details
            if(that.targetuser) {
                $(".pictureName").html(reportButton);
                $(".galleryDetailsTop h2").text(sprintf(SPI._langStrings.myGallery.gallery_title, that.targetuser));
            } else {
                $(".galleryDetailsTop h2").text(sprintf(SPI._langStrings.myGallery.gallery_title, $.profilar.forService().username));
            }
            var time_ago = SPI.formatDate(parseInt(currentTimeStamp), SPI._langStrings.relative_date_plain);
            SPI.gameCache.getGame(currentItemId, function(game) {
                $(".picturePreviewTop h3").html(game.gamelink + " id=\"gamename\" >" + game.title + "</a> <span>("+ time_ago +")</span>");
            });



            $(".reportButton").unbind('click').hover(
                function() {
                    $(".reportPicture").attr(
                        "src", "/img/userprofile/ico_report_hover.png"
                    );
                },
                function() {
                    $(".reportPicture").attr(
                        "src", "/img/userprofile/ico_report.png"
                    );
                }
            ).click(
                function() {
                    SPI.myGallery.reportPicture(that.gamatarid);
                }
            );

            // rating
            $("a#bigpic-rating-display span.hearts3").css('background-position','right -'+(parseInt(that.items[currentImage-1].average_rating) * 14)+'px');
            $("#bigpic-rating").pRating({
                siteid: SPI._settings.global.site_id,
                gameid: parseInt(that.gamatarid),
                itemtype: 10, // 10 = UGC
                visibility: 0, // hide with css visibility not css display
                buttonLike: '#i-like-this-bigpic',
                buttonDontLike: '#i-dont-like-this-bigpic',
                buttonRatingHearts: '#bigpic-rating-display',
                buttonThanks: '#bigpic-rating',
                langstrings: {
                    ilikeit: SPI._langStrings.myGallery.ilikepic,
                    ihateit: SPI._langStrings.myGallery.idontlikepic,
                    thanks: SPI._langStrings.myGallery.rating_thanks
                }
            }).css('visibility','visible');

            // display prev next buttons
            if (prevItemId != -1) {
                $("a.buttonPrev").hover(function(){
                    $(this).css('background', 'transparent url(/img/prettyPhoto/light_square/btnPrevious.png) no-repeat scroll 0px 130px').click(function(){
                    window.location.href=sprintf(that.target_details_href, prevItemId);
                    });
                },function(){
                    $(this).css('background', 'transparent url(/img/prettyPhoto/light_square/btnPrevious.png) no-repeat scroll 10000px 10000px');
                });
            }
            if (nextItemId != -1) {
                $("a.buttonNext").hover(function(){
                    $(this).css('background', 'transparent url(/img/prettyPhoto/light_square/btnNext.png) no-repeat scroll 164px 130px').click(function(){
                    window.location.href=sprintf(that.target_details_href, nextItemId);
                    });
                },function(){
                    $(this).css('background', 'transparent url(/img/prettyPhoto/light_square/btnNext.png) no-repeat scroll 10000px 10000px');
                });
            }
            // overlay ! yupikayey motherf****r
            $("a[rel^='prettyPhoto']").prettyPhoto({
                inclusion_closebutton: SPI._langStrings.myGallery.closebutton,
                inclusion_byauthor: SPI._langStrings.myGallery.by,
                inclusion_your_rating: SPI._langStrings.myGallery.your_rating,
                inclusion_ilikepic: SPI._langStrings.myGallery.ilikepic,
                inclusion_idontlikepic: SPI._langStrings.myGallery.idontlikepic,
                inclusion_nrofcomments: SPI._langStrings.myGallery.nrofcomments,
                inclusion_areyousure: SPI._langStrings.myGallery.areyousure,
                inclusion_reportar_success: SPI._langStrings.myGallery.reportar_success,
                inclusion_average_rating: SPI._langStrings.myGallery.average_rating,
                inclusion_rating_thanks: SPI._langStrings.myGallery.rating_thanks,
                site_id: SPI._settings.global.site_id,
                reportar_url: SPI._settings.myGallery.reportar_url,
                comments_url: SPI._settings.myGallery.comments_url,
                rating_add_url: SPI._settings.myGallery.rating_add_url,
                userprofilelink: SPI._langStrings.myGallery.userprofilelink,
                onlyTitle: true,
                onlyTitleValue: that.items[currentImage-1].title
            });
        } else {
            renderEmptyElements(target_tag, config.settings.li_id, elements_per_page, columns, false);
        }
    };

    that.renderGameGalleryDetailPage = function(page) {
        var target_tag   = that.target_tag;
        var columns      = that.columns;
        var show_title   = that.show_title;
        var show_delete  = that.show_delete;
        var show_picture = that.show_picture;
        var show_avatar  = that.show_avatar;

        that.target_details_href = SPI._settings.myGallery.mygallery_url_details_game;
        localData.currentPage = page || 1;
        if(!page) {
            page = localData.currentPage;
        }
        var elements_per_page = 6;
        $("#" + target_tag).empty();

        if(that.items.length > 0) {
            var currentItemId;
            var currentTimeStamp;
            var currentImage;
            var tempautopage;

            currentItemId = that.items[0].itemid;
            currentTimeStamp = that.items[0].created;
            currentImage = 1;
            that.currentUser = that.items[0].username;

            for (i = 0; i < that.items.length; i++) {
                if (that.items[i].id == that.gamatarid) {
                    tempautopage = Math.ceil((i + 1) / elements_per_page);
                    currentItemId = that.items[i].itemid;
                    currentTimeStamp = that.items[i].created;
                    currentImage = i + 1;
                    that.currentUser = that.items[i].username;
                    if(i>0) {
                        var prevItemId = that.items[i-1].id;
                    } else {
                        var prevItemId = -1;
                    }
                    if(i<(that.items.length-1)) {
                        var nextItemId = that.items[i+1].id;
                    } else {
                        var nextItemId = -1;
                    }

                    break;
                }
            }
            if (that.autopage) {
                that.autopage = false;
                if (that.gamatarid != 0) {
                    page = tempautopage;
                } else {
                    // No gamgatar id provided in url
                    that.gamatarid = that.items[0].id;
                    var prevItemId = -1;
                    var nextItemId = that.items[1].id;;
                    // Fill preview image
                    $("#gallery_detail_preview_image").attr(
                        "src", sprintf(SPI._settings.myGallery.mygallery_url_big, that.items[0].id)
                    );
                }
            }

            itemsPage = that.items.slice((parseInt(page)-1) * elements_per_page,(parseInt(page)-1) * elements_per_page + elements_per_page);
            while(itemsPage.length == 0 || page <=0){
                page --;
                itemsPage = that.items.slice((parseInt(page)-1) * elements_per_page,(parseInt(page)-1) * elements_per_page + elements_per_page);
            };
            localData.currentPage = page;

            renderEmptyElements(target_tag, config.settings.li_id, elements_per_page, columns, show_title);

            for (i = 0; i < (itemsPage.length); i++) {
                fillElement(config.settings.li_id + i, itemsPage[i], show_title, show_delete, show_picture, show_avatar);
            };

            that.scaleImages("#galleryGrid .imgWrapper img", ".imgWrapper", "fill");

            var trigger = 'div.profileImageItemNoEmpty';
            initTooltips(target_tag, trigger, "drawProfileGalleryPage");
            ellipseTitles(target_tag);

            // pagination
            var paging = SPI.paginatorString(that.items.length, page, elements_per_page, 4, that.renderGameGalleryDetailPage, config.langStrings);
            $(".pagination").empty();
            if (paging != '') {
                $("#image_pagination").append(paging);
            } else {
                $("#image_pagination").hide();
            }
            $("img#image_" + that.gamatarid).parent(".imgWrapper").addClass("selected");

            var author = that.getUsernameForGamatarid(that.gamatarid);

            // Load author avatar
            $.profilar.loadExternalPrefs([author], function(pdata, errors) {
                if (typeof(pdata[0].avatar) != 'undefined') {
                    $('#authorAvatar').attr('src', SPI.sprintf(
                        SPI._settings.global.avatar_url_small, pdata[0].avatar
                    ));
                }
            }, ['avatar']);

            // Fill image details
            var time_ago = SPI.formatDate(parseInt(currentTimeStamp), SPI._langStrings.relative_date_plain);
            SPI.gameCache.getGame(currentItemId, function(game) {
                $(".galleryDetailsTop h2").text(sprintf(SPI._langStrings.myGallery.gamegallery_title, game.title));
                $(".picturePreviewTop h3").html(game.gamelink + " id=\"gamename\" class=\"gamedetailMod\">" + game.title + "</a><br style=\"clear: left;\" /><span class=\"gamedetailMod\">"+SPI.sprintf(SPI._langStrings.myGallery.by,"<a class=\"gamegallerydetaila\" href=\""+SPI._settings.myprofile.public_pageurl+"?username="+author+"\">"+author+"</a>")+" ("+ time_ago +")</span>");
                if(author==$.profilar.forService().username) {
                    $('.reportButton').hide();
                } else {
                   $('.reportButton').show();
                }
                $("#ghref").attr('href', sprintf(SPI._settings.myGallery.mygallery_url_onegamegallery, game.nice_name));
            });

            // title
            $(".picturePreviewTop div").text(sprintf($(".picturePreviewTop div").text(), currentImage, that.totalItems));
            $(".pictureNameText").empty().text(that.items[currentImage-1].title);

            // rating
            $("a#bigpic-rating-display span.hearts3").css('background-position','right -'+(parseInt(that.items[currentImage-1].average_rating) * 14)+'px');
            $("#bigpic-rating").pRating({
                siteid: SPI._settings.global.site_id,
                gameid: parseInt(that.gamatarid),
                itemtype: 10, // 10 = UGC
                visibility: 0, // hide with css visibility not css display
                buttonLike: '#i-like-this-bigpic',
                buttonDontLike: '#i-dont-like-this-bigpic',
                buttonRatingHearts: '#bigpic-rating-display',
                buttonThanks: '#bigpic-rating',
                langstrings: {
                    ilikeit: SPI._langStrings.myGallery.ilikepic,
                    ihateit: SPI._langStrings.myGallery.idontlikepic,
                    thanks: SPI._langStrings.myGallery.rating_thanks
                }
            }).css('visibility','visible');

            // display prev next buttons
            if (prevItemId != -1) {
                $("a.buttonPrev").hover(function(){
                    $(this).css('background', 'transparent url(/img/prettyPhoto/light_square/btnPrevious.png) no-repeat scroll 0px 130px').click(function(){
                    window.location.href=sprintf(that.target_details_href, prevItemId);
                    });
                },function(){
                    $(this).css('background', 'transparent url(/img/prettyPhoto/light_square/btnPrevious.png) no-repeat scroll 10000px 10000px');
                });
            }
            if (nextItemId != -1) {
                $("a.buttonNext").hover(function(){
                    $(this).css('background', 'transparent url(/img/prettyPhoto/light_square/btnNext.png) no-repeat scroll 164px 130px').click(function(){
                    window.location.href=sprintf(that.target_details_href, nextItemId);
                    });
                },function(){
                    $(this).css('background', 'transparent url(/img/prettyPhoto/light_square/btnNext.png) no-repeat scroll 10000px 10000px');
                });
            }

            // overlay ! yupikayey motherfucker
            $("a[rel^='prettyPhoto']").prettyPhoto({
                inclusion_closebutton: SPI._langStrings.myGallery.closebutton,
                inclusion_byauthor: SPI._langStrings.myGallery.by,
                inclusion_your_rating: SPI._langStrings.myGallery.your_rating,
                inclusion_ilikepic: SPI._langStrings.myGallery.ilikepic,
                inclusion_idontlikepic: SPI._langStrings.myGallery.idontlikepic,
                inclusion_nrofcomments: SPI._langStrings.myGallery.nrofcomments,
                inclusion_areyousure: SPI._langStrings.myGallery.areyousure,
                inclusion_reportar_success: SPI._langStrings.myGallery.reportar_success,
                inclusion_average_rating: SPI._langStrings.myGallery.average_rating,
                inclusion_rating_thanks: SPI._langStrings.myGallery.rating_thanks,
                site_id: SPI._settings.global.site_id,
                reportar_url: SPI._settings.myGallery.reportar_url,
                comments_url: SPI._settings.myGallery.comments_url,
                rating_add_url: SPI._settings.myGallery.rating_add_url,
                userprofilelink: SPI._langStrings.myGallery.userprofilelink,
                onlyTitle: true,
                onlyTitleValue: that.items[currentImage-1].title
            });
        } else {
            renderEmptyElements(target_tag, config.settings.li_id, elements_per_page, columns, false);
        }
    };

    that.renderAtMyprofilePage = function() {
        var target_tag='myLastImages';
        var n = Math.min(2, that.items.length);
        $('#'+target_tag).empty();

        renderEmptyElements(target_tag, config.settings.li_id, 2, 2);

        for (i = 0; i < n; i++) {
            fillElement(config.settings.li_id+i, that.items[i], false, that.show_delete, false);

            var deleteHref =
                "javascript:if(confirm('"+SPI._langStrings.myGallery.removeConfirmation+"')){SPI.myGallery.removeFromMyGallery("+
                that.items[i].id+");"+
                "SPI.myGallery.renderAtMyprofilePage();}";
            $("#profileImageFrame"+i+" .imageDelete").attr(
                "href", deleteHref
            ).ifixpng();
        };

        that.scaleImages("#myLastImages .imgWrapper img", ".imgWrapper", "fill");

        var trigger = 'div.profileImageItemNoEmpty';
        initTooltips(target_tag, trigger, "drawProfileGalleryOverview");

        var moreLinkText = "";

        if (that.public_flag) {
            moreLinkText = SPI.sprintf(
                SPI._langStrings.myGallery.moreLinkPublic, that.targetuser
            );
        } else if (that.items.length == undefined || that.items.length == 0) {
            moreLinkText = SPI._langStrings.myGallery.moreLinkEmpty;
        } else {
            moreLinkText = SPI.sprintf(
                SPI._langStrings.myGallery.moreLink, that.items.length
            );
        };

        $("#myLastImagesBox .moreLink").html(moreLinkText);
    };

    that.renderGalleryAtGamepage = function() {
        var target_tag='galleryAtGamePage';
        var trigger = 'div.profileImageItemNoEmpty';

        $('#'+target_tag).empty();
        if(typeof(that.items.length) == 'undefined') {
            $('.galleryAtGamePage').hide();
            return;
        }
        renderEmptyElements(target_tag, config.settings.li_id, 4, 2);
        for (i = 0; i < that.items.length; i++) {
            fillElement(config.settings.li_id+i,that.items[i],false, false);
        };

        that.scaleImages("#galleryAtGamePage .imgWrapper img", ".imgWrapper", "fill");

        initTooltips(target_tag, trigger, "drawProfileGalleryGamePage");

        $("a[rel^='prettyPhoto']").prettyPhoto({
            inclusion_closebutton: SPI._langStrings.myGallery.closebutton,
            inclusion_byauthor: SPI._langStrings.myGallery.by,
            inclusion_your_rating: SPI._langStrings.myGallery.your_rating,
            inclusion_ilikepic: SPI._langStrings.myGallery.ilikepic,
            inclusion_idontlikepic: SPI._langStrings.myGallery.idontlikepic,
            inclusion_nrofcomments: SPI._langStrings.myGallery.nrofcomments,
            inclusion_areyousure: SPI._langStrings.myGallery.areyousure,
            inclusion_reportar_success: SPI._langStrings.myGallery.reportar_success,
            inclusion_average_rating: SPI._langStrings.myGallery.average_rating,
            inclusion_rating_thanks: SPI._langStrings.myGallery.rating_thanks,
            site_id: SPI._settings.global.site_id,
            reportar_url: SPI._settings.myGallery.reportar_url,
            comments_url: SPI._settings.myGallery.comments_url,
            rating_add_url: SPI._settings.myGallery.rating_add_url,
            userprofilelink: SPI._langStrings.myGallery.userprofilelink,
            onlyTitle: false
        });


    }

    that.getUsernameForGamatarid = function(gamatarid) {
        if (typeof(localData.usernames[gamatarid]) != 'undefined') {
            return localData.usernames[gamatarid];
        }

        var username;
        var url = SPI.sprintf(SPI._settings.myGallery.mygallery_url_get, gamatarid);
        $.ajax({
            global: false,
            async: false,
            cache: false,
            timeout: 7000,
            url: url,
            type: 'GET',
            dataType: 'json',
            data: {
                outputtype: 'json'
            },
            success: function(data){username=data.gamatar.result.username; },
            error: function(data) {username=false;}
        });

        localData.usernames[gamatarid] = username;

        return username;
    }

    that.getGidForGamatarid = function(gamatarid) {
        if (typeof(localData.gids[gamatarid]) != 'undefined') {
            return localData.gids[gamatarid];
        }

        var gid;
        var gamelink;
        var url = SPI.sprintf(SPI._settings.myGallery.mygallery_url_get, gamatarid);
        $.ajax({
            global: false,
            async: false,
            cache: false,
            timeout: 7000,
            url: url,
            type: 'GET',
            dataType: 'json',
            data: {
                outputtype: 'json'
            },
            success: function(data){ gid=data.gamatar.result.itemid; },
            error: function(data) { gid=false;}
        });

        localData.gids[gamatarid] = gid;

        return gid;
    }

    that.hasItems = function() {
        return that.items.length > 0;
    };

    var removeElement = function(arr, id) {
        for (var i = 0; i < arr.length; ++i) {
            if (arr[i].id == id) {
                arr.splice(i, 1);
                break;
            }
        }
    }

    var removeImage = function(id, callback) {
        $.ajax({
            global: false,
            cache: false,
            beforeSend: function() {
            },
            timeout: config.settings.timeout,
            url: SPI.sprintf(config.settings.mygallery_url_delete, id),
            type: 'POST',
            dataType: 'json',
            success: handleDeleteResponse,
            error: function(xml, mesg, error) { handleDeleteResponse.call(this, {"gamatar":[]}, ''); },
            after_call: callback,
            data: {
                username: $.profilar.forService().username,
                hash: $.profilar.forService().hash,
                outputtype: 'json'
            }
        });
    };

    var handleDeleteResponse = function(data, mesg) {
        var delSuccess = false;
        if( data.gamatar && data.gamatar.errorcode == 0 ) { // success
            delSuccess = true;
        }
        this.after_call( delSuccess );
    };

    that.removeFromMyGallery = function(id) {
        removeImage(id, function(removed) {});
        removeElement(that.items, id);
        --that.totalItems;
    };

    that.initGamebar = function() {
        that.savedImages = 0;

        if (that.items.length !== undefined) {
            that.savedImages = that.items.length;
        }

        SPI.gameBar.initData('image', {count: that.savedImages});
    };

    that.notLoggedNewImageCallback = function() {
        ++that.savedImages;
        SPI.gameBar.unlock('image', {count: that.savedImages});
    };

    that.newImageCallback = function() {
        ++that.savedImages;
        SPI.gameBar.unlock('image', {count: that.savedImages});
    };

    that.reportPicture = function(gamatarid) {
        var confirmed = window.confirm(SPI._langStrings.myGallery.areyousure);
        if(confirmed) {
            var postData = {
                username: '',
                hash: '',
                outputtype: 'json',
                reporttype: 'ugc',
                reporteduser: that.currentUser
            };

            if ($.profilar.loggedIn()) {
                postData.username = $.profilar.forService().username;
                postData.hash = $.profilar.forService().hash;
            }

            var what_to_report = SPI.sprintf(SPI._settings.myGallery.reportar_url, SPI._settings.global.site_id, gamatarid);
            $.ajax({
                url: what_to_report,
                data: postData,
                global: false,
                timeout: config.settings.timeout,
                type: 'POST',
                success: function(data) {
                    alert(SPI._langStrings.myGallery.reportar_success);
                },
                error: function(data) {
                }
            });
        }
    };

    var renderEmptyElements = function(target_tag, placeholder, quantity, columns_param, show_title_param) {
        var showTitle = show_title_param || false;
        var columns = columns_param || 5;
        var tt_class = "";
        for (i = 0; i < quantity; i++) {
            // Building LIs with tooltip classes
            if ((i + 1) % columns == 0){
                tt_class = 'lastInRow ttR';
            } else if ((i + 1) % columns == columns - 1){
                tt_class = 'ttR';
            } else {
                tt_class = 'ttL';
            }
            var li_item = SPI.render(config.settings.empty_item, {
                'li_id': placeholder + i + '',
                'ttclass': tt_class
            });
            $("#" + target_tag).append(li_item);
        };

        if (showTitle) {
            $("#" + target_tag + " .imageTitleOverflow").css("display", "block");
        };
        return;
    };

    var fillElement = function(placeholder, element, showTitle_param, showDelete_param, showPicture_param, showAvatar_param, showAuthor_param) {
        var showTitle = showTitle_param || false;
        var showDelete = showDelete_param || false;
        var showPicture = true;
        var showAvatar = showAvatar_param == undefined ? true : showAvatar_param;
        var showAuthor = showAuthor_param || false;

        if (showPicture_param === false) showPicture = showPicture_param;
        // Filling LIs with real data
        $("#" + placeholder + " .profileImageClick img").attr(
            "src", SPI.sprintf(SPI._settings.myGallery.mygallery_url_small, element.id)
        ).attr(
            "id", "image_" + element.id
        );

        if(showPicture) {
            $("#" + placeholder + " .profileImageClick").attr(
                "href", SPI.sprintf(SPI._settings.myGallery.mygallery_url_big, element.id)
            ).removeClass(
                "inactive"
            );
            $("#" + placeholder + " .profileImagePhoto").attr(
                'rel', 'prettyPhoto[gallery]'
            );
            $("#" + placeholder + " .imageTitleOverflow").attr(
                'rel', 'prettyPhoto[galleryTitle]'
            );
        } else {
            SPI.gameCache.getGame(element.itemid, function(game) {
                var nicename = game.nice_name;

                $("#" + placeholder + " .profileImageClick").attr(
                    "href", SPI.sprintf(that.target_details_href, element.id)
                ).removeClass(
                    "inactive"
                );
                if (showTitle) {
                    $("#" + placeholder + " .imageTitle").text(game.title).parent().css("display", "block");
                };
            });
        }

        $("#" + placeholder + " .profileImageItem").addClass(
            "profileImageItemNoEmpty"
        );

        if (showDelete) {
            $("#" + placeholder + " .imageDelete").show();
        }

        // show image author ---------------------------------------------------
        if (showAuthor) {
            var userLink = '<a href="' + config.langStrings.userprofilelink + 
                           '?username=' + element.username + '">' + 
                           SPI.cutStringPlease(
                               element.username,
                               config.settings.maxImageAuthorLength
                           )
                           + '</a>';

            $("#" + placeholder + " .image-author:first").html(
                SPI.sprintf(config.langStrings.by, userLink)
            );
        }
        //----------------------------------------------------------------------
        
        // Tooltip - fill fields
        $("#" + placeholder + " .tooltipTitle").text(element.title);
        $("#" + placeholder + " .tooltipDescription").text(element.description);
        $("#" + placeholder + " .tooltipRatingValue").text(element.average_rating + '').attr('id', 'pic_rating_'+element.id);
        $("#" + placeholder + " .tooltipUsername").text(element.username);

        if (showAvatar) {
            $.profilar.loadExternalPrefs( [element.username], function(data, errors) {
                for( var k in data ) {
                    if( data[k].username && data[k].username.toLowerCase() == element.username.toLowerCase() && data[k].avatar && data[k].avatar != '' && data[k].avatar != undefined ) {
                        element.avatar_url = SPI.sprintf( SPI._settings.global.avatar_url_small, data[k].avatar ) || config.settings.noimage;
                        $("#" + placeholder + " .tooltipAvatar img").attr('src', element.avatar_url);
                    }
                }
            });
        }

        return;
    };

    var initTooltips = function(target_tag, trigger, tooltip_template) {
        $('#'+ target_tag +' li.ttR').dTooltip({
            eventHandler: trigger,
            displayDiv: 'tltright',
            content:'.tltcontent',
            track:true,
            position:'right',
            x: -216,
            y: 5,
            drawItemCallback: tooltip_template
        });
        $('#'+ target_tag +' li.ttL').dTooltip({
            eventHandler: trigger,
            displayDiv: 'tltleft',
            content:'.tltcontent',
            track:true,
            position:'left',
            x: 10,
            y: 5,
            drawItemCallback: tooltip_template
        });
        $('#'+ target_tag +' li img').attr('alt','').attr('title','');
        $('#'+ target_tag +' li a').attr('alt','').attr('title','');
    };

    var ellipseTitles = function(target_tag) {
        $("#"+ target_tag +" li").dEllipsis({
            overflowElement:'a span.imageTitleOverflow',
            textElement:'a span.imageTitle',
            shortSteps: true,
            wrapInWidth: true
        });
    };

    that.scaleImages = function(img, container, method) {
        // Match all elements as an not scaled
        $(img).addClass("notScaled");

        if (tryScaleImages(img, container, method)) {
            var interval = 500;
            var label    = "scaling timer";
            var times    = 20;

            $(document).everyTime(interval, label, function(){
                if (!tryScaleImages(img, container, method)) {
                    $(document).stopTime(label);
                }
            }, times);
        }
    };

    var tryScaleImages = function(img, container, method) {
        $(img + ".notScaled").cjObjectScaler({
            destObj: $(img).parent(container),
            method: method
        });

        var $notScaledCount = 0;

        $(img + ".notScaled").each(function() {
            ++$notScaledCount;
            // CJ Object Scaler adds height and width (inter alia)
            if ($(this).attr("height") != undefined) {
                --$notScaledCount;
                $(this).removeClass("notScaled");
            }
        });

        return $notScaledCount > 0;
    };

    var refreshSkyBanner = function() {
        var skyBannerIframeId = '#a83105c9';
        if( $(skyBannerIframeId).get(0) ) {
             var skyBannerIframeSrc = $(skyBannerIframeId).attr('src');
             $(skyBannerIframeId).attr('src', skyBannerIframeSrc);
             $(skyBannerIframeId).load();
        }
    } 

    return that;
})();
;/**
 * Spil Games game bar - SPI plugin
 * @author: nez
 *
 * Usage: SPI.gameBar.init(options);
 *
 */
SPI.gameBar = (function($){
    var config = {settings: {
		textRotateTime: 15000
    }};

    var results = {
        achievement: { won: 0, of: 0, points: 0 },
        highscore:   { tenthPlace: -1, firstplace: -1, points: 0, position: 0, newpoints: 0, newposition: 0 },
        image:       { count: 0 }
    };
    var textInt = null;

    var that = {};
    that.loggedDefaultTexts = [];
    that.root = null;
    that.username = null;
    that.gender = null;

    that.init = function( element, gamebarOptions ) {
        SPI.getAndUpdateConfig('gamebar', config, null);
        that.gamebarOptions = gamebarOptions;
        var root = $(element+':first');
        if( root.length == 0 ) { return; }

        that.root = root;
        that.username = $.profilar.forService().username;
        that.gender = $.profilar.get('gender');

        $('div#gamebar div.gamebar_content', root).addClass('default');

        $('div.icons a', root).unbind('click').click(function(){ return false; });

        if( $.profilar.loggedIn() == false ) {

            that.username = config.langStrings.guest.guest+'';
            // GUEST
            $('div#gamebar', root).removeClass('logged').addClass('guest');
            // hovers
            $('div.icons a', root).hover(
                function(){
                    var _type = $(this).parent().attr('class');
                    // clean after unlock
                    cleanStyles();
                    $('div#gamebar div.gamebar_content', root).addClass( 'hover_' + _type );
                    $('div.left div:first', root).empty().html( getDefaultAchievementText( _type ) );
                    
                },
                function(){
                    var _type = $(this).parent().attr('class');
                    $('div#gamebar div.gamebar_content', root).removeClass( 'hover_' + _type );
                    $('div.left div:first', root).empty().html( getAchievementText( _type ) );
                    SPI.gameBar.setGuestDefaults();
                }
            );

            return;
        } else {
            // LOGGED IN
            $('div#gamebar', root).removeClass('guest').addClass('logged');
        
            SPI.gameBar.rotateText(); // to set start text
            textInt = setInterval("SPI.gameBar.rotateText()", config.settings.textRotateTime );

            // hovers
            $('div.icons a', root).hover(
                function(){
                    stopDefaultAnimation();

                    var _type = $(this).parent().attr('class');

                    // clean after unlock
                    cleanStyles();
                    $('div#gamebar div.gamebar_content', root).addClass( 'hover_' + _type );
                    $('div.left div:first', root).empty().html( getAchievementText( _type ) );
                },
                function(){
                    var _type = $(this).parent().attr('class');
                    $('div#gamebar div.gamebar_content', root).removeClass( 'hover_' + _type );

                    SPI.gameBar.rotateText(); // to set start text
                    textInt = setInterval("SPI.gameBar.rotateText()", config.settings.textRotateTime );
                }
            );
        }
    };

    var cleanStyles = function() {
        $('div#gamebar div.icons li a.active', that.root).removeClass( 'active' );
        $('div#gamebar div.unlocked', that.root)
            .removeClass('unlocked')
            .removeClass('achievement')
            .removeClass('highscore')
            .removeClass('image')
            .addClass('default');
    };

    var getAchievementText = function( eventType ) {        
        var texts = {
            achievement: SPI.sprintf(config.langStrings.logged.hover_achievement, results.achievement.won, results.achievement.of),
            highscore:   SPI.sprintf(config.langStrings.logged.hover_highscore, SPI.number_format( results.highscore.points ), results.highscore.position),
            image:       SPI.sprintf(config.langStrings.logged.hover_image, results.image.count)
        };
        return ''+texts[eventType];
    };

    var getDefaultAchievementText = function(_type) {
        var _type = _type || '';
        var texts_temp = {
            achievement: {type: 'achievement', text: SPI.sprintf(config.langStrings.logged.default_achievement, 'href="#"')},
            highscore:   {type: 'highscore',   text: SPI.sprintf(config.langStrings.logged.default_highscore, SPI.number_format( results.highscore.tenthPlace ) )},
            image:       {type: 'image',       text: SPI.sprintf(config.langStrings.logged.default_image, that.username)}
        };
        var texts = [];
        if( that.gamebarOptions.length > 0 ) {
            for( var i in that.gamebarOptions ) {
                if( texts_temp && texts_temp[ that.gamebarOptions[i] ] ) {
                    // HACK for "not loaded yet highscores"
                    // @fixme in future
                    if( that.gamebarOptions[i] == 'highscore' && results.highscore.tenthPlace == -1 ) {
                        texts.push({type: 'highscore', text: SPI.sprintf(config.langStrings.logged.default_highscore, 1)});
                        continue; 
                    }
                    texts.push(  texts_temp[ that.gamebarOptions[i] ] );
                }
            }
        }

        //console.log( texts );

        if( _type != '' && $.inArray(_type, that.gamebarOptions) != -1 ) {
            if( texts_temp[_type] ) {
                return ''+ texts_temp[_type].text;
            } else {
                return '';
            }
        }

        if( texts.length > 0 ) {
            var num = 0;
            if( texts.length > 1 ) {
                num = SPI.rand( texts.length ) - 1;
            }
            return ''+ texts[ num ].text;
        }
        return '';
    };

    that.rotateText = function() {
        cleanStyles();
        var text = getDefaultAchievementText();
        if( text != '' ) {
            insertText( text );
        } else {
            stopDefaultAnimation();
        }
    };

    var insertText = function( text, right ) {
        if( text && text.length>0 ) {
            if( right == 'right') {
                $('div.right', that.root).empty().html( ''+text );
            } else {
                $('div.left div:first', that.root).empty().html('<div id="gamebarText">'+text+'</div>');
            }
        }
    };
    var stopDefaultAnimation = function() {
        if( textInt ) {
            clearInterval( textInt );
            textInt = null;
        }
    };

    var getGender = function(gender) {
        return config.langStrings.gender[gender];
    };

    that.initData = function( eventType, params ) {
        results[eventType] = $.extend({}, params);
    };

    that.unlock = function( eventType, params ) {
        if( $.inArray(eventType, that.gamebarOptions) < 0 ) {
            return;
        }
        stopDefaultAnimation();
        results[eventType] = $.extend(results[eventType], params);

        var message = '';
        if( $.profilar.loggedIn() ) {
            // LOGGED IN
            switch( eventType ) {
                case 'achievement': //      won: 0, of: 0, points: 0
                    message = SPI.sprintf(config.langStrings.logged.unlocked_achievement, results[eventType].points );
                break;
                case 'highscore':   //      firstplace: 0, points: 0, position: 0
                    message = SPI.sprintf(config.langStrings.logged.unlocked_highscore, SPI.number_format( results[eventType].newpoints ), results[eventType].newposition );
                break;
                case 'image':       //      count: 0, name: ''
                    message = config.langStrings.logged.unlocked_image;
                break;
            }
        } else {
            // NOT LOGGED IN
            switch( eventType ) {
                case 'achievement': //      won: 0, of: 0, points: 0
                    message = SPI.sprintf(config.langStrings.guest.unlocked_achievement, results[eventType].points );
                break;
                case 'highscore':   //      firstplace: 0, points: 0, position: 0
                    message = config.langStrings.guest.unlocked_highscore;
                break;
                case 'image':       //      count: 0, name: ''
                    message = config.langStrings.guest.unlocked_image;
                break;
            }
            insertText( SPI.sprintf(config.langStrings.guest.unlocked_right, 'href="'+config.settings.register_url+'"', 'href="'+config.settings.login_url+'"'), 'right' );
        }

        cleanStyles();

        $('div#gamebar div.gamebar_content', that.root)
            .removeClass('default')
            .addClass('unlocked')
            .addClass(''+eventType);

        $('div#gamebar div.gamebar_content div.icons li.'+eventType+' a', that.root)
            .addClass('active');

        insertText( message );
        $('#gamebarText').effect('pulsate', { times:3 }, 500);
        $('.icons .'+eventType).effect('pulsate', { times:3 }, 500);

        if( $.profilar.loggedIn() ) {
            textInt = setInterval("SPI.gameBar.rotateText()", config.settings.textRotateTime );
        } else {
            setTimeout('SPI.gameBar.setGuestDefaults()',  config.settings.textRotateTime );
        }
    };

    that.setGuestDefaults = function() {        
        cleanStyles();
        insertText( SPI.sprintf(config.langStrings.guest.default_message, 'href="'+config.settings.register_url+'"', 'href="'+config.settings.login_url+'"') );
    };

    return that;
})(jQuery);

;/**
 * Cookie based last played games system.
 *
 * Requires jQuery >=1.2.6 and SPI.gamesCookieProxy!
 *
 * @author Rafal Jonca
 * @author Radek Jeruzal [few additions, rewrite to SPI object]
 */
SPI.lastPlayedGames = (function() {
    var config = {settings: {
			splitter: '.',
			targetUser: '',
			profilarName: 'myrecent'
        }
    };
    var that = {};
	var gamesCache = null;

	var decodeString = function(data) {
        try {
            if (data == null || data == '') {
                data = new Array();
            } else {
                data = data.split(config.settings.splitter);
                for (var i=0;i<data.length;++i) {
                    data[i] = parseInt(data[i]);
                }
            }
        } catch (e) {
            data = new Array();
        }
        return data;
	};

	var encodeString = function(data) {
        if (data.length > config.settings.maxGames) {
            data = data.slice(0, config.settings.maxGames);
        }
        var saveData = data.join(config.settings.splitter);

        // Save empty string if no data.
        if (data.length == 0) {
            saveData = '';
        }

		return saveData;
	};

    var loadGames = function(callback, forceLoad) {
		if (gamesCache !== null && forceLoad !== true) {
			callback.call(this, gamesCache);
		}

        //for logged in user
        if (config.settings.targetUser == '') {
            if ( $.profilar.loggedIn() ) {
                $.profilar.loadPref(function() {
                   gamesCache = decodeString($.profilar.getPref(config.settings.profilarName));
				   callback.call(this, gamesCache);
                }, [config.settings.profilarName]);
            } else {
                callback.call(this, []);
            }
        } else {
            $.profilar.loadExternalPrefs([config.settings.targetUser], function(data,errors) {
                try {
					gamesCache = decodeString(data[0][config.settings.profilarName] || '');
				} catch(e) {
					gamesCache = decodeString('');
				}
				callback.call(this, gamesCache);
            }, [config.settings.profilarName]);
        };
    };

    var saveGames = function(callback) {
		if (config.settings.targetUser == '' && $.profilar.loggedIn()) {
            $.profilar.setPref(config.settings.profilarName, encodeString(gamesCache) );
            $.profilar.submitPref(function(errors) {
                if (errors) {
					callback.call(this, false);
				} else {
                    callback.call(this, true);
                }
            }, [config.settings.profilarName]);
		}
    };

    var resetGames = function(callback) {
		gamesCache = [];
		saveGames(callback);
    };

    var addGame = function(gameId, callback, forceLoad) {
        loadGames(function(games){
		    var index = jQuery.inArray(gameId, games);
		    if (index != -1) {
		        games.splice(index,1);
		    }
			var newLength = games.unshift(gameId);
			gamesCache = games;
			saveGames(function(ok){
				if (ok) {
					callback.call(this, newLength);
				} else {
					callback.call(this, null);
				}
			});
		}, forceLoad);
    };

    var clearGames = function() {
        resetGames(function(ok) {
			if (ok) {
				that.renderAtFavsPage();
			} else {
				alert(config.langStrings.clear_error);
			}
        });
    };

    var loadGame = function(gameId, ndx, template) {
        SPI.gameCache.getGame( gameId,function(obj) {
        	if (obj != null){
				obj.i = ndx + 1;
                var a = $(SPI.render(template, obj));
                $('#myrec_'+ndx).append(a).removeClass('indicator');
            } else {
				$('#myrec_'+ndx).remove();
			}
        });
    };

    that.hasGames = function() {
        return gamesCache.length > 0;
    };

    that.renderAtOverviewPage = function() {
		loadGames(function(games) {
			if (games.length == 0) {
				$('#bottomRightBox2').hide();
				return;
			}

			for (var i=0; i<config.settings.maxOnOverview && i<games.length; i++) {
				$('#recentlyGames').append('<li id="myrec_' + i + '" class="indicator '+ (i%2?'':'odd') + '"></li>');
			}

			// Real assigning.
			for (var i=0; i<config.settings.maxOnOverview && i<games.length; i++) {
				loadGame(games[i], i, config.templates.overview_li);
			}
		});
    };

	that.renderAtFavsPage = function(){
		loadGames(function(games) {
			if (games.length == 0) {
				$('#bottomRightBox1').hide();
				$('#bottomRightBox2').css('background', 'none');
				$('#bottomRightBox2 .boxheader').css('margin-top', '0');
				return;
			}

			for (var i=0; i<config.settings.maxOnFavs && i<games.length; i++) {
				$('#recentlyGames').append('<li id="myrec_' + i + '" class="bolder indicator '+ (i%2?'':'odd') + '"></li>');
			}

			// Real assigning.
			for (var i=0; i<config.settings.maxOnFavs && i<games.length; i++) {
				loadGame(games[i], i, config.templates.favs_li);
			}
		});

        // Additional subfunction to clear games list
        $('#deleteLink a').click(function () {
            clearGames();
			return false;
        });
	}

    that.addGameAfterTimeframe = function(gameId, miliseconds) {
        return setTimeout(function(){
            addGame(gameId, function(){});
        }, miliseconds);
    };

	that.init = function(settings, callback) {
		SPI.getAndUpdateConfig('lastPlayedGames', config, settings);
	};

	return that;
})();
;/**
 * Spil Games comments system - SPI plugin
 * @author: Rafał Jońca
 * @requires: jQuery
 *
 */

SPI.comments = (function($, SPI){
    var config = {settings: {
            list_url: '/cm/pr/1/list/%s/1/%s',
            list_url_profile: '/cm/pr/1/list/%s/0/%s',
            list_url_image: '/cm/pr/1/list/%s/10/%s',
            report_url: '/cm/pr/1/report/%s/1/%s/%s',
            report_url_image: '/cm/pr/1/report/%s/10/%s/%s',
			reportar_url: '/rp/pb/1/add/3/%s/11/%s',
            send_url: '/cm/pr/1/add/%s/1/%s',
            send_url_image: '/cm/pr/1/add/%s/10/%s',
            timeout: 7000,
			noimage: '/img/userprofile/dummy_small.gif',
			li_id: 'cmid_'
        }
    };
    var totalComments = -1;
    var allEnabled = false;
    var that = {};
	var commentCache = [], plusTotal = 0;
    var wrapManually = (function() {
        var userAgent = navigator.userAgent.toLowerCase();
        var version = (userAgent.match( /.+(?:firefox)[\/: ]([\d.]+)/ ) || [0,'0'])[1];
        if (/mozilla/.test( userAgent ) && !/(compatible|webkit)/.test( userAgent ) && (version.substr(0,3) == '3.0' || version.substr(0,1) == '2')) {
            return true;
        }
        return false;
    })();

    that.fixWrap = function(text, newSeparator, wrap_limit) {
        if (!wrapManually) return text;

        newSeparator = newSeparator || '\n';
		wrap_limit = wrap_limit === undefined ? config.settings.wrap_words_limit : wrap_limit;
        var newText = text.split(/[\s]+/);
        var i, s;
        for (i=0; i<newText.length; ++i) {
            s = '';
            while (newText[i].length > wrap_limit) {
                s += newText[i].substr(0,wrap_limit)+newSeparator;
                newText[i] = newText[i].substr(wrap_limit);
            }
            newText[i] = s + newText[i];
        }
        return newText.join(' ');
    };

    var updateTotalComments = function() {
        if (!allEnabled) {
            $(config.settings.comments_more).text(SPI.sprintf(config.langStrings.read_all_folded, totalComments));
        }
    }

    var reportHandler = function(obj) {
        $.ajax({
            url: obj.data('report_url'),
            data: {username: ''},
            global: false,
            timeout: config.settings.timeout,
            type: 'POST',
            success: function(data) {
                alert(config.langStrings.report_popup);
            }
        });
    };

    var reportarHandler = function() {
    if (! confirm(config.langStrings.report_question) ) return false;
		var postData = $.profilar.forService();
		postData.reporteduser = $(this).data('reportar_data').reporteduser;
		postData.reporttype = 'comment';
		postData.reportweight = config.settings.report_weight;
		var obj = $(this);
		reportHandler(obj); // TODO: remove for reportar!
		return false; // TODO: remove for reportar!

        $.ajax({
            url: obj.data('reportar_url'),
            data: postData,
            global: false,
            timeout: config.settings.timeout,
            type: 'POST',
            success: function(data) {
                reportHandler(obj);
            },
			error: function(data) {
				reportHandler(obj);
			}
        });
    };

    var renderRow = function(row) {
        row.date = SPI.formatDate(parseInt(row.timestamp), SPI._langStrings.relative_date_plain);

        if (row.reported >= config.settings.reported_limit) {
            row.comment = config.langStrings.removed;
            row.commentClass = ' removed';
        } else {
            row.commentClass = '';
        }

        row.show_report_button = true;
        if ($.profilar.loggedIn()) {
            // user won't see report button for own comments
            if ($.profilar.get('username') == row.username) {
                row.show_report_button = false;
            }
        }

        var ed = $(SPI.render(config.templates.li, row));

        var report_url = '';
        var reportar_url = '';
        if (config.settings.image_id != undefined) {
            report_url = SPI.sprintf(config.settings.report_url_image, row.siteid, row.itemid, row.commentid);
        } else {
            report_url = SPI.sprintf(config.settings.report_url, row.siteid, row.itemid, row.commentid);
            //reportar_url = SPI.sprintf(config.settings.reportar_url, row.siteid, row.commentid);
        }

        ed.parent().find('.cmnt_report a').data('report_url', report_url).data('reportar_url', reportar_url).data('reportar_data', {reporteduser: row.username}).click(reportarHandler);
        return ed;
    };

    var errorHandler = function(data) {
        $('.commentsBox').hide();
        $('#unavailableComments').show();
        //$(config.settings.comments_box).empty().append('<li class="comments_info">'+config.langStrings.error_loading+'</li>');
    };

    var errorHandlerProfile = function(data) {
        $('.commentsBox').hide();
        //$('.commentsUnav').show();
    };

    var errorNoCommentsHandlerProfile = function(data) {
        $('.commentsBox').hide();
        $('.commentsUnav').show();
        // fix dots :// @fixme @todo - this needs to be fixed in DESIGN!
        $('#bottomLeftBox').height(($('#bottomRightBox1').height()+$('#bottomRightBox2').height())+37+'px');
    };

    var parseEmoticon = function(input) {
        var output = $().parseEmo(SPI._settings.emoticons, SPI.escape(input));
        if (input != output) {
            return output;
        }
        return false;
    };

    var loadHandler = function(data) {
        // Check if there is a total and if not, we have an error.
        if( data['commentar'] == undefined || data.commentar['total'] == undefined ) {
            errorHandler(data);
            return;
        }

		if (data.commentar.total == '0') {
			data.commentar.resultset = [];
		}

		var finalComments = [];
		plusTotal = 0;

        //show cached comments only on the first page
		if (commentCache.length > 0 && that.page==1) {
			if (data.commentar.resultset.length>0) {
				var timestampUser = 0, timestampServer = 0, timeDelta = 0, j=0;
				for (var i=0; i<commentCache.length; ++i) {
					timestampServer = parseInt(commentCache[i].timestamp);
					while (data.commentar.resultset.length>j && parseInt(data.commentar.resultset[j].timestamp)>timestampServer) {
						finalComments.push(data.commentar.resultset[j]);
						j+=1;
					}
					if (data.commentar.resultset.length>j) {
						if (data.commentar.resultset[j].username.toLowerCase() == commentCache[i].username.toLowerCase() && Math.abs(parseInt(data.commentar.resultset[j].timestamp)-timestampServer) < 5) {
							finalComments.push(data.commentar.resultset[j]);
							j+=1;
						} else {
							finalComments.push(commentCache[i]);
							plusTotal+=1;
						}
					}
				}

				for (var i=j; i<data.commentar.resultset.length; i++ ) {
					finalComments.push(data.commentar.resultset[i]);
				}

				totalComments = parseInt(data.commentar.total);// + plusTotal;
			} else {
				finalComments = commentCache;
				totalComments = commentCache.length;
			}
		} else {
			finalComments = data.commentar.resultset;
			totalComments = parseInt(data.commentar.total);
		}

        //updateTotalComments();

        if (totalComments == 0) {
            $(config.settings.comments_box).empty();
            if ($.profilar.loggedIn()){
                $("iframe.commentText2").contents().find(".frameBody").data('clicked', false).html('<div class="noCommentsBox">'+config.langStrings.nocomments+'</div>');
                $('iframe.commentText2').contents().find(".frameBody").click(function(){
                   if($(this).data('clicked')==false) {
                       clearInput();
                       $(this).data('clicked',true);
                       }
                   });
               $('#emoHolder a').click(function(){
                   if($('iframe.commentText2').contents().find(".frameBody").data('clicked')==false) {
                       clearInput();
                       $('iframe.commentText2').contents().find(".frameBody").data('clicked',true);
                       }
                   });
            } else {
                $('#noCommentsBox').show();
            }
            return;
        }

		var users = [];

		for( var i in finalComments ) {
			finalComments[i].avatar_url = config.settings.noimage;
			if( finalComments[i].authenticated == '1' ) {
				users.push( finalComments[i].username );
			}
		}

		$.profilar.loadExternalPrefs( users, function(pdata, errors) {
            for( var j in finalComments ) {
                for( var k in pdata ) {
                    if( pdata[k].username && pdata[k].username.toLowerCase() == finalComments[j].username.toLowerCase() && pdata[k].avatar ) {
                        finalComments[j].avatar_url = SPI.sprintf( SPI._settings.global.avatar_url_big, pdata[k].avatar ) || config.settings.noimage;
                    }
				}
			}

			// We have at least one comment, start parsing and rendering...
            /*
			if (totalComments > config.settings.max_folded) {
			    $(config.settings.comments_more).show();
			} else {
			    $(config.settings.comments_more).hide();
			}
          */

			var comments_box = $(config.settings.comments_box);
			comments_box.empty();

			// Parse and render...
			var i, ed, row;
			for (i =0; i<finalComments.length; ++i) {
				comments_box.append(renderRow(finalComments[i]));
				var parsed = parseEmoticon(finalComments[i].comment);
			    
                parsed ? comments_box.find('.commentBody:last').html(parsed): null;
			}
            $.each($('commentsBody'))

            var paging = SPI.paginatorString(totalComments, that.page, config.settings.comments_per_page, 4, loadComments, config.langStrings);
            $("#pagination_top").empty();
            $("#pagination_bottom").empty();
            if (paging != '') {
                $("#pagination_top").append(paging).show();
                $("#pagination_bottom").append(paging.clone(true)).show();
            } else {
                $("#pagination_top").hide();
                $("#pagination_bottom").hide();
            }
		}, ['avatar']);
    };

    var loadComments = function(page) {
        that.page = page;
        var url = '';
        if (config.settings.image_id != undefined) {
            url = SPI.sprintf(config.settings.list_url_image, SPI._settings.global.site_id, config.settings.image_id);
        } else {
            url = SPI.sprintf(config.settings.list_url, SPI._settings.global.site_id, config.settings.game_id);
        }

        $(config.settings.comments_box).empty().append('<li class="comments_info">'+config.langStrings.loading_start+'</li>');
        $('#noCommentsBox').hide();

        $.ajax({
            cache: true,
            url: url,
            data: {
               authenticated: '1',
               pagesize: config.settings.comments_per_page,
               pagenr: page,
               //reported_limit: config.settings.reported_limit,
               outputtype: 'json'
            },
            dataType: 'json',
            global: false,
            timeout: config.settings.timeout,
            type: 'GET',
            error: errorHandler,
            success: loadHandler
        });

        //$(config.settings.comments_more).hide();
        totalComments = -1;
    };

    // Checks form errors and show error messages.
    var checkErrors = function() {
        var ok = true;
        var comment = $('textarea.commentText2').val();

        $(config.settings.comments_form).find('div.error').remove();
        $(config.settings.comments_form).find('p.error').removeClass('error');

        if (SPI.trim(comment).length == 0 || comment.length > config.settings.max_chars) {
            ok = false;
            $('.commentButton').before('<div class="error cb">'+config.langStrings.error_comment+'</div>').parent().addClass('error');
        }

        return ok;
    };

    var submitErrorHandler = function(data) {
        $(config.settings.comments_form).find('div.error').remove();
        $(config.settings.comments_form).find('p.error').removeClass('error');
        var errorcode = $("errorcode", data).text();
        if( errorcode != '' && errorcode == '503' ) {
            $('.commentButton').before('<div class="error cb">'+config.langStrings.error_over_quota+'</div>').parent().addClass('error');
        } else {
            $('.commentButton').before('<div class="error cb">'+config.langStrings.error_submit+'</div>').parent().addClass('error');
        }

        unlockSubmit();
    };

    var charsLeftHandler = function() {
        var text = $('textarea.commentText2').val();
        if (text.length > config.settings.max_chars) {
            $('#cf_chars_left').addClass("counterror");
        } else {
            $('#cf_chars_left').removeClass("counterror");
        }
        $('#cf_chars_left').text(SPI.sprintf(config.langStrings.charactersleft,config.settings.max_chars-text.length));
    };

    var clearInput = function() {
        $("iframe.commentText2").contents().find(".frameBody").empty();
    };

    var handleNewCommentCache = function(data, mesg) {
        clearInput();
		if (data.hyscor && data.hyscor.errorcode !== undefined) {
            unlockSubmit();
			return;
		}

        var itemId = 0;
        if (config.settings.image_id != undefined) {
            itemId = config.settings.image_id;
        } else {
            itemId = config.settings.game_id;
        }

		commentCache.unshift({timestamp: data.hyscor.time, comment: this.comment, authenticated: 1, commentid: -1, itemid: itemId, username: $.profilar.forService().username, siteid: SPI._settings.global.site_id, reported: "0", reviewed: 0, remote_addr: '0.xxx.xxx.xxx'});
		loadComments(1);

        unlockSubmit();
    };

    // Comment submitting handler.
    var submitHandler = function() {
        lockSubmit();

        // clear all errors
        $(config.settings.comments_form).find('span.error').remove();

        // Run event on iframe input field to fill textarea even if iframe was filled up using mouse paste.
        if ($.find('iframe.commentText2').length) {
            $('iframe.commentText2').contents().find(".frameBody").keyup();
        }

        var url = '';
        if (config.settings.image_id != undefined) {
            url = SPI.sprintf(config.settings.send_url_image, SPI._settings.global.site_id, config.settings.image_id);
        } else {
            url = SPI.sprintf(config.settings.send_url, SPI._settings.global.site_id, config.settings.game_id);
        }

        if (checkErrors()) {
            $.ajax({
                cache: false,
                url: url,
                data: $(config.settings.comments_form).serialize(),
                dataType: 'xml',
                global: false,
                timeout: config.settings.timeout,
                type: 'POST',
                error: submitErrorHandler,
                success: function(data) {
                    var errorcode = $("errorcode", data).text();
                    if( errorcode != '' && errorcode != '0' ) {
                        submitErrorHandler();
                        return;
                    }

					var tmp = $('#cf_comment').val();
                    $('#cf_comment').val('').change();

		            $.ajax({
		    			cache: false,
		    			timeout: 2000,
		    			url: config.settings.timeurl,
		                type: 'GET',
		                dataType: 'json',
		                success: handleNewCommentCache,
		                error: function(xml, mesg, error) { handleNewCommentCache.call(this, {"hyscor":[]}, ''); },
		                data: { outputtype: 'json' },
						comment: tmp
					});
                }
            });
        } else {
            unlockSubmit();
        }

        return false;
    };

    var lockSubmit = function() {
        $('#cf_submit').unbind();
    };

    var unlockSubmit = function() {
        $('#cf_submit').click(submitHandler);
    };

    // Show all button/link handler
    var allHandler = function() {
        if (allEnabled) {
            allEnabled = false;
            $(this).text(SPI.sprintf(config.langStrings.read_all_folded, totalComments));
            $(config.settings.comments_box).find('li:gt('+(config.settings.max_folded-1)+')').hide();
        } else {
            allEnabled = true;
            $(this).text(config.langStrings.read_all_unfolded);
            // If we have already loaded the comments, just show them...
            if ($(config.settings.comments_box).find('li').length > config.settings.max_folded + plusTotal) {
                $(config.settings.comments_box).find('li:gt('+(config.settings.max_folded-1)+')').show();
            } else {
                loadComments();
            }
        }
    };

    var commentAddHandler = function() {
		$("#loginform").show();
		$("#comment_add").hide();
    };

	// profile part....
    var renderGameRowInProfile = function(row, game, i) {
        row.date = SPI.formatDate(parseInt(row.timestamp), SPI._langStrings.relative_date_plain);
        if(typeof(game.id)!='object') {
            row.gameurl = game.gamelink;
            row.gamename = game.title;
            row.thumbnail = game.thumbnail;
            row.i = i + 1;
            var ed = $(SPI.render(config.templates.li_game_profile, row));
        } else {
            row.gamename = SPI._langStrings.comments.game_removed_from_site;
            row.i = i + 1;
            var ed = $(SPI.render(config.templates.li_game_profile_empty, row));
        }
        if ((typeof(that.targetUser) != 'undefined') && (that.targetUser != $.profilar.forService().username)){
            ed.parent().find('.cmnt_report a').data('report_url', SPI.sprintf(config.settings.report_url, row.siteid, row.itemid, row.commentid)).data('reportar_url', SPI.sprintf(config.settings.reportar_url, row.siteid, row.commentid)).data('reportar_data', {reporteduser: row.username}).click(reportarHandler);
        }else{
            ed.parent().find('.cmnt_report a').remove();
        };
        return ed;
    };
    var renderUGCRowInProfile = function(row, i) {
        row.date = SPI.formatDate(parseInt(row.timestamp), SPI._langStrings.relative_date_plain);
        row.url = SPI.sprintf(config.settings.gameZoomUrl,row.itemid);
        row.itemname = that.getTitleForGamatarid(row.itemid);
        row.i = i + 1;
        var ed = $(SPI.render(config.templates.li_ugc_profile, row));
        if ((typeof(that.targetUser) != 'undefined') && (that.targetUser != $.profilar.forService().username)){
            ed.parent().find('.cmnt_report a').data('report_url', SPI.sprintf(config.settings.report_url_image, row.siteid, row.itemid, row.commentid)).data('reportar_url', SPI.sprintf(config.settings.reportar_url, row.siteid, row.commentid)).data('reportar_data', {reporteduser: row.username}).click(reportarHandler);
        }else{
            ed.parent().find('.cmnt_report a').remove();
            ed.parent().find('.cmnt_report').addClass('noreport');
        };
        return ed;
    };

    var loadInProfileHandler = function(data) {
        // Check if there is a total and if not, we have an error.
        if( data['commentar'] == undefined || data.commentar['total'] == undefined ) {
            errorHandlerProfile(data);
            return;
        }

        //Display different box when there's no comments yet!
        var comments_total = data.commentar['total'];
        if( comments_total == 0) {
            errorNoCommentsHandlerProfile();
            return;
        }

        var comments_box = $('ul#commentsHolder');
        comments_box.empty();

        if (parseInt(data.commentar.total) == 0) {
            for(i in [1,2,3,4,5]) $(comments_box).append('<li><p class="cmnt_report noreport">&nbsp;</p><div class="icon"></div><div class="commentWrapper"><div class="commentText">'+config.langStrings.emptyinlist+'</div></div></li>');
        return;
        };

        // Parse and render...
        var i, ed, row,item;
        for (i =0; i<data.commentar.resultset.length; ++i) {
            comments_box.append('<li id="cmnt'+ i + '">&nbsp;</li>');
            item = data.commentar.resultset[i];
            if (parseInt(item.itemtype) == 1){
                //game
                SPI.gameCache.getGame(item.itemid, function(_row, _i, _liid) {
                    return function(game) {
                        if (game) {
                                comments_box.find('#cmnt'+_i).empty().append(renderGameRowInProfile(_row, game, _i));
                            	var parsed = parseEmoticon(_row.comment);
                            	parsed ? comments_box.find("#cmnt"+_i).find('.commentBody').html(parsed): null;
                        } 
                    }
                }(data.commentar.resultset[i], i, config.settings.li_id + i));
            };
            if (parseInt(item.itemtype) == 10){
            	row = data.commentar.resultset[i];
                comments_box.find('#cmnt'+i).empty().append(renderUGCRowInProfile(row, i));
                var parsed = parseEmoticon(row.comment);
                parsed ? comments_box.find("#cmnt"+i).find('.commentBody').html(parsed): null;
            };
        };
      if (parseInt(data.commentar.total) > 5){
        $(".pagination").empty();
        var paging = SPI.paginatorString(data.commentar.total, that.page, config.settings.profile_limit, 4, SPI.comments.renderLatestsComments, config.langStrings);
        if (paging != '') {
            $(".pagination").append(paging);
        } else {
            $(".pagination").hide();
        };
      };
    };

    that.getTitleForGamatarid = function(gamatarid) {
        var url = SPI.sprintf(SPI._settings.myGallery.mygallery_url_get, gamatarid);
        var title = false;
        $.ajax({
            global: false,
            async: false,
            cache: false,
            timeout: 7000,
            url: url,
            type: 'GET',
            dataType: 'json',
            data: {
                outputtype: 'json'
            },
            success: function(data){ title=data.gamatar.result.title;},
            error: function(data) { title =false;}
        });
        return title;
    }

    that.renderLatestsComments = function(page,targetUser) {
	  that.page = page;
	  that.targetUser =  targetUser ||   that.targetUser;
		SPI.getAndUpdateConfig('comments', config);

		$('ul#commentsHolder').empty().append('<li class="comments_info">'+config.langStrings.loading_start+'</li>');

		var getData =  {
            authenticated: '1',
            pagesize: 5,
            pagenr: page || 1,
            outputtype: 'json'
        };

		if (that.targetUser) {
			getData.targetuser = that.targetUser;
		} else {
			getData.username = $.profilar.forService().username;
			getData.hash = $.profilar.forService().hash;
		}

        $.ajax({
            cache: true,
            url: SPI.sprintf(config.settings.list_url_profile, SPI._settings.global.site_id, 0),
            data: getData,
			targetUser: that.targetUser,
            dataType: 'json',
            global: false,
            timeout: config.settings.timeout,
            type: 'GET',
            error: errorHandlerProfile,
            success: loadInProfileHandler
        });
	};
	// ... end of profile part

    that.init = function(settings) {
        $("#cf_form textarea").rte(SPI._settings.emoticons);
        $("#" + SPI._settings.emoticons.iconlist_div).hover(function() {
            var ulHeight = 230;
            if($.browser.msie && $.browser.version == '6.0') {
                ulHeight += 30;
            }
            $(this).height(ulHeight);
        }).mouseleave(function() {
            $(this).height(88);
        });
        SPI.getAndUpdateConfig('comments', config, settings);
        // attach to form
        //$('#comment_add_href').click(commentAddHandler);
        unlockSubmit();
        $('textarea.commentText2').change(charsLeftHandler).keyup(charsLeftHandler).change();

        // load comments and attach all handler
        //$(config.settings.comments_more).click(allHandler);
        loadComments(1);
    };

    return that;
})(jQuery, SPI);

