panfu['debug'] = false;
panfu['errors'] = new Object();
panfu['AJAX_RETRY'] = new Object();
panfu['partnerId'] = 0;

if (typeof(panfu['lang'])=='undefined') {
		panfu['lang']='';
}
var ct_rdy=false;
running = new Array();

function hideLoading()
{
	$("#overlay").hide();
	$('#loading').hide();
}

function showLoading()
{
	$("#overlay").show();
	$('#loading').show();
}

function getGet( name ) {
	name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	var regexS = "[\\?&]"+name+"=([^&#]*)";
	var regex = new RegExp( regexS );
	var results = regex.exec( window.location.href );
	if( results == null )
		return null;
	else
		return results[1];
}

function login_form_show_enter_password() {
    $('#login input[name="login_pass"]').show();
    $('#login #dumb').hide();
}

function form_check_checkbox(div) {
    div = $(div);

    $("span.checkbox", div).removeClass('checked');

    if ($('input[type=checkbox]', div).attr('checked')) {
        $("span.checkbox", div).addClass('checked');
    }
}

/**
 * Initializes popup to be shown later
 *
 * @param {string} id ID of main element, e.g. 'registrationHelpPopup' (without '#')
 * @param {int=} width
 * @param {int=} height
 */
function modalbox_init(id, width, height) {
    $("#" + id).dialog({
        autoOpen: false,
        modal: true,
        resizable: false,
        draggable: false,
        position: 'center',
        width: width != undefined ? width : 'auto',
        height:  height != undefined ? height : 'auto',
        closeOnEscape: false
    });
}

/**
 * Opens popup - it requires popup to be initialized before
 *
 * @see modalbox_init
 *
 * @param id ID of main element, e.g. 'registrationHelpPopup' (without '#')
 */
function modalbox_open(id) {
    $("body").css('overflow', 'hidden');
    $("#" + id).dialog('open');
    $(document).trigger('modalbox.open', id);
}

/**
 * Closes popup
 * 
 * @param id ID of main element, e.g. 'registrationHelpPopup' (without '#')
 */
function modalbox_close(id) {
    $("body").css('overflow', 'auto');
    $("#" + id).dialog('close');
    $(document).trigger('modalbox.close', id);
}

$(document).ready(function() {

	panfu['partnerId'] = getGet('partnerId');
	if (panfu['partnerId']==null) panfu['partnerId'] = 0;

	$('body').append('<div id="overlay"></div><div id="loading"><img src="' + (location.protocol != 'https:' ? "http://content.panfu.com/website" : '') + '/images/loadingAnimation.gif"></div>');
	$("#overlay").css('height',$('body').height());
	hideLoading();

	//ajax retry up to 5 times on timeout.. then reload the page if failed.
    $.ajaxSetup({timeout: 19000});

	$("body").ajaxError(function(event, request, settings,thrownError){
        YI.logger.debug("AJAX error: " + thrownError);

		if (typeof(panfu['AJAX_RETRY'][settings.url])=='undefined') panfu['AJAX_RETRY'][settings.url]=0;
		panfu['AJAX_RETRY'][settings.url]+=1;
		if (panfu['AJAX_RETRY'][settings.url]<5)
			$.ajax(settings);
		else {
			//hideLoading();
			//window.location.href=window.location.href;
		}
	 });

	panfu['check'] = 'false';
	var snd = { 'mode': 'init' };
	$.getJSON(
		YI.get('relative_path')+'includes/token.php?mode=init&callback=?',
		function (data) {
			if (data['check'] != true) {
				$('#pause_time').css('display', 'block');
				colorError('login_pass',false);
				colorError('login_name',false);
				countdown(data['pause']);
				$('#login_error').show();
				$('#login_right').show();
				$('#login_form').remove();
			} else {
				if (data['ct']) {
					var ct = data['ct'];
					$('#register_form').prepend('<input type="hidden" name="ct" value="'+ct+'" />');
				}
				$('#login_form').css('display', 'block');
				if (data['saved'] == true) {
					$('input[name="login_name"]').val(data['name']);
					$('input[name="login_pass"]').val(data['pass']);
					if (!frame) $('#save').css('display', 'none');

					$('#erase').css('display', 'block');
					$('input[name="save"]').attr('checked','checked');
                    form_check_checkbox('#login .checkbox');
				}
				if (data['ct']) {
					ct_rdy=true;
				}
			}
		}
		);

	$('input[name="agb"]').click(function() {
		if (this.checked == true) {
			$('#agb').addClass('hide');
		} else $('#agb').removeClass('hide');
	});

	$('input[name="boy"]').click(function() {
		checkSex();
	});

	$('input[name="girl"]').click(function() {
		checkSex();
	});

	$('input[name="login_submit"]').click(function() {
        $(document).trigger('registration.submit');
		checkLoginData();
		return false;
	});

	unfocused('name','');
	unfocused('email','');
	unfocused('email_confirm','');
	unfocused('login_name','');

    if (document.cookie.length > 0) {
        c_start = document.cookie.indexOf("l_u=");
        if (c_start != -1) {
            c_start = c_start + "l_u".length + 1;
            c_end = document.cookie.indexOf(";", c_start);
            if (c_end == -1) c_end = document.cookie.length;
            unfocused('login_name', unescape(document.cookie.substring(c_start, c_end)));
            $('input[name="login_name"]').val(document.cookie.substring(c_start, c_end));
        }

        c_start = document.cookie.indexOf("l_p=");
        if (c_start != -1) {
            c_start = c_start + "l_p".length + 1;
            c_end = document.cookie.indexOf(";", c_start);
            if (c_end == -1) c_end = document.cookie.length;
            unfocused('login_pass', unescape(document.cookie.substring(c_start, c_end)));
            $('input[name="login_pass"]').val(document.cookie.substring(c_start, c_end));
            login_form_show_enter_password();
        }
    }

	untoolMe('name');
	untoolMe('email');
	untoolMe('email_confirm');
	untoolMe('login_name');
    untoolMe('sex');
    untoolMe('agb');

    if ($(".emailFormatVerificationBox").length) {
        $("#emailFormatVerification form").submit(function() {
            modalbox_close('emailFormatVerification');
            emailFormatVerification();
            return false;
        });

        if ($("#emailFormatVerificationHotmail").length) {
            $("#emailFormatVerificationHotmail input[name=email_verify_submit_proposal]").click(function() {
                modalbox_close('emailFormatVerificationHotmail');
                emailFormatVerificationProposal();
                return false;
            });

            $("#emailFormatVerificationHotmail input[name=email_verify_submit_user_input]").click(function() {
                modalbox_close('emailFormatVerificationHotmail');
                emailFormatVerification();
                return false;
            });
        }
    }
   
    // bind checkbox and radiobutton actions
    $("#register_form label.checkbox").click(function(e) {
        e.preventDefault();

        var checkbox = $("input[type=checkbox]", this);
        var new_value = !checkbox.attr('checked');

        checkbox.attr('checked', new_value);

        $(this).removeClass('checked');

        if (new_value) {
            $(this).addClass('checked');
        }

        if (checkbox.attr('name') == 'agb' && new_value) {
            untoolMe('agb');
        }

        return false;
    });

    $("#register_form label.radiobutton").click(function(e) {
        var radiobutton = $("input[type=radio]", this);

        $("input[type=radio]").each(function() {
            $(this).parent().removeClass('checked');
            $(this).attr('checked', false);
        });

        radiobutton.attr('checked', true);
        $(this).addClass('checked');

        var name = radiobutton.attr('name');

        if (name == 'girl' || name == 'boy') {
            panfu['sex'] = name;
            untoolMe('sex');
        }

        return false;
    });

    // binding events for refactored top bar
    if ($("#top").length) {
        // flags
        $("#top #flags_container .current").mouseenter(function() {
            $("#top #flags_container .switch").show();
        });

        $("#top #flags_container").mouseleave(function() {
            $("#top #flags_container .switch").hide();
        });

        $("#top #flags_container .flag").click(function() {
            document.location = $("a", this).attr('href');
        });

        // login form

        $('#login input[name="login_name"]').focus(function() {
            focused('login_name', $(this).val());
            $(this).removeClass('inactive');
        });

        $('#login input[name="login_name"]').blur(function() {
            if ($(this).val() == '') {
                $(this).addClass('inactive');
            }

            checkLoginUsername($(this).val(), '');
            unfocused('login_name', $(this).val());
        });

        $('#login #dumb').focus(function() {
            login_form_show_enter_password();
            $('input[name="login_pass"]').focus();
        });

        $('#login input[name="login_pass"]').blur(function() {
            if ($(this).val() == '') {
                $(this).hide();
                $('#dumb').show();
            }

            unfocused("login_pass", $(this).val());
        });

        $('input[name="login_pass"]').focus(function() {
            focused("login_pass", $(this).val());
        });

        unfocused('login_pass','');

        var login_checkbox_click = function(e) {
            e.preventDefault();

            var div = $(this).parent();

            var checkbox = $("input[type=checkbox]", div);
            var new_value = !checkbox.attr('checked');

            checkbox.attr('checked', new_value);

            form_check_checkbox(div);

            return false;
        };

        $("#login .checkbox label").click(login_checkbox_click);
        $("#login .checkbox span.checkbox").click(login_checkbox_click);
    }

    $('#dumb_reg').focus(function() {
        $(this).hide();
        $('input[name="pass"]').show();
        $('input[name="pass"]').focus();
    });

    $('input[name="pass"]').blur(function() {
        if ($(this).val() == '') {
            $(this).hide();
            $('#dumb_reg').show();
        }
    });

    unfocused('login_name', '');

    if (document.cookie.length > 0) {
        c_start = document.cookie.indexOf("l_p=");
        if (c_start != -1) {
            c_start = c_start + "l_p".length + 1;
            c_end = document.cookie.indexOf(";", c_start);
            if (c_end == -1) c_end = document.cookie.length;
            unfocused('login_pass', unescape(document.cookie.substring(c_start, c_end)));
        }
    }

    untoolMe('login_pass');

    $('a.popup').click(function() {
        mywind = window.open($(this).attr("href"),"_new","location=1,status=1,scrollbars=1,width=830,height=600");
        mywind.moveTo(0,0);
        return false;
    });

    YI.set('registration.suggestions.loading', false);
    YI.set('registration.suggestions.ready', false);
    YI.set('registration.suggestions.tries', 0);
    YI.set('registration.suggestions.tries.max', 5);

    if (YI.get('username_suggestion')) {
        $("#register_form label.radiobutton").click(function() {
            retrieveUsernameSuggestions();
        });
    }

    modalbox_init("emailFormatVerification", 417, 360);
    modalbox_init("emailFormatVerificationHotmail", 417, 360);
    modalbox_init("registrationHelpPopup", 544, 354);
    modalbox_init("userNameSuggestionPopup", 544, 354);

    $('#userNameSuggestionPopup .submit').click(function() {
        var item = $('#usersuggestion_options').find('.checked').text();
        $('input[name="name"]').val(item);
        panfu['name'] = item;

        modalbox_close('userNameSuggestionPopup');
        revalidateUser();
        return false;
    });
});

function toolMe(name, message, color) {
	if (color !='green') {
		color='red';
	}
	var width = 200;
	var side = 'left';
	switch (name) {
		case 'name':
		case 'email':
		case 'email_confirm':
			width = 350;
			side = 'top';
			break;

		case 'agb':
			width = 200;
			side = 'left';
			break;
		case 'pass':
			width = 250;
			side = 'left';
			break;
		case 'login_name':
		case 'login_pass':
			width = 220;
			side = 'right';

			break;
        
		default:
			width = 200;
			side = 'left';
			break;
	}

	//softoolMe(name, message);

	var shrink = true;
	if (frame) {
		shrink = false;
		side = $("body").css('direction') == 'rtl' ? 'right' : 'left';
		width = 350;
		switch (name) {
			case 'pass':
				width = 150;
				side = $("body").css('direction') == 'rtl' ? 'left' : 'right';
				break;
			case 'login_pass':
				side = 'bottom';
                break;
            case 'email_confirm':
                side = 'bottom';
                width = 250;
                break;
            case 'email':
                side = 'left';
                width = 75;
				break;
            case 'name':
                side = 'top';
                width = 300;
                break;
            case 'sex':
                width = 200;
                break;
            case 'agb':
                width = 200;
                side = 'left';
                break;

		}
	}
    var stick_to;

    if ($.browser.msie && $.browser.version == "6.0" && $("#top").length && name == 'login_name') {
        stick_to = $('#top #login #login_form');

    } else if (name == 'sex' || name == 'agb') {
        stick_to = $('#' + name + '_label');

    } else {
        stick_to = $('input[name="'+name+'"]');
        if (name == 'pass' && !stick_to.is(':visible')) {
            stick_to = $('#dumb_reg');
        }
    }

	stick_to.bt(message,
		{
			trigger: 'none',
			fill: color,
			cssStyles: {color: 'white', fontWeight: 'bold'},
			padding: 5,
	  		cornerRadius: 5,
	  		spikeLength: 20,
	  		spikeGirth: 10,
	  		positions: [side],
	  		clickAnywhereToClose: false,
			shrinkToFit: shrink,
			width:width+'px'
		}
	);

    stick_to.btOn();
}

function softoolMe(name, message){
    if (panfu['tooltips_enabled']) {
        $('input[name="'+name+'"]').attr('title',message);
        $('input[name="'+name+'"]').tooltip({
            track: true,
    //		extraClass: 'red',
            top: -45,
            left: 5,
            fade: 50
        });
    }
}

function untoolMe(name) {
	$('input[name="'+name+'"]').btOff();
	switch (name) {
		case 'name':
		case 'email':
		case 'email_confirm':
			softoolMe(name, panfu['info'][name]);
			break;
        case 'pass':
            $('#dumb_reg').btOff();
            break;
        
        case 'sex':
        case 'agb':
            $('#' + name + '_label').btOff();
            break;

		default:
			break;
	}
}

function focused(name,val){
	if (val == panfu['info'][name]) {
		$('input[name="'+name+'"]').val("");
	}
	$('input[name="'+name+'"]').removeClass('empty_input');
	panfu[name]=null;

}

function unfocused(name, val) {
	if (val == "") {
		$('input[name="'+name+'"]').addClass('empty_input');
		$('input[name="'+name+'"]').val(panfu['info'][name]);
	} else {
		$('input[name="'+name+'"]').removeClass('empty_input');
	}
}

function checkSex() {
	if ( $('input[name="boy"]').attr('checked') == true || $('input[name="girl"]').attr('checked') == true ) {
		$('#sex').addClass('hide');
	} else {
        $('#sex').removeClass('hide');
    }
}

function validateChars(string, mode) {
	if(mode=='pwd'){
		var error_found = false;
		var temp_ph = new Array();
		for (i = 0; i < string.length; i++) {

            temp_ph[i] = string.charCodeAt(i);

            if((temp_ph[i] < 33) || (temp_ph[i] > 126)){

            	error_found = true;
                break;
            }
       }
		return (!error_found);
	}
	//var re = new RegExp('[!"\'¬¨√ü$%&/\\()|{}=?`¬¨¬•*+#<>^.,:;‚Äö√á¬®]');
	//if (mode=='name') re = new RegExp('[!"\'¬¨√ü$%&/\\()|{}=?`¬¨¬•*+#<>^.,:;‚Äö√á¬®@]');

	var re = new RegExp('[!"\'¬¨√ü$%&/\\()|{}=?`¬¨¬•*+#<>^.,:;‚Äö√á¬®]');

	if (mode=='name') {
		//'@' is not allowed for registering
		re = new RegExp('[^-A-Za-z0-9_]');
	}
	matched = string.match(re);

	if ((mode=='name') && (!matched)) {
		re = new RegExp('([0-9].*){6,}');
		matched = string.match(re);
	}

	//alert(string+' flound illegal character:'+string.match(re));
	return (!matched);
}

function validateEmail(email) {
    email = email.toLowerCase();
	var result = email.match(/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/);
    return result != null && result.length > 0;
}

function checkData(mode, string, ip) {

    var checkf = false;
	if (ip=='-1' || ip==-1) {
		checkf = true;
	}

	if (typeof(running[mode]) == 'undefined')  running[mode]=false;
	//mark as error first
	if (string != '' && string!=panfu['info'][mode]) {
		colorWait(mode);

	}
	else {
		colorError(mode, false);
		panfu['errors'][mode] = panfu['missing_message'][mode];
	}
	//then make check
	var success = false;

	if ( string != '' && string!=panfu['info'][mode] ) {
		//alert("if");
		if ( mode == 'name' ) {
			success = validateChars(string, 'name') && (string.length < 20);
		} else if ( mode == 'email' ) {
			success = validateEmail(string);
		} else if ( mode == 'email_confirm') {
            success = string == $("input[name=email]").val();
        }
		//alert(success);
		//alert(running[mode]);

		if (success == true && !running[mode] && mode != 'email_confirm') {
			//alert("inside if");
			running[mode]=true;
			document.body.style.cursor = 'wait';
			// get key
            var encoded_string = encodeURIComponent(string);
			$.getJSON(
				YI.get('relative_path')+'includes/login_functions.php?langId='+panfu['lang']+'&mode=checkdata&string='+encoded_string+'&type='+mode+'&callback=?',
				function (data) {
                    if (YI.logger.isDebugEnabled()) {
                        YI.logger.debug('checkData - finished for [mode=' + mode + "][string=" + string + "]");
                    }

					if ((data['key'] != 'error') && (data['ref'] != '') && (data['bl'] == true)) {
						sendToInfoServer(mode, string, data['key'], checkf);
                        
					} else if (data['bl'] == false) {
						//re-set error (delayed)
						if (mode=='name') {
                            colorError(mode, true, panfu['error_message']['name_bad']);
                        } else {
                            colorError(mode, true, panfu['error_message'][mode]);
                        }
						document.body.style.cursor = 'default';
						running[mode] = false;
					} else {
                        YI.logger.debug('General error in checkData - reload forced');
						window.location.reload();
					}
				}
			);

		}
        else if (success == true && mode =='email_confirm') {
            colorError(mode, false);
            panfu[mode] = string;
        }
		else if ( success == false) {
            var msg = ((mode == 'name') && (string.length > 20)) ? 'name_too_long' : mode;
			colorError(mode, true, panfu['error_message'][msg]);
		}
	}

	if (success == false) {
		panfu[mode] = '';
		if (checkf) {
            checkFields();
        }
	}


}


/**
 * Check if the given pandaname is allowed (not blacklisted) and not used by someone else.  If username_suggestion is
 * deactivated, this method performs the final checks immediately.
 * 
 * @param string pandaname  Name of the panda being checked
 */
function finalNameCheck(pandaname) {
    if (YI.get('username_suggestion')) {
        var string = pandaname;
        var mode = 'name';
        var checkf = false;
        running[mode] = true;
        YI.logger.debug('Checking the pandaname for usability: ' + pandaname);

        $.getJSON(
            YI.get('relative_path')+'includes/login_functions.php?langId='+panfu['lang']+'&mode=checkdata&string='+string+'&type='+mode+'&callback=?',
            function (data) {
                if ((data['key'] != 'error') && (data['ref'] != '') && (data['bl'] == true)) {
                    YI.logger.debug('Pandaname ' + pandaname + ' is not blacklisted');
                    YI.set('name_error', false);
                    sendToInfoServer(mode, string, data['key'], false, true);

                } else if (data['bl'] == false) {
                    document.body.style.cursor = 'default';
                    running[mode] = false;

                    YI.logger.debug('Pandaname ' + pandaname + ' is on the blacklist');

                } else {
                    YI.logger.debugWithObject('Other error occured on checking pandaname: ', data);
                    window.location.reload();
                }
            }
        );
        
    } else {
        YI.logger.debug('Username suggestion not activated, passing on to finalCheck');
        finalCheck(pandaname);
    }
}

/**
 * If a the last check of the panda name resulted in an already used name and USERNAME_SUGGESTION is turned on,
 * retrieve a list of alternate panda names.  If no error occured on the last name check, perform the final checks.
 */
function doNameChecking() {
    if (YI.get('name_error')) {
        if (YI.get('username_suggestion')) {
            YI.logger.debug('Executing username suggestions');

            if (YI.get('registration.suggestions.ready')) {
                showUsernameSuggestions(getUsernameSuggestions(panfu['name'], panfu['sex']));
            } else {
                if (!YI.get('registration.suggestions.loading')) {
                    retrieveUsernameSuggestions();
                }

                var tryCount = YI.get('registration.suggestions.tries');
                var maxTries = YI.get('registration.suggestions.tries.max');
                tryCount++;

                YI.logger.debug('Postponing showing popup, it is not ready yet');

                if (tryCount > maxTries) {
                    YI.logger.debug('Max number of tries to get suggestion exceeded [tried=' + tryCount + "]" +
                            "[max=" + maxTries + "], showing error");
                    colorError('name', true, panfu['error_message']['name_bad']);
                } else {
                    YI.logger.debug("Next try in 1s");
                    YI.set('registration.suggestions.tries', tryCount);
                    setTimeout('doNameChecking()', 1000);
                }
            }
        } else {
            YI.logger.debug('No username suggestion activated');
        }
    } else {
        finalCheck(panfu['name']);
    }
}

function getUsernameSuggestions(username, sex) {
    return YI.get('registration.suggestions.data.' + username + '.' + sex);
}

function setUsernameSuggestions(username, sex, value) {
    return YI.set('registration.suggestions.data.' + username + '.' + sex, value);
}

/**
 * Retrieve a list of alternate usernames for the given panda.
 *
 * @param {string=} pandaname Current panda name to generate alternatives for. If left empty, value from panfu[] array
 * will be taken
 */
function retrieveUsernameSuggestions(pandaname) {
    if (pandaname == undefined) {
        pandaname = panfu['name'];
    }

    if (!YI.get('username_suggestion')) {
        return;
    }

    if (!pandaname) {
        YI.logger.debug('[retrieveUsernameSuggestions] Pandaname is empty!');
        return;
    }

    if (!YI.get('name_error')) {
        YI.logger.debug('[retrieveUsernameSuggestions] There is no error in name, no need to retrieve suggestions');
        return;
    }

    var sex_available_values = ['girl', 'boy'];
    var sex = panfu['sex'];

    if ($.inArray(sex, sex_available_values) == -1) {
        YI.logger.debug('[retrieveUsernameSuggestions] Sex field is not set yet, skipping retriving suggestions till sex will be selected');
        return;
    }

    var usernameSuggestions = getUsernameSuggestions(pandaname, sex);

    if (usernameSuggestions) {
        YI.logger.debug('[retrieveUsernameSuggestions] Suggestions for [' + pandaname + '] are already available: ' + usernameSuggestions);
        return;
    }

    if (YI.get('registration.suggestions.loading')) {
        YI.logger.debug('[retrieveUsernameSuggestions] Suggestions for [' + pandaname + '] are still being loaded');
        return;
    }

    YI.logger.debug('[retrieveUsernameSuggestions] Retrieving suggestions for username: ' + pandaname);

    setUsernameSuggestions(pandaname, sex, undefined);
    YI.set('registration.suggestions.loading', true);
    YI.set('registration.suggestions.ready', false);

    $.ajax({
        url: YI.get('relative_path')+'includes/login_functions.php?langId='+panfu['lang']+'&mode=usernameSuggestion&username='+pandaname+'&sex='+panfu['sex'] +'&type=usernameSuggestion&callback=?',
        context: { pandaname: pandaname, sex: sex },
        dataType: 'jsonp',
        success: function (data) {
            YI.logger.debugWithObject('[retrieveUsernameSuggestions] Suggestions from Server:', data);

            if (data['result']) {
                setUsernameSuggestions(this.pandaname, this.sex, data['data']);
            } else {
                YI.logger.debug('[retrieveUsernameSuggestions] No suggestions available!');
                colorError('name', true, panfu['error_message']['name_bad']);
            }
            
            YI.set('registration.suggestions.loading', false);
            YI.set('registration.suggestions.ready', true);
        },
        error: function(xmlHttpRequest, textStatus, errorThrown) {
            YI.logger.debugWithObject('[retrieveUsernameSuggestions] Error fetching suggestions!', errorThrown);
            colorError('name', true, panfu['error_message']['name_bad']);

            YI.set('registration.suggestions.loading', false);
            YI.set('registration.suggestions.ready', false);
        }
    });
}

/**
 * Show the username suggestions based on the response from authentitaction server.
 * @param object data  Object with two keys: 'result' is a boolean and shows wether the list is ok and 'data' contains
 *     an array of username alternatives.
 */
function showUsernameSuggestions(data) {
    YI.logger.debug('Providing suggestions to the user');
    
    var head = YI.get('username_suggestion_pattern').replace('XXXXXXXXX', '"' + panfu['name'] + '"');
    $('#usersuggestion_headline').text(head);
    // data = {'data': ['foobar', 'frodo', 'sepp', 'nix', 'da']};

    var options = $('#usersuggestion_options');
    options.empty();

    var first = true;
    for (var i=0; i < 3; i++) {
        var name = data[i];
        if (name != undefined) {
            options.append('<div class="checkbox' + (first ? ' checked' : '') + '">' + name + '</div>');
            first = false;
        }
    }
    options.find('.checkbox').click(function() {
        options.find('.checkbox').removeClass('checked');
        $(this).addClass('checked');
    });

    modalbox_open('userNameSuggestionPopup');
}

/**
 * If an alternate username was selected this method double checks that username again.  This is neccessary to make
 * the final pass work by retrieving a 'secondKey' from information server.  If the username check succeeds, the final
 * checking will be called.
 */
function revalidateUser() {
    var mode = 'name';
    var string = panfu['name'];
    $.getJSON(
        YI.get('relative_path')+'includes/login_functions.php?langId='+panfu['lang']+'&mode=checkdata&string='+string+'&type='+mode+'&callback=?',
        function (data) {
            if ((data['key'] != 'error') && (data['ref'] != '') && (data['bl'] == true)) {
                running[mode] = true;
                sendToInfoServer(mode, string, data['key'], false, false, function() {
                    finalCheck(string);
                });

            } else {
                colorError('name', true, panfu['error_message']['name_bad']);
            }
        }
    );
}

function checkLoginUsername(name, ip) {
	if (validateChars(name, null) != true) {
		colorError('login_name',true, panfu['error_message']['name']);
	} else {
		colorError('login_name',false);
	}
}

function checkPassword(pwd, _name) {
	if (pwd != '') {
		var all = ( _name == 'pass' ) ? 'true' : 'false';
		var send = { 'mode': 'passcheck', 'string': pwd, 'all': all };
		if (all=='true' && ($('input[name="name"]').attr('value').lastIndexOf(pwd)>-1) ) {
			colorError(_name, true, panfu['error_message']['password']);
		}
		else if (all == 'true'){
			running[_name]=true;
			document.body.style.cursor = 'wait';
			$.getJSON(
				YI.get('relative_path')+'includes/login_functions.php?langId='+panfu['lang']+'&mode=passcheck&string='+pwd+'&all='+all+'&callback=?',
				function (data) {
					if (running[_name]) {
						if (data['return'] == true) {
							colorError(_name, false);
						} else {
							colorError(_name, true, panfu['error_message']['pwd_short']);
						}
					}
					document.body.style.cursor = 'default';
					running[_name]=false;
				}
			);
		}
	} else {
		colorError(_name, false);
		panfu['errors'][_name]=panfu['missing_message']['pass'];
	}
}

function sendToInfoServer(mode, string, key, checkf, name_check, success_cbk) {
	var methodName = { 'name': 'checkUsername', 'email': 'checkEmail', 'final': 'registration' };
	tmp = (mode == 'final') ? 'name' : mode;
	// Check mode

	if (methodName[mode] != '' && running[mode]) {
		document.body.style.cursor = 'wait';
        var encoded_string = encodeURIComponent(string);
        if (mode == 'final') {
            var parts = string.split('&');
            for (var ix in parts) {
                var items = parts[ix].split('=');
                if (items.length > 1) {
                    items[1] = encodeURIComponent(items[1]);
                }
                parts[ix] = items.join('=');
            }
            encoded_string = parts.join('&');
        }
        
        YI.logger.debug('sending to InfoServer: mode=' + mode + ', string=' + encoded_string + ', Checkfields: ' + checkf + ', Namecheck:' + name_check);

		$.ajax({
            url: panfu['infoserverurl'] + methodName[mode] + '?' + tmp + '=' + encoded_string + '&format=json&key=' + key + '&callback=?',
            method: 'GET',
            dataType: 'jsonp',
            context: {
                name_check: name_check,
                success_cbk: success_cbk,
                mode: mode,
                checkf: checkf,
                string: string
            },
            success: function (data) {
                if (data['return'] == 'true') {
                    // SPECIAL
                    if ((this.mode == 'final') && (panfu['debug'] == true)) alert("You were successfully written in the DB =)");
                    if (this.mode == 'final') {
                        $(document).trigger('registration.success', data);

                        try {
                            localTracker._trackPageview('/virtual-signup.php');
                        } catch(err) {}

                        try {
                            globalTracker._trackPageview('/virtual-signup.php');
                        } catch(err) {}

                        try {
                            partnerTracker._trackPageview('/virtual-signup.php');
                        } catch(err) {}

                        if (GWO_ENABLED) {
                            try {
                                var gwoTracker = _gat._getTracker(GWO_EXPERIMENT_ACCOUNT);
                                gwoTracker._trackPageview(GWO_EXPERIMENT + "/goal");
                            } catch(err) {
                            }
                        }

                        $.cookie('token', null);
                        $.cookie('login_count', null);

                        doAfterRegister(panfu['name'], panfu['pass']);
                        doLogin(panfu['name'], panfu['pass'], panfu['partnerId']);
                    }
                    if (panfu['debug'] == true) {
                        YI.logger.debug(data['return']);
                    }

                    if ((running[this.mode] == 'true') || (running[this.mode] == true)) {
                        colorError(this.mode, false);
                    }

                    if (data['secondkey']) {
                        panfu['key2'] = data['secondkey'];
                    }

                    if (this.success_cbk != null && this.success_cbk != 'undefined') {
                        this.success_cbk();
                    }

                } else {
                    YI.logger.debugWithObject('sendToInfoServer failed: ', data);

                    if (this.mode == 'final') {
                        YI.logger.debug('general error on final check - reload forced');
                        window.location.reload(); // fatal error ?
                    }
                    
                    if (this.mode == 'name') {
                        if (YI.get('username_suggestion')) {
                            YI.set('name_error', true);
                            colorError(this.mode, false);
                            YI.logger.debug("Username is not correct, but not showing error, name suggestion popup will be shown");
                            retrieveUsernameSuggestions(this.string);
                        } else {
                            colorError(this.mode, true, panfu['error_message']['name_bad']);
                        }
                    } else {
                        if (this.mode == 'email') colorError(this.mode, true, panfu['error_message']['email_bad']);
                        else colorError(this.mode, true, panfu['error_message'][this.mode]);
                    }
                    if (panfu['debug'] == true) YI.logger.debug('return from server: ' + data['return']);
                }

                document.body.style.cursor = 'default';
                running[this.mode] = false;
                panfu[this.mode] = this.string;
                if (this.checkf) checkFields();

                if (this.name_check) {
                    doNameChecking();
                }
            }
        });
	}
}

function eraseUser() {
	$.getJSON(
		YI.get('relative_path')+'includes/login_functions.php?mode=erase',
		function(data) {
			if (data['return'] == true) {
				$('input[name="login_name"]').val('');
				$('input[name="login_pass"]').val('');
				$('#save').css('display', 'block');
				$('#support').css('display', 'block');
				$('#erase').css('display', 'none');
			}
		}
	);
}

function colorError(id, error, message) {
	error = (!defined(error)) ? true : error;
	soft = false;
	if (typeof(message)=='undefined' || message.length<1) {
		msg = panfu['missing_message'][id];
		soft = true;
	}
	else {
		msg = message;
	}
	if (typeof(msg)!='string') msg = '';
	$('input[name="'+id+'"]').removeAttr("readonly");
	$('input[name="'+id+'"]').removeClass('yellowBorder');
	$('input[name="'+id+'"]').removeClass('redBorder');
	$('input[name="'+id+'"]').addClass('greenBorder');
	$('#'+id).addClass('hide');
	untoolMe(id);
	if (error == true) {
		panfu['errors'][id]=msg+' ';
		if (soft) {
			softoolMe(id,msg);
		}
		else {
			$('input[name="'+id+'"]').removeClass('greenBorder');
			$('input[name="'+id+'"]').addClass('redBorder');
			$('#'+id).removeClass('hide');
			toolMe(id,msg);
		}

        $(document).trigger('registration.validation.error', id);
	} else {
		panfu['errors'][id]='';
	}
    if (error == false && (id == 'name' ? !YI.get('name_error') : true)) {
        $(document).trigger('registration.validation.success', id);
    }
}

function colorWait(id){
	untoolMe(id);
	$('input[name="'+id+'"]').attr("readonly",true);
	$('input[name="'+id+'"]').removeClass('greenBorder');
	$('input[name="'+id+'"]').removeClass('redBorder');
	$('input[name="'+id+'"]').addClass('yellowBorder');
	var message = panfu['checking_message'][id];
	toolMe(id,message,'green');

}


function checkFields() {
    //validate_error = null;
	//wait for all checkings complete
	for(tag in running) if (running[tag]) {
        setTimeout("checkFields()", 1000);
		return;
	}

	// Check if name + email were already checked
	if (typeof(panfu['name']) == 'undefined' || panfu['name']==null) {
		checkData('name', $('input[name="name"]').val(), '-1'); return;
	}

	if (typeof(panfu['email']) == 'undefined'  || panfu['email']==null) {
		checkData('email', $('input[name="email"]').val(), '-1'); return;
	}

	if (typeof(panfu['email_confirm']) == 'undefined'  || panfu['email_confirm']==null) {
		checkData('email_confirm', $('input[name="email_confirm"]').val(), '-1'); return;
	}

	checkPassword($('input[name="pass"]').val(),'pass');

	// Assign form fields to window array (which stores globals so we have variable variables in JS =)) (yvan)
	var fields = new Array('name', 'email', 'email_confirm', 'pass','newsletter', 'agb');
	for (var i=0; i < fields.length; i++) {
		panfu[fields[i]] = $(':input[name="'+fields[i]+'"]').val();
	}

    var empty = true;
    var emfields = new Array('name', 'email', 'email_confirm', 'pass');
    for (var i=0; i < emfields.length; i++) {
        var item = $(':input[name="' + emfields[i] + '"]');
        if (!item.hasClass('empty_input') && item.val() != '') {
            empty = false;
        }
    }
    if (empty) {
        empty = ! (document.login_new.boy.checked || document.login_new.girl.checked);
        if (empty) {
            empty = (! document.login_new.agb.checked);
        }
    }

	// 1- Check if hidden field "subject" is empty, if not, it might be a robot =)
	//alert("subject="+$('input[name="subject"]').val());
    if ($('input[name="subject"]').val() == '') {
        //alert("inside if");
        // Are all fields empty?
        if (empty) {
            showRegistrationPopup();
            return;
        }

        // 2- Check required fields (sex and agb are special cases)
        if ((document.login_new.boy.checked == false) && (document.login_new.girl.checked == false)) {
            colorError('sex', true);
        } else {
            panfu['sex'] = (document.login_new.boy.checked == true) ? 'boy' : 'girl';
            colorError('sex', false);
        }
        if ((document.login_new.agb.checked == false)) {
            colorError('agb', true);
        } else {
            colorError('agb', false);
        }

        // Show the tool tips for each error
        var errorPrint = "";
        for (tmpName in panfu['errors']) {
            var err_tmp = panfu['errors'][tmpName];
            if (typeof(err_tmp)=='string' && err_tmp.length>1) {
                errorPrint += '<li>';
                errorPrint += err_tmp;
                errorPrint += '</li>';

                toolMe(tmpName, err_tmp);
            }
        }

        // Errors
        if (errorPrint.length == 0) {
            if ($("#emailFormatVerification").length) {
                var value = encodeURIComponent(panfu['email']);
                YI.logger.debug('Verifing Email: ' + value);
                $.ajax({
                    async: false,
                    url: YI.get('relative_path') + 'includes/login_functions.php?langId=' + panfu['lang'] + '&mode=checkEmailFormat&email=' + value + '&callback=?',
                    dataType: 'jsonp',
                    success: function(data) {
                        YI.logger.debug("Verifing email [" + value + "], result: [" + data['return'] + "], info: [" + data['info'] + "]");

                        if (data['return'] == 'INVALID' || data['return'] == 'INVALID_FORMAT') {
                            $("#emailFormatVerification").show();
                            $("#emailFormatVerification input[name=email_verify]").val(panfu['email']);
                            modalbox_open('emailFormatVerification');
                        } else if (data['return'] == 'INVALID_FORMAT_HOTMAIL') {
                            var tmp_email = panfu['email'].split("@");
                            $("#emailFormatVerificationHotmail input[name=email_verify_proposal]").val(tmp_email[0] + "@hotmail.com");
                            modalbox_open('emailFormatVerificationHotmail');
                            
                        } else {
                            finalNameCheck(panfu['name']);
                        }
                    }
                });
            } else {
                finalNameCheck(panfu['name']);
            }
        }
    }
}

/**
 * Show email format verification popup
 *
 * @param {event=} event
 * @param {string} field
 */
function emailFormatVerification(event, field) {
    field = field == null ? 'email_verify' : field;

    if (YI.logger.isDebugEnabled()) {
        YI.logger.debug('Running emailFormatVerification for [field=' + field + ']');
    }

    var value = $(".emailFormatVerificationBox:visible input[name=" + field + "]").val();

    if (event == 'secondCheck' || value != panfu['email']) {
        // email was changed in this window, perform validation once more

        $("input[name=email]").val(value);
        $("input[name=email_confirm]").val(value);

        // verify data if this method is not executed after waiting
        if (event != 'secondCheck') {
            checkData('email', $("input[name=email]").val(), null);
        }

        // waiting till data verification will be finished, and then running the same method skipping data check
        for (tag in running) {
            if (running[tag]) {
                if (YI.logger.isDebugEnabled()) {
                    YI.logger.debug("emailFormatVerification: checkData on email field is still running for data: [" + $("input[name=email]").val() + "]");
                }

                setTimeout("emailFormatVerification('secondCheck', '" + field + "')", 1000);
                return false;
            }
        }

        if (!panfu['errors']['email']) {
            finalNameCheck(panfu['name']);
        }
    } else {
        finalNameCheck(panfu['name']);
    }

    return false;
}

/**
 * Show email format verification with proposal (e.g. for Hotmail)
 *
 * @param {event=} event
 */
function emailFormatVerificationProposal(event) {
    emailFormatVerification(event, 'email_verify_proposal');
    return false;
}

function finalCheck(pandaname) {
    YI.logger.debug('Finally checking pandaname using InfoServer:' + pandaname);
	var send = {
		'mode' : 'checkdata',
		'mode2': 'final',
		'string': pandaname,
		'ct' : $('input[name="ct"]').val()
	};
	//showLoading();
	$.getJSON(
		YI.get('relative_path')+'includes/login_functions.php?langId='+ panfu['lang']+'&mode=checkdata&mode2=final&string='+pandaname+'&ct='+$('input[name="ct"]').val()+'&callback=?',
		function (data) {
			if ((data['return'] != 'error') && (data['key'] != 'error')) {
				var refID = $('input[name="refID"]').val();
				var partnerId = $('input[name="refID"]').val(); //previous refID
				if(partnerId == '0') partnerId = '';
				var NUMS = $('input[name="NUMS"]').val();
				var referrer = $('input[name="referrer"]').val();
				var newsletter = (document.login_new.newsletter.checked == true) ? 'true' : 'false';
				var str = panfu['name']+'&password='+panfu['pass']+'&email='+panfu['email'];
				//str += '&code='+panfu['promocode'];
				//str += '&refID='+refID;
				if((refID.length <= 8) && (refID.length >= 0) && (parseInt(refID) == Number(refID)))
				{
					str += '&refID='+refID;
				}else
				{
					str += '&refID=';
				}
				//sending empty value - InfoServer waits for this - partnerId is now sended through variable with the same name
				str += '&nums='+NUMS+'&referrer='+referrer;

				str += '&partnerId='+partnerId;
				str += '&sex='+panfu['sex'];
				//str += '&birthday='+panfu['bday']+'-'+panfu['bmonth']+'-'+panfu['byear'];
				str += '&chatID=1&newsletter='+newsletter;
				var zanox_id = $.cookie('zanox_id');
				var tduid = $.cookie('TRADEDOUBLER');
				if((zanox_id == null) && (tduid == null))
				{
					str += '&advertiser_id=';
				}else if(zanox_id != null)
				{
					str += '&advertiser_id='+zanox_id;
				}else if(tduid != null)
				{
					str += '&advertiser_id='+tduid;
				}

				if (typeof(panfu['win']) == 'string')
				{
					str += '&win='+panfu['win'];
				}
				if (typeof(panfu['code']) == 'string')
				{
					str += '&code='+panfu['code'];
				}

                str += '&dataShare=' + ($("input[name=data_share]").attr('checked') ? 'true' : 'false');

                var country = $("input[name=country]").val();

                if (country && country != 'UNKNOWN') {
                    str += '&country=' + country;
                }

				str += '';
				running['final']=true;
				sendToInfoServer('final', str, panfu['key2'],false);
			} else
			{
				//hideLoading();
				YI.logger.debug("an error occured...");
			}
		}
	);
}

function checkLoginData(user,pw) {
	if (ct_rdy) {
        checkLoginData_rdy(user, pw);
    } else {
        YI.logger.debug("Token is not ready for checkLoginData");
        setTimeout("checkLoginData('" + user + "','" + pw + "')", 1000);
    }
}

function checkLoginData_rdy(user,pw) {
	if (typeof(user)!="string") user = $('input[name="login_name"]').val();
	if (typeof(pw)!="string") pw = $('input[name="login_pass"]').val();
	var ct = $('input[name="ct"]').val();
	var count;
	var save = ($('input[name="save"]').attr('checked') == true).toString();
	var send = {
		'mode': 'logincheck',
		'name': user,
		'pass': pw,
		'ct' : ct,
		'save': save
	};
	if (user == '') colorError('login_name', true);
	if (pw == '') {
        colorError('login_pass', true);
        colorError('dumb_pass', true);
    }

    YI.logger.debug("Sending login check to server [login=" + user + "]");

	$.getJSON(
		YI.get('relative_path')+'includes/login_functions.php?langId='+panfu['lang']+'&mode=logincheck&name='+user+'&pass='+pw+'&ct='+ct+'&save='+save+'&callback=?',
		function(data) {
			YI.logger.debug("Received response from server [status=" + data['return'] + "]");

			count = data['count'];
			if (count < 6) {
				if (data['return'] == true) {
					colorError('login_pass',false);
					colorError('login_name',false);

					doLogin(data['name'], data['pass'],panfu['partnerId']);
					return;
				} else if (data['return'] == false) {
					/* WRONG USER */

					if (user != 'undefined' && user != null) colorError('login_name',true, panfu['error_message']['userpw']);
					if (pw != 'undefined' && pw != null) {
                        colorError('login_pass', true, panfu['error_message']['userpw']);
                        colorError('dumb_pass', true, panfu['error_message']['userpw']);
                    }

					untoolMe('login_pass');
					untoolMe('dumb_pass');

					$('#login_left').css('display', 'block');
					$('#login_right').css('display', 'block');
					$('#login_error').css('display', 'block');

				if (count == 4) showWarning();
				if (count > 4) hideWarning();
				}
			} else {
				// countdown

				countdown(600);
				$('#pause_time').css('display', 'block');
				colorError('login_pass',false);
				colorError('login_name',false);
				$('#login_left').css('display', 'block');
				$('#login_right').css('display', 'block');
				$('#login_error').css('display', 'block');
				$('#login_form').remove();

			}
		});

}

function showRegistrationPopup() {
    untoolMe('name');
    untoolMe('email');
    untoolMe('email_confirm');
    untoolMe('login_name');
    untoolMe('sex');
    untoolMe('agb');

    modalbox_open('registrationHelpPopup');
}

/* Helpers */

function defined(x) {
	return (typeof(x) != undefined);
}

function debugObject(obj) {
	var ret = '';
	for (prop in obj) {
		ret += prop+': '+obj[prop]+"\n";
	}
	return ret;
}

function countdown(seconds) {
	var min = Math.round((seconds/60)-0.5);
	var sec = seconds - (min * 60);
	sec = (sec < 10) ? '0'+sec : sec;
	$('#pause_amount').html(min+':'+sec);
	if (seconds > 0) {
		seconds -= 1;
		setTimeout('countdown("'+seconds+'")', 1000);
	} else if (seconds == 0) window.location.href = window.location.href;
}

function showWarning() {
	untoolMe('login_pass');
	untoolMe('login_name');
	$('#warning').css('display', 'block');
	setTimeout('hideWarning()', 20000);
}

function hideWarning() {
	$('#warning').fadeOut('slow');
}

function trackingPixelCheck(userId)
{
	var id;
	id = Number(userId);
	if((id != 0) && (id != NaN))
	{
		var send = {
			'mode': 'trackingPixelCheck',
			'pid': userId
		};
		$.getJSON(
			YI.get('relative_path')+'includes/login_functions.php?mode=trackingPixelCheck&pid='+userId+'&callback=?',
			function(data) {
				if(data['tracking_pixel'] != '')
				{
					$('body').append(data['tracking_pixel']);
				}
			});
	}
}

function doAfterRegister(user,pw) {
	var exdate=new Date();
	exdate.setSeconds(exdate.getSeconds()+30);
	document.cookie="ot_u=" +escape(user)+";expires="+exdate.toGMTString()+";path=/";
	document.cookie="ot_p=" +escape(pw)+";expires="+exdate.toGMTString()+";path=/";
}
