/* Copyright (c) 2007-2010 SPIL GAMES.  DO NOT COPY THIS CODE. */
;;(function() {
jQuery.fn.imgError = function(settings) {

    var settings = $.extend({
        noimage: '/img/noimage_small.gif'
    }, settings);
    var images = [];
    var noimagePath = settings.noimage || '';
    var self = this;
    
    return this.each(function(i, val){
        var image = new Image();
        $(image)
        .error(function(){
            try{
                if( noimagePath != '' && $('img[src="'+$(this).attr('src')+'"]').attr('src') != noimagePath ) {
                    var a = $(self).eq(i)[0].attributes;
                    var attrs = [];
                    var old = { w: $(self).eq(i).width(), h: $(self).eq(i).height() };
                    var newImg = $('<img src="' + noimagePath + '" />');
                    $(a).each(function(i,val){
                        if(val.nodeName.toLowerCase() != 'src') {
                            if( val.nodeValue != '' && val.nodeValue != null && val.nodeValue != 'undefined' && val.nodeValue !== false )
                                $(newImg).attr(val.nodeName, val.nodeValue);
                        };
                    });
                    $(self).eq(i).before( newImg ).remove();
                };
            }catch(ex){};
        })
        .attr('src', $(this).attr('src'));
    });
}
})(jQuery);

;/*
 * jQuery ifixpng plugin
 * (previously known as pngfix)
 * Version 2.1  (23/04/2008)
 * @requires jQuery v1.1.3 or above
 *
 * Examples at: http://jquery.khurshid.com
 * Copyright (c) 2007 Kush M.
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 */

 /**
  *
  * @example
  *
  * optional if location of pixel.gif if different to default which is images/pixel.gif
  * $.ifixpng('media/pixel.gif');
  *
  * $('img[@src$=.png], #panel').ifixpng();
  *
  * @apply hack to all png images and #panel which icluded png img in its css
  *
  * @name ifixpng
  * @type jQuery
  * @cat Plugins/Image
  * @return jQuery
  * @author jQuery Community
  */

(function($) {

	/**
	 * helper variables and function
	 */
	$.ifixpng = function(customPixel) {
		$.ifixpng.pixel = customPixel;
	};

	$.ifixpng.getPixel = function() {
		return $.ifixpng.pixel || '/img/pixel.gif';
	};

	var hack = {
		ltie7  : $.browser.msie && $.browser.version < 7,
		filter : function(src) {
			return "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true,sizingMethod=scale,src='"+src+"')";
		}
	};

	/**
	 * Applies ie png hack to selected dom elements
	 *
	 * $('img[@src$=.png]').ifixpng();
	 * @desc apply hack to all images with png extensions
	 *
	 * $('#panel, img[@src$=.png]').ifixpng();
	 * @desc apply hack to element #panel and all images with png extensions
	 *
	 * @name ifixpng
	 */

	$.fn.ifixpng = hack.ltie7 ? function() {
    	return this.each(function() {
			var $$ = $(this);
			// in case rewriting urls
			var base = $('base').attr('href');
			if (base) {
				// remove anything after the last '/'
				base = base.replace(/\/[^\/]+$/,'/');
			}
			if ($$.is('img') || $$.is('input')) { // hack image tags present in dom
				if ($$.attr('src')) {
					if ($$.attr('src').match(/.*\.png([?].*)?$/i)) { // make sure it is png image
						// use source tag value if set
						var source = (base && $$.attr('src').search(/^(\/|http:)/i)) ? base + $$.attr('src') : $$.attr('src');
						// apply filter
						$$.css({filter:hack.filter(source), width:$$.width(), height:$$.height()})
						  .attr({src:$.ifixpng.getPixel()})
						  .positionFix();
					}
				}
			} else { // hack png css properties present inside css
				var image = $$.css('backgroundImage');
				if (image.match(/^url\(["']?(.*\.png([?].*)?)["']?\)$/i)) {
					image = RegExp.$1;
					image = (base && image.substring(0,1)!='/') ? base + image : image;
					$$.css({backgroundImage:'none', filter:hack.filter(image)})
					  .children().children().positionFix();
				}
			}
		});
	} : function() { return this; };

	/**
	 * Removes any png hack that may have been applied previously
	 *
	 * $('img[@src$=.png]').iunfixpng();
	 * @desc revert hack on all images with png extensions
	 *
	 * $('#panel, img[@src$=.png]').iunfixpng();
	 * @desc revert hack on element #panel and all images with png extensions
	 *
	 * @name iunfixpng
	 */

	$.fn.iunfixpng = hack.ltie7 ? function() {
    	return this.each(function() {
			var $$ = $(this);
			var src = $$.css('filter');
			if (src.match(/src=["']?(.*\.png([?].*)?)["']?/i)) { // get img source from filter
				src = RegExp.$1;
				if ($$.is('img') || $$.is('input')) {
					$$.attr({src:src}).css({filter:''});
				} else {
					$$.css({filter:'', background:'url('+src+')'});
				}
			}
		});
	} : function() { return this; };

	/**
	 * positions selected item relatively
	 */

	$.fn.positionFix = function() {
		return this.each(function() {
			var $$ = $(this);
			var position = $$.css('position');
			if (position != 'absolute' && position != 'relative') {
				$$.css({position:'relative'});
			}
		});
	};

})(jQuery);

$(function(){
    $(".pngfix").ifixpng();
});

;;var intCheckCookies = function(){
    $.cookie('_spill_tst_cookie', 123);
    tmp = parseInt($.cookie('_spill_tst_cookie'));
    $.cookie('_spill_tst_cookie', null);
    if (tmp == 123){return 1;};
    return 0;
};
var intUrlSet = function(){
    if(intCheckCookies() == 1){
        $.cookie('_intSPIL', document.location.href,{expires:10,path:'/'});
    };
};
var intUrlGet = function(url){
    if((intCheckCookies() == 1) && ($.cookie('_intSPIL') != null)){
        top.location.href = $.cookie('_intSPIL');
        return true;
    }else{
        top.location.href = url;
        return true;
    }
};
;var userprofiledebug = 1;

// errors display ----------------------------------------------------------

var __showError = function( errorsObj, pagetype, options ) {

    var options = $.extend(true, {
        errorElement: null,
        isAlert: false,
        callback: null,
        debug: true
    }, options);

    var mesg = '';
    var page = pagetype || null;
    if( page == null ) {
        alert('No pagetype provided!');
        return false;
    }

    if( typeof errorsObj != 'object' ) {
        mesg = errorsObj;
    } else {
        // get only FIRST
        var codeObj = errorsObj[0];
        if( codeObj.code == '500' ) {
        	mesg = SPI._langStrings.userprofile.errorcode_503+'';
        } else {
	        if( !codeObj.element ) { codeObj.element = '__empty'; }  // when no operation defined
	        // HACK:
	        codeObj.operation = codeObj.operation.replace('.','_');
	        // texts declaration:
	        var lstrings = {
	            /*
	            'profilebox': {
	                'authenticate':
	                    'username': {
	                        'code_401': 'Wrong username'
	                    },
	                    'password': {
	                        'code_401': SPI._langStrings.userprofile.password_wrong
	                    }
	                }
	            },*/
	            'register': { // page type
	                'register': { // operation
	                    'password': { // element
	                        'code_406': SPI._langStrings.userprofile.validation.password_notacceptable
	                    },
	                    'username': {
	                        'code_406': SPI._langStrings.userprofile.validation.username_notacceptable,
	                        'code_409': SPI._langStrings.userprofile.errorcode_409
	                    },
	                    'email': {
	                        'code_409': SPI._langStrings.userprofile.validation.registration_email_exists
	                    }
	                }
	            },
	            'unregister': {
	                'authenticate': {
	                    'username': {
	                        'code_401': SPI._langStrings.userprofile.validation.username_wrong // not used
	                    },
	                    'password': {
	                        'code_401': SPI._langStrings.userprofile.validation.password_wrong // not used
	                    }
	                },
	                'deregister': {
	                    'username': {
	                        'code_401': SPI._langStrings.userprofile.validation.username_wrong // not used
	                    },
	                    'password': {
	                        'code_401': SPI._langStrings.userprofile.validation.password_wrong // not used
	                    }
	                }
	            },
	            'new_password': {
	                'followup': {
	                    '__empty': {
	                        'code_404': SPI._langStrings.userprofile.validation.new_password_reset_passlink_used,
	                        'code_503': SPI._langStrings.userprofile.errorcode_503
	                    }

	                },
	                'followup_modify': {
	                    'password': {
	                        'code_406': SPI._langStrings.userprofile.validation.new_password_password_not_acceptable
	                    }
	                }
	            },
	            'changepass': {
	                'authenticate': {
	                    'password': {
	                        'code_401': SPI._langStrings.userprofile.validation.password_wrong,
	                        'code_406': SPI._langStrings.userprofile.validation.password_notacceptable
	                    }
	                },
	                'modify': {
	                    'password': {
	                        'code_406': SPI._langStrings.userprofile.validation.password_notacceptable
	                    }
	                }
	            },
	            'forgot_password': {
	                'trigger': {
	                    'email': {
	                        'code_404': SPI._langStrings.userprofile.validation.forgot_password_email_not_exists
	                    }
	                }
	            },
	            'profile': {
	                'authenticate': {
	                    'password': {
	                        'code_401': SPI._langStrings.userprofile.validation.password_wrong,
	                        'code_406': SPI._langStrings.userprofile.validation.password_notacceptable
	                    }
	                },
	                'modify': {
                        'email': {
                            'code_409': SPI._langStrings.userprofile.validation.email_exists
                        }
                    }
	            },
	            'emailconfirm': {
	                'followup': {
		                '__empty': { // when no operation defined
		                    'code_404': 'Your email was already confirmed or used url is not valid.',
	                        'code_503': SPI._langStrings.userprofile.errorcode_503
		                }
		            }
	            }
	        };
	        try {
	            mesg = eval('lstrings.'+page+'.'+codeObj.operation+'.'+codeObj.element+'.code_'+codeObj.code);
	        } catch(e) {
	            if( options.debug ) {
	                try {
	                    mesg = 'Undefined error: '+page+'/'+codeObj.operation+'/'+codeObj.element+'/'+codeObj.code;
	                } catch(e){
	                    mesg = 'Undefined!';
	                }
	            }
	        }

	    }

	    // CHANGEPASS (oldpass) HACK

	    if( typeof codeObj == 'object' && page == 'changepass' && codeObj.operation == 'authenticate' && codeObj.element == 'password' ) {
	        codeObj.element = 'old_password';
	    }


    }

    if( mesg != '' ) {
        if( options.isAlert === true ) {
            alert( '' + mesg );
        } else {
            if( options.errorElement != null && options.errorElement.length ) {
                options.errorElement.empty().html('' + mesg).show();
            } else {
                if( codeObj && codeObj.element && $('#'+pagetype+' #f_'+codeObj.element+'_error').length > 0 ) {
                    $('#'+pagetype+' #f_'+codeObj.element+'_error div.errorbox div.content').empty().html('' + mesg+'').show();
                } else {
                    if( $('#'+pagetype+' .validationErrors').length > 0 ) {
                        $('#'+pagetype+' .validationErrors:first').addClass('error').html('' + mesg).show();
                    }
                }
            }
        }
    }

    if( options.callback != null && typeof options.callback == 'function' ) {
        if (page == 'forgot_password' || page == 'new_password') {
            options.callback.call(this, mesg);
        } else if (page == 'register') {
        	options.callback.call(this, codeObj);
        } else {
            options.callback.call(this);
        }
    }

};

// forms switch ------------------------------------------------------------
var showForm = function(formType) {
    switch(formType) {
        default:
        case 'register':
            $("div#register").show();
        break;
        case 'profile':
            $("div#profile-update").show();
        break;
        case 'changepass':
            $("div#pass-change").show();
        break;
    }
};

// age check ---------------------------------------------------------------
var ageCheck = function(birthdate, min_age) {
	var year  = parseInt(birthdate.year);
	var month = parseInt(birthdate.month) - 1;
	var day   = parseInt(birthdate.day);
	var theirDate = new Date((year + min_age), month, day);
	var today = new Date;
    return ( (today.getTime() - theirDate.getTime()) < 0) ? false : true;
};

// validation --------------------------------------------------------------
var validateEmail = function(value) { // contributed by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/
	return /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test(value);
};
var validateUsername = function(value) {
    return /^[a-z0-9-_]+$/i.test(value);
};
jQuery.checkUserprofileField = function(settings) {
    // default settings
    var settings = $.extend(true, {
        author: 'nez',
        version: '1.0',
        debug: false,
        formType: null,
        fieldName: null,
        fieldId: null,
        fieldValue: null,
        username_minLength: 3,
        password_minLength: 6
    }, settings);

    if( settings.formType == null || settings.fieldName == null || settings.fieldId == null || settings.fieldValue == null ) {
        if( settings.debug == true && window.console ) {
            console.log('Error: formType, fieldName, fieldId or fieldValue is empty');
        }
    } else {
        //----------------------------
        var errMesg = new Array();

        var fieldName = settings.fieldName;
        var fieldId = settings.fieldId;
        var fieldValue = settings.fieldValue;

        switch( settings.formType ) {

            case 'profile':

                switch( fieldName ) {
                	case 'old_password':
                    case 'password': if( fieldValue.length < settings.password_minLength ) { errMesg.push({id: fieldId, mesg: SPI._langStrings.userprofile.validation.password_isempty+''});} break;
                    case 'givenname': if( $.profilar.get('givenname').length>0 && fieldValue.length<1 ){errMesg.push({id: fieldId, mesg: SPI._langStrings.userprofile.validation.firstname_isempty+''});} break;
                    case 'surname': if( $.profilar.get('surname').length>0 && fieldValue.length<1 ){errMesg.push({id: fieldId, mesg: SPI._langStrings.userprofile.validation.lastname_isempty+''});} break;
                    case 'email': if(!validateEmail(fieldValue)){errMesg.push({id: fieldId, mesg: SPI._langStrings.userprofile.validation.email_invalid+''});} break;
                }

            break;
            case 'register':

                switch( fieldName ) {
                    case 'username':
                        if( fieldValue.length < settings.username_minLength ) {
                            errMesg.push({id: fieldId, mesg: SPI._langStrings.userprofile.validation.username_minlength+''});
                        } else {
                            if( !validateUsername(fieldValue) ) {
                                errMesg.push({id: fieldId, mesg: SPI._langStrings.userprofile.validation.username_badchar+''});
                            } else {}
                        }
                    break;
                    case 'password':
                        if( fieldValue.length < settings.password_minLength ) { errMesg.push({id: fieldId, mesg: SPI._langStrings.userprofile.validation.password_minlength+'' });}
                    break;
                    case 'password_repeat':
                        if( fieldValue != $("#register input[name=password]").val() || fieldValue.length < settings.password_minLength ){ errMesg.push({id: fieldId, mesg: SPI._langStrings.userprofile.validation.password_mustmatch+'' });}
                    break;
                    case 'email': if(!validateEmail(fieldValue)){errMesg.push({id: fieldId, mesg: SPI._langStrings.userprofile.validation.email_invalid+''});} break;
                    case 'dob_month': if(fieldValue=='-1'){errMesg.push({id: fieldId, mesg: SPI._langStrings.userprofile.validation.dob_selectmonth+''});} break;
                    case 'dob_day': if(fieldValue=='-1'){errMesg.push({id: fieldId, mesg: SPI._langStrings.userprofile.validation.dob_selectday+''});} break;
                    case 'dob_year': if(fieldValue=='-1'){errMesg.push({id: fieldId, mesg: SPI._langStrings.userprofile.validation.dob_selectyear+''});} break;
                    case 'gender': if($("#register input[name=gender]:checked").length == 0){errMesg.push({id: fieldId, mesg: SPI._langStrings.userprofile.validation.gender_choose+''});} break;
                    case 'parent_email':
                    	if($('div#up_registration_parent_email').is(':visible') && !validateEmail(fieldValue)){
                    		errMesg.push({id: fieldId, mesg: SPI._langStrings.userprofile.validation.parent_email_invalid+''});
                    	} else if ($('input#f_parent_email').val() == $('input#f_email').val()){
                    		errMesg.push({id: fieldId, mesg: SPI._langStrings.userprofile.validation.parent_email_eq_child_email+''});
                    	}
                    break;
                    case 'privacy_policy': if($('div.privacy_policy_check').is(':visible') && $("#register input[name=privacy_policy]:checked").length == 0){errMesg.push({id: fieldId, mesg: SPI._langStrings.userprofile.validation.privacy_policy_unchecked+''});} break;
                }

            break;
            case 'changepass':

                switch( fieldName ) {
                    case 'old_password':
                        if( fieldValue.length < settings.password_minLength ) { errMesg.push({id: fieldId, mesg: SPI._langStrings.userprofile.validation.old_password_minlength+''});}
                    break;
                    case 'password':
                        if( fieldValue.length < settings.password_minLength ) {
                            errMesg.push({id: fieldId, mesg: SPI._langStrings.userprofile.validation.password_minlength+''});
                        }
                    break;
                    case 'password_repeat':
                        if( fieldValue == '' ) {
                            errMesg.push({id: fieldId, mesg: SPI._langStrings.userprofile.validation.changepass_password_repeat_minlength+'' });
                        } else {
                            if( fieldValue != $("#password input[name=password]").val()){ errMesg.push({id: fieldId, mesg: SPI._langStrings.userprofile.validation.changepass_password_mustmatch+'' });}
                        }
                    break;
                }
            break;
            case 'forgot_password':
                switch (fieldName) {
                    case 'email':
                        if (!validateEmail(fieldValue)) {
                            errMesg.push({id: fieldId, mesg: SPI._langStrings.userprofile.validation.forgot_password_email_invalid+''});
                        }
                    break;
                }
            break;
            case 'new_password':
                switch (fieldName) {
                    case 'password':
                        if (fieldValue.length < settings.password_minLength) {
                            errMesg.push({id: fieldId, mesg: SPI._langStrings.userprofile.validation.new_password_password_minlength+''});
                        }
                    break;
                    case 'password_repeat':
                        if (fieldValue == '') {
                            errMesg.push({id: fieldId, mesg: SPI._langStrings.userprofile.validation.new_password_password_repeat_minlength+''});
                        } else if (fieldValue != $('#new_password_form #f_password').val()) {
                            errMesg.push({id: fieldId, mesg: SPI._langStrings.userprofile.validation.new_password_password_repeat_must_match+''});
                        }
                    break;
                }
            break;
            case 'unregister':
                switch( fieldName ) {
                    case 'username':
                        if( fieldValue.length < settings.username_minLength ) {
                            errMesg.push({id: fieldId, mesg: SPI._langStrings.userprofile.validation.username_minlength+''});
                        } else {
                            if( !validateUsername(fieldValue) ) {
                                errMesg.push({id: fieldId, mesg: SPI._langStrings.userprofile.validation.username_badchar+''});
                            } else {}
                        }
                    break;
                    case 'password':
                        if( fieldValue.length < settings.password_minLength ) {
                            errMesg.push({id: fieldId, mesg: SPI._langStrings.userprofile.validation.password_minlength+''});
                        }
                    break;
                }
            break;
        }

        //----------------------------

        var retVal = errMesg.length>0 ? false : true;
        return [ retVal, errMesg ];
    }
};

jQuery.nValidateUserprofileRT = function(settings) {
    // default settings
    var settings = $.extend(true, {
        author: 'nez',
        version: '1.0',
        debug: false,
        formType: 'register',
        classname: 'validateMe'
    }, settings);

    // special case for date validation
    $("#f_dob_year").parent().append('<div id="f_dob_error" class="error" style="color: rgb(255, 0, 0);"></div>').show();
    $('#f_dob_year, #f_dob_month, #f_dob_day').blur(function(){
        var cyear = parseInt( $("select[name=dob_year]").val() );
        var cmonth = parseInt( $("select[name=dob_month]").val() );
        var cday = parseInt( $("select[name=dob_day]").val() );
        var mesg = '';
        if( cyear > 0 && cmonth > 0 && cday > 0 ) {
            if( ageCheck( {year: cyear, month: cmonth, day: cday}, 14) == false ) {
                mesg = SPI._langStrings.userprofile.validation.too_young+'';
            }
            var dateOk = true;
            if ((cmonth==4 || cmonth==6 || cmonth==9 || cmonth==11) && cday==31) {
                  dateOk = false;
            }
            if (cmonth == 2) { // check for february 29th
                  var isleap = (cyear % 4 == 0 && (cyear % 100 != 0 || cyear % 400 == 0));
                  if (cday > 29 || (cday==29 && !isleap)) {
                        dateOk = false;
                  }
            }
            if( !dateOk ) {
                mesg = SPI._langStrings.userprofile.validation.invalid_date+'';
            }
        }

        if( mesg ) {
            $('div#f_dob_error').html('- '+mesg).show();
            $(this).addClass('validationError');
        } else {
            $(this).removeClass('validationError');
            $('div#f_dob_error').hide();
        }
	});

    $("."+settings.classname).each( function(){

        var self = $(this);
        var fieldName = $(self).attr('name');
        var fieldId = $(self).attr('id');
        $('#'+fieldId).parent().append('<div id="'+fieldId+'_error" class="error" style="color: rgb(255, 0, 0);"></div>').show();

        $(self).blur(function(){

            var fieldValue = $(self).val();
            var errMesg = new Array();

            var fieldTest = $.checkUserprofileField({
                'formType': settings.formType,
                'fieldName': fieldName,
                'fieldId': fieldId,
                'fieldValue': fieldValue
            });
            if( fieldTest[0] == false ) {
                errMesg = fieldTest[1];
            }

            if( errMesg.length > 0 ) {
                $('div#'+fieldId+'_error').html('- '+errMesg[0].mesg).show();
                $(this).addClass('validationError');
            } else {
                $(this).removeClass('validationError')
                $('div#'+fieldId+'_error').hide();
            }
        });
    });
};

jQuery.nValidateUserprofileOD = function(settings) {
    // default settings
    var settings = $.extend(true, {
        author: 'nez',
        version: '1.0',
        debug: false,
        formType: 'register'
    }, settings);

    var errMesg = new Array(), errString = '';

    $(".validationError").removeClass('validationError');
    $('div[id$=_error]').empty().hide();

    $(".validateMe").each(function(){

        var fieldName = $(this).attr('name');
        var fieldId = $(this).attr('id');
        var fieldValue = $(this).val();

        var fieldTest = $.checkUserprofileField({
                'formType': settings.formType,
                'fieldName': fieldName,
                'fieldId': fieldId,
                'fieldValue': fieldValue
            });
        if( fieldTest[0] == false ) {
            errMesg.push(fieldTest[1]);
        }

    });

    if( settings.formType == 'profile' || settings.formType == 'register' ) {
        // age check
        var cyear = parseInt( $("select[name=dob_year]").val() );
        var cmonth = parseInt( $("select[name=dob_month]").val() );
        var cday = parseInt( $("select[name=dob_day]").val() );
        if( cyear > 0 && cmonth > 0 && cday > 0 ) {
            if( ageCheck( {year: cyear, month: cmonth, day: cday}, 14) == false ) {
                errMesg.push([{id: 'f_dob_year', mesg: SPI._langStrings.userprofile.validation.too_young+''}]);
            }
            var dateOk = true;
            if ((cmonth==4 || cmonth==6 || cmonth==9 || cmonth==11) && cday==31) {
                  dateOk = false;
            }
            if (cmonth == 2) { // check for february 29th
                  var isleap = (cyear % 4 == 0 && (cyear % 100 != 0 || cyear % 400 == 0));
                  if (cday > 29 || (cday==29 && !isleap)) {
                        dateOk = false;
                  }
            }
            if( !dateOk ) {
                errMesg.push([{id: 'f_dob_day', mesg: SPI._langStrings.userprofile.validation.invalid_date+''}]);
            }
        }
    }


    if( errMesg.length > 0 ) {
        $(errMesg).each(function(i,val){
            $('div#'+val[0].id+'_error').html('- '+val[0].mesg).show();
            $('#'+val[0].id).addClass('validationError');
        });
        return false;
    }
    return true;

};

jQuery.nValidateRegistrationRT = function(settings) {
    // default settings
    var settings = $.extend(true, {
        author: 'nez',
        version: '1.0',
        debug: false,
        formType: 'register',
        classname: 'validateMe',
        notAllowedAge: 7,
        parentConfirmationAge: 14
    }, settings);

    /*
    var dateOkay = true;

    $('#f_dob_year, #f_dob_month, #f_dob_day').change(function(){
        validateDate();
    });
    $('#f_dob_year, #f_dob_month, #f_dob_day').blur(function(){
        validateDate();
    });
    */

    var validateDate = function(){
        var cyear = parseInt( $("select[name=dob_year]").val() );
        var cmonth = parseInt( $("select[name=dob_month]").val() );
        var cday = parseInt( $("select[name=dob_day]").val() );
        var mesg = '';
        $("#dob select.validationError").removeClass("validationError");
        if( cyear > 0 && cmonth > 0 && cday > 0 ) {
			if( ageCheck( {year: cyear, month: cmonth, day: cday}, settings.notAllowedAge) == false || ageCheck( {year: cyear, month: cmonth, day: cday}, settings.parentConfirmationAge) == true) {
				if( ageCheck( {year: cyear, month: cmonth, day: cday}, settings.notAllowedAge) == false){
					mesg = SPI._langStrings.userprofile.validation.too_young+'';
				}
				$("#up_registration_parent_email input.validationError").removeClass('validationError');
				$('#up_registration_parent_email').hide();

                parentEmailOkay = true;
			}else if( ageCheck( {year: cyear, month: cmonth, day: cday}, settings.parentConfirmationAge) == false ) {
				$('#up_registration_parent_email').show();
                $("#up_registration_parent_email input[name=parent_email]").trigger('focus');

                //assume that parents email is empty (not OK)
                parentEmailOkay = false;
			}
            var dateOk = true;
            if ((cmonth==4 || cmonth==6 || cmonth==9 || cmonth==11) && cday==31) {
                  dateOk = false;
            }
            if (cmonth == 2) { // check for february 29th
                  var isleap = (cyear % 4 == 0 && (cyear % 100 != 0 || cyear % 400 == 0));
                  if (cday > 29 || (cday==29 && !isleap)) {
                        dateOk = false;
                  }
            }
            if( !dateOk ) {
                mesg = SPI._langStrings.userprofile.validation.invalid_date+'';
                $("#dob input").addClass('validationError');
            }
            dateOkay = dateOk;
 			$('div#error_f_dob div#f_dob_age_or_date_error_text').empty().append(mesg);
            $('.dob_dmy').hide();
			if($('div#f_dob_age_or_date_error_text').text().length == 0) {
                $('#dob_validationCorrectImage').show();
                $('#dob_validationErrorImage').hide();
			} else {
                $('#dob_validationCorrectImage').hide();
                $('#dob_validationErrorImage').show();
                $("#dob select").addClass("validationError");
                dateOkay = false;
			}
        } else {
            if( cyear<=0 ) {
                $('#error_f_dob_year').show();
                $("#f_dob_year").addClass("validationError");
            } else {
                $('#error_f_dob_year').hide();
            }
            if( cmonth<=0 ) {
                $('#error_f_dob_month').show();
                $("#f_dob_month").addClass("validationError");
            } else {
                $('#error_f_dob_month').hide();
            }
            if( cday<=0 ) {
                $('#error_f_dob_day').show();
                $("#f_dob_day").addClass("validationError");
            } else {
                $('#error_f_dob_day').hide();
            }
            $('#dob_validationCorrectImage').hide();
            $('#dob_validationErrorImage').show();
            dateOkay = false;
        }

        updateNextButton();
	};

    var updateNextButton = function() {
        if (
            usernameOkay    === false ||
            emailOkay       === false ||
            passwordOkay    === false ||
            repeatOkay      === false ||
            parentEmailOkay === false
        ) {
            $("#registration_form .moveButtonRight").addClass("disabled").unbind('click');
        } else {
            $("#registration_form .moveButtonRight").removeClass("disabled").unbind('click').click(function(){executeBlurs(); saveActionReg();});
        }
    };


    $("."+settings.classname).each( function(){

        var self = $(this);
        var fieldName = $(self).attr('name');
		var fieldId = $(self).attr('id');

        $(self).blur(function(){

            var fieldValue = $(self).val();
            var errMesg = new Array();

            var fieldTest = $.checkUserprofileField({
                'formType': settings.formType,
                'fieldName': fieldName,
                'fieldId': fieldId,
                'fieldValue': fieldValue
            });
            if( fieldTest[0] == false ) {
                errMesg = fieldTest[1];
            }

            if( errMesg.length > 0 ) {
				if(fieldId != "f_dob_month" && fieldId != "f_dob_year" && fieldId != "f_dob_day") {
					$('div#'+fieldId+'_ok.ok').hide();
					$('div#'+fieldId+'_help div.reghelpbox').hide();
					$('div#'+fieldId+'_error div.regerrorbox').show();
					$('div#'+fieldId+'_error div.regerrorbox div.content').empty().append(errMesg[0].mesg);
				} else {
					$('div#f_dob_age_or_date_error_text div.regerrorbox').hide();
					$('div#f_dob_ok.ok').hide();
					$('div#f_dob_noselect_error_text div.regerrorbox').show();
					if($('div#f_dob_noselect_error_text div.regerrorbox div.content div#'+fieldId+'_error').text().length == 0){
						$('div#f_dob_noselect_error_text div.regerrorbox div.content').append('<div id="'+fieldId+'_error">'+errMesg[0].mesg+'</div>');
					}
					if($('div#f_dob_noselect_error_text div.content').text().length == 0) {
						$('div#f_dob_noselect_error_text div.regerrorbox').hide();
						$('div#'+fieldId+'_ok.ok').show();
					} else {
						$('div#f_dob_noselect_error_text div.regerrorbox').show();
					}
				}
				$(this).addClass('validationError');
            } else {
                $(this).removeClass('validationError');
				if(fieldId != "f_dob_month" && fieldId != "f_dob_year" && fieldId != "f_dob_day" && fieldName != 'gender') {
					if(fieldId != "f_email" && fieldId != "f_username"){
						$('div#'+fieldId+'_error div.regerrorbox').hide();
						$('div#'+fieldId+'_help div.reghelpbox').hide();
						$('div#'+fieldId+'_ok.ok').show();
					}
				} else if (fieldName == 'gender'){
					$('#register input[name='+fieldName+']').removeClass('validationError');
					$('div#f_male_error div.regerrorbox').hide();
					$('div#f_male_help div.reghelpbox').hide();
					$('div#f_male_ok.ok').show();
				}else {
					$('div#f_dob_error div#f_dob_noselect_error_text div.content div#'+fieldId+'_error').empty();
				}

            }
        });
    });
};



jQuery.nValidateRegistrationOD = function(settings) {
    // default settings
    var settings = $.extend(true, {
        author: 'nez',
        version: '1.0',
        debug: false,
        formType: 'register',
        notAllowedAge: 7,
        parentConfirmationAge: 14
    }, settings);
    var errMesg = new Array(), errString = '';
	var toReturn = true;

    $(".validationError").removeClass('validationError');

    $(".validateMe").each(function(){
        var fieldName = $(this).attr('name');
        var fieldId = $(this).attr('id');
        var fieldValue = $(this).val();

		var fieldTest = $.checkUserprofileField({
                'formType': settings.formType,
                'fieldName': fieldName,
                'fieldId': fieldId,
                'fieldValue': fieldValue
        });
        if( fieldTest[0] == false ) {
            errMesg.push(fieldTest[1]);
        }
    });

	var cyear = parseInt( $("select[name=dob_year]").val() );
	var cmonth = parseInt( $("select[name=dob_month]").val() );
	var cday = parseInt( $("select[name=dob_day]").val() );
    var mesg = '';
    $("#dob select.validationError").removeClass("validationError");
	if( cyear > 0 && cmonth > 0 && cday > 0 ) {
		if( ageCheck( {year: cyear, month: cmonth, day: cday}, settings.notAllowedAge) == false || ageCheck( {year: cyear, month: cmonth, day: cday}, settings.parentConfirmationAge) == true) {
			if( ageCheck( {year: cyear, month: cmonth, day: cday}, settings.notAllowedAge) == false){
				mesg = SPI._langStrings.userprofile.validation.too_young+'';
				toReturn = false;
			}
			$("div#up_registration_parent_email input.validationError").removeClass('validationError');
			$('div#up_registration_parent_email').hide();
		}else if( ageCheck( {year: cyear, month: cmonth, day: cday}, settings.parentConfirmationAge) == false ) {
			$('div#up_registration_parent_email').show();
            $("#up_registration_parent_email input[name=parent_email]").trigger('focus');
            if($("#up_registration_parent_email input[name=parent_email]").val() == ''){
                toReturn = false;
            }
		}
//		if( ageCheck( {year: cyear, month: cmonth, day: cday}, settings.notAllowedAge) == false ) {
//			mesg = SPI._langStrings.userprofile.validation.too_young+'';
// 			$('div#f_dob_error div#f_dob_age_or_date_error_text div.content').empty().append(mesg);
//			toReturn = false;
//		}
		var dateOk = true;
		if ((cmonth==4 || cmonth==6 || cmonth==9 || cmonth==11) && cday==31) {
			  dateOk = false;
		}
		if (cmonth == 2) { // check for february 29th
			  var isleap = (cyear % 4 == 0 && (cyear % 100 != 0 || cyear % 400 == 0));
			  if (cday > 29 || (cday==29 && !isleap)) {
					dateOk = false;
			  }
		}
		if( !dateOk ) {
			mesg = SPI._langStrings.userprofile.validation.invalid_date+'';
 			$('div#f_dob_error div#f_dob_age_or_date_error_text').empty().append(mesg);
            $("#dob input").addClass('validationError');
            $('#dob_validationCorrectImage').hide();
            $('#dob_validationErrorImage').show();
			toReturn = false;
		}
	} else {
        toReturn = false;
    }

    if( errMesg.length > 0 ) {
        $(errMesg).each(function(i,val){
			if(val[0].id != "f_dob_month" && val[0].id != "f_dob_year" && val[0].id != "f_dob_day") {
				$('div#'+val[0].id+'_ok.ok').hide();
				$('div#'+val[0].id+'_help div.reghelpbox').hide();
				$('div#'+val[0].id+'_error div.regerrorbox').show();
				$('div#'+val[0].id+'_error div.regerrorbox div.content').empty().append(val[0].mesg);
//				$('#'+val[0].id).not('input[type="radio"]').addClass('validationError');
				$('#'+val[0].id).addClass('validationError');
			}else {
				$('div#f_dob_noselect_error_text div.regerrorbox').show();
				if($('div#f_dob_noselect_error_text div.regerrorbox div.content div#'+val[0].id+'_error').text().length == 0){
					$('div#f_dob_noselect_error_text div.regerrorbox div.content').append('<div id="'+val[0].id+'_error">'+val[0].mesg+'</div>');
				}
				$('#'+val[0].id).addClass('validationError');
			}
        });

		if($('div#f_dob_error').children().length == 0) {
			$('div#f_dob_error').hide();
		} else {
			$('div#f_dob_error').show();
		}
		if($(".validationError").size() > 0){
			toReturn = false;
		}
    }

	if($('div#f_dob_error').children().length == 0) {
		$('div#f_dob_error').hide();
	} else {
		$('div#f_dob_error').show();
	}
    return toReturn;
};

jQuery.nValidateForgotPasswordRT = function(settings) {
    // default settings
    var settings = $.extend(true, {
        debug: false,
        classname: 'validateMe'
    }, settings);

    $("."+settings.classname).each( function(){
        var self = $(this);
        var fieldName = $(self).attr('name');
		var fieldId = $(self).attr('id');

        $(self).focus(function(){
            var fieldValue = $(self).val();

            if(fieldValue == ''){
                $('#'+fieldId+'_ok').hide();
                $('#'+fieldId+'_error').hide();
                $('#'+fieldId+'_help').show();

                //$(this).removeClass('validationError');
            }
        });

        $(self).blur(function(){
            var fieldValue = $(self).val();

            var fieldTest = $.checkUserprofileField({
                'formType': settings.formType,
                'fieldName': fieldName,
                'fieldId': fieldId,
                'fieldValue': fieldValue
            });

            $('#'+fieldId+'_help').hide();

            if (fieldTest[0] == false) {
                var errorMessage = fieldTest[1][0].mesg;

                $('#'+fieldId+'_ok').hide();
                $('#'+fieldId+'_error .main .content').empty().append(errorMessage);
                $('#'+fieldId+'_error').show();

                $(this).addClass('validationError');
            } else {
                $('#'+fieldId+'_error').hide();
                $('#'+fieldId+'_ok').show();

                $(this).removeClass('validationError');
            }
        });
    });
};

jQuery.nValidateForgotPasswordOD = function(settings) {
    // default settings
    var settings = $.extend(true, {
        debug: false,
        classname: 'validateMe'
    }, settings);
    var isOK = true;

    $("."+settings.classname).each( function(){
        var self = $(this);
        var fieldName = $(self).attr('name');
		var fieldId = $(self).attr('id');
        var fieldValue = $(this).val();

		var fieldTest = $.checkUserprofileField({
                'formType': settings.formType,
                'fieldName': fieldName,
                'fieldId': fieldId,
                'fieldValue': fieldValue
        });

        $('#'+fieldId+'_help').hide();

        if (fieldTest[0] == false) {
            var errorMessage = fieldTest[1][0].mesg;

            $('#'+fieldId+'_ok').hide();
            $('#'+fieldId+'_error .main .content').empty().append(errorMessage);
            $('#'+fieldId+'_error').show();

            $(this).addClass('validationError');
            isOK = false;
        } else {
            $('#'+fieldId+'_error').hide();
            $('#'+fieldId+'_ok').show();

            $(this).removeClass('validationError');
        }
    });

    return isOK;
};

loadExternalPrefs_callback = function(prefsdata, prefserrors) {
	if(prefsdata.length == 0) {
		window.location = '/';
		return;
	}

	if(prefsdata[0].avatar !== undefined) {
		$('img.userAvatar').css('background-image',"url('"+SPI.sprintf(SPI._settings.global.avatar_url_big, prefsdata[0].avatar)+"')");
	} else {
		$('img.userAvatar').css('background-image',"url('/img/_/profile/dummy_big.jpg')");
	};
	$('div.avatar img.userAvatar').load(function () {
	  $('div.avatar img.userAvatar').css('visibility','visible');
	});

	var uname = new Array();
	uname.push(SPI.getURLparam("username"));

	$('div#maincontent div.breadcrumb h4,span#up_leftbox_username, #profilecontent span.username').text(uname[0]);
	$('div.navigation a').each(function(){
		$(this).attr('href', $(this).attr('href') + '?username='+uname[0]);
	});

	/* If privacy=="0" (public) then load public external profile data */
	if(prefsdata[0].privacy == "0") {
		$.profilar.loadExternalProfiles(uname, function(data, errors) {
			$('div#profilecontent').show();

			if(isNaN(data[0].age)) {
				$('td#up_leftbox_age').text('Unknown');
			} else {
				$('td#up_leftbox_age').text(data[0].age);
			};

			if(data[0].gender == "m") {
				$('td#up_leftbox_gender').text(SPI._langStrings.userprofile.male);
			} else {
				$('td#up_leftbox_gender').text(SPI._langStrings.userprofile.female);
			};
		}, ['username', 'gender', 'age']);

		SPI.handlers.run('userprofile', []);

	} else {
		// If it is your profile, redirect to profile page.
		if (uname[0] == $.profilar.forService().username) {
			SPI.reloadSite(SPI._settings.global.my_profile_page);
		}

		/* Display that the profile is private */

		$("#leftbox_privacybox,div#privateprofile").show();
		$("table#profileData").hide();
		$.profilar.loadExternalProfiles(uname, function(data, errors) {
			$('div#maincontent div.breadcrumb h4').text(data[0].username);
		}, ['username']);
	};

	// Filling awards
	SPI.achievements.init();
	SPI.achievements.getAchievementsCountForUser(function(data){
		try{
			tmp = data.hyscor.resultset.total || 0;
		}catch(e){
			tmp = 0;
		};
		$('div#userinfo span#awardsCount, #profilecontent span.awardsCount').html(tmp);
	},uname);

	// Filling points
	SPI.highscore.init();
	SPI.highscore.getUserLevel(function(data){
		try{
			tmp = data.hyscor.level || 0;
		}catch(e){
			tmp = 0;
		};
		fillPoints(tmp,false,true,false);
	},uname);

	$("#userinfo").show();
};



// NIE RUSZAC BO ZABIJE
jQuery.nValidateUserprofileOnDemand = function(settings) {
    // default settings
    var settings = $.extend(true, {
        author: 'nez',
        version: '1.0',
        debug: false,
        formType: 'register',
        notAllowedAge: 7,
        parentConfirmationAge: 14,
        layer: ''
    }, settings);

    var errMesg = new Array(), errString = '';
	var toReturn = true;

    $("div#"+settings.layer+" .validationError").removeClass('validationError');

    $("div#"+settings.layer+" .validateMe").each(function(){

        var fieldName = $(this).attr('name');
        var fieldId = $(this).attr('id');
        var fieldValue = $(this).val();

        var fieldTest = $.checkUserprofileField({
                'formType': settings.formType,
                'fieldName': fieldName,
                'fieldId': fieldId,
                'fieldValue': fieldValue
            });
        if( fieldTest[0] == false ) {
            errMesg.push(fieldTest[1]);
        }

    });

    if( errMesg.length > 0 ) {
        $(errMesg).each(function(i,val){
        	displayError = val[0].mesg;
			$('div#'+val[0].id+'_ok.ok').hide();
			$('div#'+val[0].id+'_help div.reghelpbox').hide();
			$('div#'+val[0].id+'_error div.regerrorbox').show();
			$('div#'+val[0].id+'_error div.regerrorbox div.content').empty().append(displayError);
        	$('div#'+val[0].id).addClass('validationError');
        });
        toReturn = false;
    }

    return toReturn;
};

// NIE RUSZAC BO ZABIJE
jQuery.nValidateUserprofileRealtime = function(settings) {
    // default settings
    var settings = $.extend(true, {
        author: 'nez',
        version: '1.0',
        debug: false,
        formType: 'register',
        notAllowedAge: 7,
        parentConfirmationAge: 14,
        classname: 'validateMe'
    }, settings);

	var errors = [];
	errors[''+settings.layer] = [];

	var checkIfInErrors = function(errors,obj) {
        for( var i = 0 ; i<errors.length; i++ ) {
            if( errors[i].id == obj.id ) return true;
        }
        return false;
    };

    var removeError = function(errors, id) {
        for( var i = 0 ; i<errors.length; i++ ) {
            if( errors[i].id == id ){
                errors.splice(i, 1);
                $("#"+settings.layer+" #"+id).removeClass('validationError');
                return;
            };
        }
        return;
    };

    $("#"+settings.layer+" ."+settings.classname).each( function(){

        var self = $(this);
        var fieldName = $(self).attr('name');
        var fieldId = $(self).attr('id');

        $(self).blur(function(){
            //$('#'+settings.layer+' .validationErrors').hide();

            var fieldValue = $(self).val();
            var errMesg = new Array();

            var fieldTest = $.checkUserprofileField({
                'formType': settings.formType,
                'fieldName': fieldName,
                'fieldId': fieldId,
                'fieldValue': fieldValue
            });

            if( fieldTest[0] == false ) {
                errMesg = fieldTest[1];
            }

            if( errMesg.length > 0 ) {
				$('div#'+fieldId+'_ok.ok').hide();
				$('div#'+fieldId+'_help div.reghelpbox').hide();
				$('div#'+fieldId+'_error div.regerrorbox').show();
				$('div#'+fieldId+'_error div.regerrorbox div.content').empty().append(errMesg[0].mesg);
				$(this).addClass('validationError');
            } else {
                $(this).removeClass('validationError');
				$('div#'+fieldId+'_error div.regerrorbox').hide();
				$('div#'+fieldId+'_help div.reghelpbox').hide();
				$('div#'+fieldId+'_ok.ok').show();
            }
        });
    });
};
;/*
    @desc common functions for whole SF
    @author macic
*/

// flash message
var hideFlashMessage = function() {
    var layer = $('div#flashMessage');
    if( layer.length>0 ) {
        layer.fadeOut('slow');
    }
};

var showNotificationForSignIn = function() {
    $("#topBox").hide();
    $("#middlePinkBox").hide();
    $("#bottomLeftBox").hide();
    $("#bottomRightBox1").hide();
    $("#bottomRightBox2").hide();
    $("#additionalBox").hide();

    $(".hidenotlogged").hide();

    $('<div class="bad"><div class="text">' + SPI._langStrings.sf_global.have_to_sign_in + '</div></div>').appendTo("#flashMessage");
    $("#flashMessage").show();
    $('a[name="show_login_popup"]').click();
};

var redirectToPublicGalleryImage = function(gamatarid) {
    window.location.href = SPI.sprintf(SPI._settings.myGallery.mygallery_url_details_game, gamatarid);
}

var redirectToParentsReminder = function() {
    window.location.href = SPI._settings.attention.parents_reminder_url;
};

var redirectToSelfReminder = function() {
    // TODO: redirect to self reminder landing page
};

var redirectToProfilePage = function() {
    window.location.href = SPI._settings.myprofile.pageurl;
};

var redirectToMainPage = function() {
    window.location.href = '/';
};

var showPublicProfile = function() {
    $("#publicContainer").removeAttr('style');
};

var showPrivateProfile = function() {
    $("#publicContainer").remove();
    $("#privateContainer").append(SPI.render('private_profile_tpl', {})).show();
};

var attachAvatarHovers = function(){
    $("div.ul_container ul li").hover(function(){
        $(this).addClass('hover');
        $(this).find('.button_group').show().width($(this).find('.button_middle').width() + 16);
    },
    function(){
        $(this).removeClass('hover');
        $(this).find('.button_group').hide();
    });
};

$(document).ready(function() {
    $.profilar.addInitHandler(function(){
        var state = $.profilar.loggedIn();
        changeLoginBox(state);
    });

    // displaying of the shadow box
    $('#shadow').ifixpng();
    $('#loginbox_top').ifixpng();
    $('#loginbox_content').ifixpng();
    $('#loginbox_bottom').ifixpng();

    $('a[name="show_login_popup"]').click(function(e) {
        e.preventDefault();
        // hide flash games
        $('#flashobj').css('visibility', 'hidden');
        $('select').css('visibility', 'hidden');
        $('#gameiframe_js').css('visibility', 'hidden');
        $('#shadow').css('width', $(window).width());
        $('#shadow').css('height', $(document).height());
        //set top margin of login box depend on window size
        setTopMarginForLoginBox();
        $('#shadow').css('display', 'block');

        // clearing of the errors
        $("div#shadow .error").css('display', 'none');
        $("div#shadow #loginslogan").css('display', 'block');
        $('div#shadow input').removeAttr('disabled')
        $('div#shadow input[name=username], div#shadow input[name=password]').val('');
        $('div#shadow input[name=remember]').removeAttr('checked');
    });

    $('.close_login_popup').click(function(e) {
        e.preventDefault();
        $('#shadow').css('display', 'none');
        // show flash games
        $('#flashobj').css('visibility', 'visible');
        $('select').css('visibility', 'visible');
        $('#gameiframe_js').css('visibility', 'visible');
    });

    // change the look of header login box
    // set to public - reusable in integrations
    changeLoginBox = function(state) {
        // nez -----------------------------------------------------------------
        $("div#user_navigation div.loading").hide();
        $("div#user_navigation div.loaded").show();
        //----------------------------------------------------------------------
        if(state) {
            // logged in user
            var avatar_id=$.profilar.getPref('avatar');
            if(avatar_id!='') {
                var normal_src = sprintf(SPI._settings.avatars.small_avatar, avatar_id);
                $("#avatarnormal").attr('src', normal_src);
            } else {
                $("#avatarnormal").attr('src', '/img/userprofile/dummy_small.gif');
            }
            $("#avatardummy").hide();
            $("#avatarnormal").show();
            $("#logout_links").hide();
            $("#login_links").show();
            var username = $.profilar.get('username');
            $("#userloggedin").text(username);

            // fill in my gallery number
            SPI.getUserGalery(username,function(data){
                $('#un_mygallery span').text(data.gamatar.resultset.total);
           },username);
            
            SPI.getUserGames(username,function(data){
                $('#un_mygames span').text(data.length);
           },username);
        } else {
            $("#avatarnormal").hide();
            $("#avatardummy").show()
            // not logged in user
            $("#login_links").hide();
            $("#logout_links").show();
        }
        adjustSize();
    }

    // adjust size of login header box
    var adjustSize = function(){
        $minWidth =
            $("#search_bar .buttonRight").width() +
            $("#search_bar .buttonLeft").width()  +
            $("#search_bar #searchtext").width()  -
            7;

        if ($("#user_navigation .body").width() < $minWidth) {
            $("#user_navigation .body").width($minWidth);
        }
    };

    // usage of popup login box
    var clickActionLoginBox = function() {

        // clear the errors and show the indicator of login
        $("div#shadow .error").css('display', 'none');
        $("div#shadow #loginslogan").css('display', 'block');
        $('div#shadow .loginIndicator').show();

        var username = $('div#shadow input[name=username]').removeAttr('disabled').val();
        var password = $('div#shadow input[name=password]').val();

        $('div#shadow input[name=username]').add('div#shadow input[name=password]').attr('disabled','true');
        $('div#shadow #logmein').unbind('click');

        var ok = true;

        // standard checks
        if( username.length < 3) {
            ok = false;
        } if (password.length < 6 || $('input#f_password_lb').is(':hidden') ) {
            ok = false;
        }

        if (ok) {
            $.profilar.login(username, password, $('div#shadow input[name=remember]')[0].checked, function(errors) {
                if (errors) {
                    var error = errors[0];
                    $('#loginslogan').css('display','none');
                    if (error.code == 403 && error.element == 'banned') {
                        $('#loginsalert_banned').css('display','block');
                    } else {
                        $('#loginsalert_auth').css('display','block');
                    }
                    $('div#shadow input[name=username]').add('div#shadow input[name=password]').removeAttr('disabled');
                    $('div#shadow #logmein').click(clickActionLoginBox);
                    $('div#shadow .loginIndicator').hide();
                } else {
                    $.profilar.checkActivation(true);

                    if ($.profilar.needActivation()) {
                        if ($.profilar.needParentsConfirmation()) {
                            redirectToParentsReminder();
                        } else {
                            redirectToSelfReminder();
                        }
                    } else {
                        window.location.reload();
                    }
                }
            });
        } else {
            $('#loginslogan').css('display','none');
            $('#loginsalert_auth').css('display','block');
            $('div#shadow input[name=username]').add('div#shadow input[name=password]').removeAttr('disabled');
            $('div#shadow #logmein').click(clickActionLoginBox);
            $('div#shadow .loginIndicator').hide();
        }
        return false;
    };

    // logout
    var clickActionLogout = function(){
        $.profilar.clearAll();
        window.location = '/';
        return false;
    };

    var setTopMarginForLoginBox = function() {
        var boxHeight = 415;
        var topMargin;
        var windowHeight;

        if (typeof(window.innerWidth) == 'number') {
            //Non-IE
            windowHeight = window.innerHeight;
        } else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
            //IE 6+ in 'standards compliant mode'
            windowHeight = document.documentElement.clientHeight;
        } else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
            //IE 4 compatible
            windowHeight = document.body.clientHeight;
        } else {
            windowHeight = 0;
        }

        if (windowHeight > boxHeight) {
            topMargin = Math.floor((windowHeight - boxHeight) / 2);
        } else {
            topMargin = 0;
        }

        $("#shadow #loginbox_wrapper").attr(
            "style", "margin: " + topMargin + "px auto 0"
        );
    };

    // assign click to login button
    $('div#shadow #logmein').click(clickActionLoginBox);

    // assign enter button for login form
    $("div#shadow form input").keypress(function(e){
        if ((e.which && e.which == 13) || (e.keyCode &&  e.keyCode == 13)) {
            return clickActionLoginBox();
        } else {
            return true;
        }
    });

    // assign click to logout button
    $("#logoutbtn").click(clickActionLogout);

    var flashMessage = SPI.flashMessage.get();

    if( flashMessage.length==2 && flashMessage[0] != '' ) {
        var layer = $('div#flashMessage');
        if( layer.length>0 ) {
            layer.empty().html('<div class="'+(flashMessage[1]=='true'?'bad':'good')+'"><div class="text">'+flashMessage[0]+'</div></div>').show();
            setTimeout('hideFlashMessage()', 5000);
        }
    }

});
;;
//validation functions
validateBasic = function(data){
	validInfo1 = validateBasicGivenname(data);
	validInfo2 = validateBasicSurname(data);
  if (validInfo1 && validInfo2){
    return {valid:true};
  }else{
    toReturn = {valid:false,invalidFields:[],validFields:[]};
    if(!validInfo1) toReturn.invalidFields.push('givenname');else toReturn.validFields.push('givenname');
    if(!validInfo2) toReturn.invalidFields.push('surname');else toReturn.validFields.push('surname');
    return toReturn;
  };
};

validateBasicGivenname = function(data){
	data.oldgivenname = $.profilar.get('givenname');
	if (typeof(data.oldgivenname) != 'undefined' && data.oldgivenname != '' && typeof(data.givenname) != 'undefined' && data.givenname != '') return true;
	if (typeof(data.oldgivenname) != 'undefined' && data.oldgivenname == '' && typeof(data.givenname) != 'undefined' && data.givenname == '') return true;
	if (typeof(data.oldgivenname) != 'undefined' && data.oldgivenname == '' && typeof(data.givenname) != 'undefined' && data.givenname != '') return true;
	return false
};
livecheckGivenname = function(data){
	if(!validateBasicGivenname(data)){
		$('.error_givenname').show();
		$('.correct_givenname').hide();
	}else{
		$('.error_givenname').hide();
		$('.correct_givenname').show();
	};
	return false;
};
validateBasicSurname = function(data){
	data.oldsurname = $.profilar.get('surname');
	if (typeof(data.oldsurname) != 'undefined' && data.oldsurname != '' && typeof(data.surname) != 'undefined' && data.surname != '') return true;
	if (typeof(data.oldsurname) != 'undefined' && data.oldsurname == '' && typeof(data.surname) != 'undefined' && data.surname == '') return true;
	if (typeof(data.oldsurname) != 'undefined' && data.oldsurname == '' && typeof(data.surname) != 'undefined' && data.surname != '') return true;
	return false
};
livecheckSurname = function(data){
	if(!validateBasicSurname(data)){
		$('.error_surname').show();
		$('.correct_surname').hide();
	}else{
		$('.error_surname').hide();
		$('.correct_surname').show();
	};
	return false;
};

livecheckOld = function(pass){
	$('.error_oldpass').hide();
	if(!validateConfirm(pass)){
		$('.correct_old').hide();
		$('.error_old').show();
	}else{
		$('.correct_old').show();
		$('.error_old').hide();
	};
	return false;
};
livecheckRepeat = function(pass){
	if(validateConfirm(pass) && pass==$('#f_password').val()){
		$('.correct_same').show();
		$('.error_same').hide();
	}else{
		$('.correct_same').hide();
		$('.error_same').show();
	};
	return false;
};

livecheckPassword = function(pass){
	if(!validateConfirm(pass)){
		$('.correct_password').hide();
		$('.error_password').show();
	}else{
		$('.correct_password').show();
		$('.error_password').hide();
	};
	return false;
};


validateConfirm = function(pass){
  if (typeof(pass) != 'undefined' && pass.length > 5) return true;
  return false;
}
validatePass = function(data){
  toReturn = {valid:true,invalid:[],isvalid:[]};
  if (typeof(data.old) != 'undefined' && data.old.length <6){
    toReturn.valid = false;
    toReturn.invalid.push('old');
  }else{
    toReturn.isvalid.push('old');
  };
  if (typeof(data.password) != 'undefined' && data.password.length <6){
    toReturn.valid = false;
    toReturn.invalid.push('password');
  }else{
    toReturn.isvalid.push('password');
  };
  if (typeof(data.password) != 'undefined' && typeof(data.repeat) != 'undefined' && data.password == data.repeat){
	    toReturn.isvalid.push('same');
	  }else{
	    toReturn.valid = false;
	    toReturn.invalid.push('same');
	  };
	  
  if (typeof(data.repeat) != 'undefined' && data.repeat.length <6){
    toReturn.valid = false;
    toReturn.invalid.push('password_repeat');
  }else{
    toReturn.isvalid.push('password_repeat');
  };
 
  return toReturn;
};

var validateEmail = function(value) { // contributed by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/
	return {valid:/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test(value)};
};

$(function(){
	$.profilar.addInitHandler(function(logged) {
        if( !logged ) { 
            return; 
        }
        $('div#change_profile .settingsBox').show();
        $.profilar.load(function(errors) {
           if (errors) {
           } else {
               var uname = $.profilar.get('username') || '';
               $('input[name=password]').val('');
               $('#basic span#f_username').html( uname );
               $('#basic input[name=username]').val( uname );
               $('#basic input[name=givenname]').val($.profilar.get('givenname'));
               $('#basic input#f_old_givenname').val($.profilar.get('givenname'));
               $('#basic input[name=surname]').val($.profilar.get('surname'));
               $('#basic input#f_old_surname').val($.profilar.get('surname'));
               $('#email span#f_email_current').html($.profilar.get('email'));
               var dob = $.profilar.get('dob').split('-');
               dobstr = SPI._langStrings.myprofile.months[dob[1]-1]+' '+dob[2]+', '+dob[0];
               $('#basic span#f_dob').html(dobstr);
               $('#basic input[name=gender][value='+$.profilar.get('gender')+']').attr('checked','checked');
           }
        },['dob', 'gender', 'email', 'givenname', 'surname']);

        $("#basic input[name=givenname]").trigger('focus');        

        // BASIC SAVE
        var saveBasicConfirm = function(){
          $('#saveBasicConfirm .loginIndicator').css('display','inline');
          $('#changeprofileconfirm .error_pass').hide();
          if(validateConfirm($('div#changeprofileconfirm input:first').val())){
              var olds = {'givenname': $.profilar.get('givenname'),'surname':   $.profilar.get('surname')};
              $.profilar.set('givenname', $('#basic input[name=givenname]').val());
              $.profilar.set('surname', $('#basic input[name=surname]').val());
              $.profilar.set('gender', $('input[name=gender]:checked').val());
              $('div#saveBasic span').unbind('click');
              $.profilar.submit($('div#changeprofileconfirm input:first').val(), function(errors) {
                   if (errors) {
                	   	$('#changeprofileconfirm .error_pass').show();
                        $('div#saveBasic span').click(function(){saveBasic(true,$('#f_givenname').val(),$('#f_surname').val());});
                        $('#saveBasicConfirm .loginIndicator').css('display','none');
                   } else {
                	   $('#saveBasicConfirm .loginIndicator').css('display','none');
                       SPI.flashMessage.set( SPI._langStrings.myprofile.profile_saved );
                       SPI.reloadSite( SPI._settings.myprofile.pageurl );
                   }
                }, ['givenname', 'surname', 'gender'] );
          }else{
        	  $('#changeprofileconfirm .error_pass').show();
        	  $('#saveBasicConfirm .loginIndicator').css('display','none');
          };
        };
        
        var saveBasic = function(realSave,gn,sn) {
            $('div#saveBasic span').unbind('click');
            validationInfo = validateBasic({givenname:gn, oldgivenname:$.profilar.get('givenname'), surname:sn, oldsurname:$.profilar.get('surname')});
            if(validationInfo.valid){
               $('.correct_givenname').show();
               $('.correct_surname').show();
               $('.error_givenname').hide();
               $('.error_surname').hide();
            }else{
              $(validationInfo.invalidFields).each(function(){
                $('.error_'+this).show();
                $('.correct_'+this).hide();
              });
              $(validationInfo.validFields).each(function(){
                $('.error_'+this).hide();
                $('.correct_'+this).show();
              });
            }
            $('div#saveBasic span').click(function(){saveBasic(true,$('#f_givenname').val(),$('#f_surname').val());});
            
            if(realSave == true && validationInfo.valid == true){
              $('form#basic,form#email,form#pass').hide();
              $('div#changeprofileconfirm').show();
              $('div#changeprofileconfirm input:first').focus();
              $('#saveBasicConfirm span').click(function(){
                saveBasicConfirm();  
              });
            }
            return false;
        };
        
        $('#f_givenname').focus(function(){
          $('.error_givenname').hide();
          $('.correct_givenname').hide();    
        }).blur(function(){
        	livecheckGivenname({'givenname':$('#f_givenname').val()});  
        });
        
        $('#f_surname').focus(function(){
          $('.error_surname').hide();
          $('.correct_surname').hide();  
        }).blur(function(){
        	livecheckSurname({'surname':$('#f_surname').val()});  
        });
        
        
        $('div#saveBasic span').click(function(){saveBasic(true,$('#f_givenname').val(),$('#f_surname').val());});
        
        // EMAIL SAVE
        var saveEmailConfirm = function(){
        	$('#saveEmailConfirm .loginIndicator').css('display','inline');
        	if(validateConfirm($('div#changeemailconfirm input:first').val())){
        		oldEmail = $.profilar.get('email');
                $.profilar.set('email', $('input#f_email').val());
                $('div#saveBasic span').unbind('click');
                $.profilar.submit($('div#changeemailconfirm input:first').val(), function(errors) {
                     if (errors) {
                          $('#changeemailconfirm .error_pass').show();
                          $('div#saveBasic span').click(function(){saveBasic(true,$('#f_givenname').val(),$('#f_surname').val());});
                          $('#saveEmailConfirm .loginIndicator').css('display','none');
                     } else {
                    	 $('#changeemailconfirm .error_pass').hide();
                    	 $.profilar.triggerEvent({
                             cheetah_sub: {aid: ''+SPI._settings.myprofile.profilar_newsletter_sub_aid, email: oldEmail, newemail: $.profilar.get('email')},
                             email: $.profilar.get('email')
                         }, function(eventId, errors) {                        
                        	 $('#saveEmailConfirm .loginIndicator').css('display','none');
                             SPI.flashMessage.set( SPI._langStrings.myprofile.email_saved );
                             SPI.reloadSite( SPI._settings.myprofile.pageurl );
                         });
                     }
                  }, ['email'] );
            }else{
              $('#changeemailconfirm .error_pass').show();
              $('#saveEmailConfirm .loginIndicator').css('display','none');
            };
          };
          
          
        var saveEmail = function(realSave){
          $('div#saveEmail span').unbind('click');
          emailtoTest = $('#f_email').val();
          validationInfo = validateEmail(emailtoTest);
          if(validationInfo.valid){
            $.profilar.isEmailAvailable( emailtoTest, function(available){
                if (available) {
                    $('.error_email_taken').hide();
                    $('.error_email').hide();
                    $('.correct_email').show();
                    if(realSave == true){
                    	$('form#basic,form#email,form#pass').hide();
                        $('div#changeemailconfirm').show();
                        $('div#changeemailconfirm input:first').focus();
                        $('#saveEmailConfirm span').click(function(){
                        	saveEmailConfirm();  
                        });
                    };
                } else {
                    $('.error_email_taken').show();
                    $('.error_email').hide();
                    $('img.error_email').show();
                    $('.correct_email').hide();
                }
            });
          }else{
            $('.error_email').show();
            $('.correct_email').hide();
          };
          $('div#saveEmail span').click(function(){saveEmail(true)});
          return false;
        };
        
        $('#f_email').focus(function(){
          $('.error_email').hide();  
        }).blur(function(){
          saveEmail(false);  
        });
        
        $('div#saveEmail span').click(function(){saveEmail(true)});
        
        var savePass = function(){
        	$('#pass .loginIndicator').css('display','inline');
        	$('div#savePass span').unbind('click');
        	passToTest = {old:$('#f_old_password').val(),password:$('#f_password').val(),repeat:$('#f_password_repeat').val()};
        	validationInfo = validatePass(passToTest)
        	if(validationInfo.valid){
        		$(validationInfo.isvalid).each(function(){
        			$('.correct_'+this).show();
        			$('.error_'+this).hide();
        		});
        		$.profilar.set('password', $('#f_password').val());
        		$.profilar.submit($('#f_old_password').val(), function(errors) {
	                if (errors) {
	                	$('#pass .loginIndicator').css('display','none');
	                	$('#f_old_password').unbind('focus',function(){
	                		$('#f_old_password').focus()
	                		$('.correct_old').hide()
	                	}).unbind('blur').focus();
	                    $('img.error_old').show(1,function(){
	                    	$('.error_oldpass').show();
	                    	$('#f_old_password').focus(function(){
	                            $('.error_old').hide();
	                            $('.correct_old').hide();
	                            $('.error_oldpass').hide();
	                          }).blur(function(){
	                        	  livecheckOld( $('#f_old_password').val()); 
	                          });
	                    	
	                    });
	                    $('div#savePass span').click(savePass);
	                } else {
	                	$('#pass .loginIndicator').css('display','none');
	                	SPI.flashMessage.set( SPI._langStrings.myprofile.password_saved);
	                    SPI.reloadSite( SPI._settings.myprofile.pageurl );
	                };
        		},['password']);
        	}else{
        		$(validationInfo.isvalid).each(function(){
                  $('.correct_'+this).show();
                  $('.error_'+this).hide();
                });
        		$(validationInfo.invalid).each(function(){
        			$('.correct_'+this).hide();
        			$('.error_'+this).show();
        			if (this == 'password_repeat'){
        				$('img.correct_same').hide();
        				$('img.error_same').show();  
        			};
        		});
        		$('div#savePass span').click(savePass);
        		$('#pass .loginIndicator').css('display','none');
        	};
        	return false;
        };
        $('div#savePass span').click(savePass);
        
        
        $('#f_old_password').focus(function(){
            $('.error_old').hide();
            $('.correct_old').hide();
          }).blur(function(){
        	  livecheckOld( $('#f_old_password').val()); 
          });
        
        $('#f_password').focus(function(){
            $('.error_password').hide();
            $('.correct_password').hide();
          }).blur(function(){
        	  livecheckPassword( $('#f_password').val()); 
        	  livecheckRepeat( $('#f_password_repeat').val()); 
          });
        
        $('#f_password_repeat').focus(function(){
            $('.error_password_repeat').hide();
            $('.correct_password_repeat').hide();
            $('.error_same').hide();
            $('.correct_same').hide();
          }).blur(function(){
        	  livecheckRepeat( $('#f_password_repeat').val()); 
          });
    
    // ENTER KEY LAUNCH
    $('input, select', $('#basic')).keyup(function(e) {
        if(e.keyCode == 13) { $('a#save_basic').trigger('click'); }
    });
    $('input, select', $('#basic_confirmation')).keyup(function(e) {
        if(e.keyCode == 13) { $('a#save_basic_confirmation').trigger('click'); }
        if(e.keyCode == 27) { $('a#cancel_basic_confirmation').trigger('click'); }
    });    
    $('input, select', $('#email')).keyup(function(e) {
        if(e.keyCode == 13) { $('a#save_email').trigger('click'); }
    });
    $('input, select', $('#email_confirmation')).keyup(function(e) {
        if(e.keyCode == 13) { $('a#save_email_confirmation').trigger('click'); }
        if(e.keyCode == 27) { $('a#cancel_email_confirmation').trigger('click'); }
    });
    $('input, select', $('#password')).keyup(function(e) {
        if(e.keyCode == 13) { $('a#save_password').trigger('click'); }
    });

});
});

;/**
 * 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;
})();
;/**
 * 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;
})();
