Tauri.ListenersModel = Class.create({
    listeners   : null,
    
    initialize : function(){
        this.listeners = $H();
    },

    addListener : function(ev,fn) {
        var evList = this.listeners.get(ev);
        if ( !evList) {
            evList = $A();
        }
        evList.push(fn);
        this.listeners.set(ev, evList);
    },
    triggerListeners : function(ev) {
       var evList = this.listeners.get(ev);
       if (evList){
           evList.each(function(fn){
               fn();
           });
       }
    }
});

Tauri.RegistrationField = Class.create(Tauri.ListenersModel, {
	fieldHandler  : null, // uchwyt do calego pola
    
    EV_REGISTRATION_FAILED : 'registrationFailed',
    EV_FIELD_CHANGE_ERROR_DISPLAY : 'errorDisplayChanged',

    getHandler : function() {
      return this.fieldHandler;
    },
    getPostData : function() {
        return $H();
    },
    getTooltip : function() {
        return null;
    },
    getErrorMsg : function() {
        return null;
    },
    fieldReady : function() {
        return true;
    },
    setFieldFromData : function() {
        return false;
    },
    startCheck : function() {
        return false;
    },
    endCheck : function() {
        return false;
    },
    errorIsDisplayed : function() {
        return false;
    },
    clearField : function() {
        return false;
    },
    validate : function() {
        return true;
    }
});

Tauri.RegistrationEditableField = Class.create(Tauri.RegistrationField, {
    required    : true,
    was_validated : false,
    message       : '',
    msgTop        : null,
    valid         : false,
    value         : null,
    label         : null,
    fieldLabel    : null,
    fieldIcon     : null, // uchwyt tylko do ikony
    field         : null, // uchwyt konkretnego pola
    fieldBox      : null, // uchwyt do diva z zawartoscia konkretnego pola
    apiFieldId  : false,
    tooltipTxt : '',
    minlength   : null,
    maxlength   : null,
    errorDisplayed  : false,

    initialize  : function($super) {
            $super();
            this.fieldLabel     = new Element('div').addClassName('label').insert(new Element('p').insert(this.label));
            this.fieldIcon      = new Element('div').addClassName('icon');
            this.fieldBox       = new Element('div').addClassName('field');
            this.fieldHandler   = new Element('div').addClassName('formline').insert(
                                            new Element('div').addClassName('data').insert(this.fieldIcon).insert(this.fieldBox)
                                  ).insert(this.fieldLabel);
        this.createHandlers();
    },
    getErrorMsg : function() {
      return this.msgHandler;
    },
    getTooltip : function() {
      return this.tooltipHandler;
    },
    hideTooltip : function() {
      this.tooltipHandler.hide();
    },
    showTooltip : function() {
        if(!this.errorDisplayed) {
            this.tooltipHandler.show();
        }
    },
    makeInvalid : function(msg){
        this.setMsg(msg);
        this.valid = false;
        this.endCheck();
        this.displayError();
    },
    setMsg  : function(msg) {
      if(msg != null) {
          this.message = msg;
          this.msgBox.update(this.message);
      }
    },
    supressErrorDisplay : function() {
        this.msgHandler.hide();
    },
    displayError : function() {
        this.errorDisplayed = true;
        this.tooltipHandler.hide();
        this.clearStatusClasses();
        if(this.message != null && this.message != '') {
            this.msgHandler.show();
        }
        this.fieldHandler.addClassName('red');
        this.triggerListeners(this.EV_FIELD_CHANGE_ERROR_DISPLAY);
    },
    errorIsDisplayed : function() {
        return this.errorDisplayed;
    },
    displayOk   : function() {
       this.clearField();
       this.msgHandler.hide();
       this.fieldHandler.addClassName('green');
    },
    clearField : function() {
        this.errorDisplayed = false;
        this.clearStatusClasses();
        this.msgHandler.hide();
        this.setMsg('');
        this.hideTooltip();
        this.fieldIcon.removeClassName('check');
    },
    clearStatusClasses : function() {
        this.getHandler().removeClassName('red');
        this.getHandler().removeClassName('green');
    },
    getPostData : function($super) {
        var data = $super();
        data.set(this.apiFieldId,this.getValue());

        return data;
    },
    validate   : function() {
        if(this.required) {
            this.was_validated = false;
        } else {
            this.was_validated = true;
        }
        this.clearField();
        this.startCheck();
        if (this.getValue().strip() === '' && this.required) {
            this.setMsg(Tauri.Lang.get('fieldRequired'));
            this.valid = false;
        } else {
            this.valid = true;
        }
    },
    fieldReady : function($super) {
        $super();
        if(!this.valid || !this.was_validated) {
            return false;
        }
        return true;
    },
    startCheck : function() {
        this.clearField();
        this.fieldIcon.addClassName('check');
    },
    endCheck : function() {
        this.fieldIcon.removeClassName('check');
    },
    getStep : function() {
        return this.step;
    },
    setFieldFromData    : function(data) {
       var isOk = true;
       var t = this;
       if(data == false) {
           t.makeInvalid(Tauri.Lang.get('internalError'));
           isOk = false;
       } else {
           if(data.code > 0) {
               if(data.code == 1) {
                   var errors = $H(data.errors);
                   if(errors) {
                       errors.each(function(e) {
                            if(e.key == t.apiFieldId) {
                                t.makeInvalid(e.value);
                                isOk = false;
                            }
                       });
                   }
               } else {
                    t.makeInvalid(Tauri.Lang.get('internalError'));
                    isOk = false;
               }
           }
       }
       if(isOk && t.required) {
           t.valid = true;
           t.was_validated = true;
           t.endCheck();
           t.displayOk();
       } else if (!t.required){
           t.endCheck();
       }
       t.triggerListeners(t.EV_FIELD_CHANGED);
    },

    createHandlers  : function() {
        this.msgBox = new Element('div').addClassName('content').insert(this.message);
        var style = 'top : ' + this.msgTop + 'px; left : 676px;';
        if(Tauri.Registration.isRtl()) {
            style = 'top : ' + this.msgTop + 'px; right : 676px;'
        }
        this.msgHandler = new Element('div').addClassName('reg-error').setStyle(style)
                            .insert(new Element('div').addClassName('arrow'))
                            .insert(new Element('div').addClassName('head')
                                .insert(new Element('div').addClassName('corner left'))
                                .insert(new Element('div').addClassName('corner right'))
                                .insert(new Element('div').addClassName('mid'))
                            )
                            .insert(this.msgBox)
                            .insert(new Element('div').addClassName('foot')
                                .insert(new Element('div').addClassName('corner left'))
                                .insert(new Element('div').addClassName('corner right'))
                                .insert(new Element('div').addClassName('mid'))
                            ).hide();
        this.tooltipHandler = new Element('div').addClassName('reg-tip').setStyle(style)
                            .insert(new Element('div').addClassName('arrow'))
                            .insert(new Element('div').addClassName('head')
                                .insert(new Element('div').addClassName('corner left'))
                                .insert(new Element('div').addClassName('corner right'))
                                .insert(new Element('div').addClassName('mid'))
                            )
                            .insert(new Element('div').addClassName('content')
                                .insert(this.tooltipTxt)
                            )
                            .insert(new Element('div').addClassName('foot')
                                .insert(new Element('div').addClassName('corner left'))
                                .insert(new Element('div').addClassName('corner right'))
                                .insert(new Element('div').addClassName('mid'))
                            ).hide();
    }
});

Tauri.RegistrationDropDown = Class.create(Tauri.RegistrationEditableField, {
    itemsList : null,
    items  : null,
    oldChosen : null,
    lastMovedNextSiblings : false,

    initialize  : function($super){
         this.msgTop = 58;
         this.was_validated = true;
         this.valid = true;
         $super();
         this.fieldBox.insert(this.itemsList);
         if(this.items.keys().length > 1) {
             this.fieldIcon.addClassName('arrow');
             Event.observe(this.fieldHandler, 'mouseout', this.listMouseout.bind(this));
             Event.observe(this.fieldHandler, 'mouseover', this.listMousein.bind(this));
             Event.observe(this.fieldHandler, 'click', this.iconClick.bind(this));
         } else {
            this.getHandler().addClassName('justOneElem');
         }
    },
    itemSelected : function(item) {
        if(!this.oldChosen) {
            this.oldChosen = item.get('handler');
            this.lastMovedNextSiblings = this.oldChosen.nextSiblings();
        }
        var handler = item.get('handler');

        if(this.lastMovedNextSiblings.length > 0) {
            this.lastMovedNextSiblings[0].insert({before : this.oldChosen});
        } else {
            this.itemsList.insert(this.oldChosen);
        }
        
        this.lastMovedNextSiblings = handler.nextSiblings();
        this.oldChosen = handler;
        this.itemsList.insert({before : handler});
        if(navigator.userAgent.match(/msie/i)) {
            if(this.wasEverClicked) {
                this.iconClick();
            } else {
                this.wasEverClicked = true;
            }
        }
    },
    listMouseout : function() {
       var t = this;
       this.hideList = setTimeout(t.hideItemslist.bind(t),1000);
    },
    listMousein  : function() {
        clearTimeout(this.hideList);
    },
    hideItemslist : function() {
        if(this.hideList > 0) {
            this.fieldHandler.removeClassName('act');
        }
    },
    getPostData : function() {
        var data = $H({world : this.selectedId});
        return data;
    },
    iconClick   : function() {
        this.fieldHandler.toggleClassName('act');
    }
});

Tauri.RegistrationWorldsList = Class.create(Tauri.RegistrationDropDown, {
    selectedId  : null,
    worldHandlers : $H(),
    worlds  : $H(),
    label : Tauri.Lang.get('worldLabel'),

    EV_WORLD_CHANGED : 'worldChanged',
    SERVER_NOT_RESPONDING   : 'serverNotResponding',

    initialize  : function($super) {
        this.itemsList = new Element('div').addClassName('list');
        var t = this;
        var post = null;
        t.worlds = Tauri.Worlds.getWorlds();
        t.worlds.values().sort(Tauri.Worlds.compareRegistrationWorlds).each(function(w){
        	if (t.selectedId == null){
        		t.selectedId = w.get('id');
        	}
            post = {world : w.get('id')};
            TauriAPI.request('get-planets-info', post, $H({onComplete : t.setPlayers.bind(t)}));
            t.worlds.get(w.get('id')).set('response',true);
            t.worlds.get(w.get('id')).set('playersHandler', new Element('span').addClassName('players').insert(Tauri.Lang.get('Please wait..')));
            t.worlds.get(w.get('id')).set('handler', new Element('a').writeAttribute({href : 'javascript:void(0)'})
                                .observe('click',t.worldSelected.bind(t, w.get('id')))
                                .insert(w.get('name'))
                                .insert(' (')
                                .insert(new Element('img').writeAttribute({src : 'images/homepage/registration/players.gif', alt : 'Friends / Players'}))
                                .insert(t.worlds.get(w.get('id')).get('playersHandler'))
                                .insert(')')
                                );
            t.itemsList.insert(t.worlds.get(w.get('id')).get('handler'));
         });
         this.items = this.worlds;
         $super();
         this.fieldLabel.update(new Element('p').addClassName('server').insert(this.label));
         this.fieldHandler.addClassName('serverlist');
         this.worldSelected(this.selectedId);
    },
    getValue : function() {
        return this.selectedId;
    },
    setPlayers : function(data,post) {
        if(!data && this.selectedId == post.world) {
            this.worlds.get(post.world).set('response',false);
        } else {
            var responseCode = parseInt(data.code);
            if(responseCode == 0) {
                var sum = 0;
                var planet = null;
                data.info.each(function(i){
                    planets = i.evalJSON();
                    planets.each(function(p) {
                        sum += parseInt(p.players);
                    });
                });
                this.worlds.get(post.world).set('players',sum);
                this.worlds.get(post.world).get('playersHandler').update(' '+sum+' ');
            } else {
               this.worlds.get(post.world).set('response',false);
               this.worlds.get(post.world).get('playersHandler').update('');
            }
       }
    },
    worldSelected    : function(worldId) {
       var world = this.worlds.get(worldId);
       if(!world) {
           return false;
       };
       this.clearField();
       this.valid = true;
       this.was_validated = true;
       var oldSelected = this.selectedId;
       this.selectedId = world.get('id');
       this.itemSelected(world);
       if(!world.get('response')) {
            this.makeInvalid(Tauri.Lang.get('internalError'));
       }
       if(worldId != oldSelected) {
            this.triggerListeners(this.EV_WORLD_CHANGED);
       }
    }
});

Tauri.serverInformationField = Class.create(Tauri.RegistrationField, {
    worlds   : null,

    initialize : function($super,worlds){
        $super();
        this.worlds = worlds;
        this.fieldHandler = new Element('p').writeAttribute('id','testServerInformation').insert(Tauri.Lang.get('testServerInformation')).hide();
    },

    toggleInfo : function() {
        if(this.worlds.worlds.get(this.worlds.selectedId).get('isTest') == true) {
           this.fieldHandler.show();
       } else {
           this.fieldHandler.hide();
       }
    }
});

Tauri.ShowRealMailsField = Class.create(Tauri.RegistrationField, {
    initialize : function($super,showMailsFlag,worlds){
        $super();
        this.showMailsFlag = showMailsFlag;
        this.fieldHandler = new Element('p').insert(Tauri.Lang.get('realEmailsInformation'));
        this.toggleMailsNote(worlds);
    },
    
    toggleMailsNote : function(worlds) {
        var directWorldActivation = worlds.worlds.get(worlds.getValue()).get('directActivation');
        if(this.showMailsFlag && !directWorldActivation) {
            this.fieldHandler.show();
        } else {
            this.fieldHandler.hide();
        }
    }
});

Tauri.AcceptTermsField = Class.create(Tauri.RegistrationField, {
    initialize : function($super){
        $super();
        var acceptRulesLink = '<a target="_blank" href="?action_code=home_page&page=conditions">' + Tauri.Lang.get('registrationRulesLink') + '</a>';
        var fillInValues = {PLAY: Tauri.Lang.get('PLAY'), registrationRulesLink: acceptRulesLink};
        this.fieldHandler = new Element('p').insert(Tauri.Lang.get('acceptRules').interpolate(fillInValues));
    }
});

Tauri.RegistrationInputField = Class.create(Tauri.RegistrationEditableField,{
    EV_FIELD_CHANGED  : 'fieldChanged',
    EV_FIELD_BLUR     : 'fieldBlur',
    IGNORED_KEY_CODES : $A('9'), // keycodes ignored in keyup context
    
    reactOnKeyUp : true,

    initialize :  function($super, attributes){
        $super();
        this.field = new Element('input').writeAttribute(attributes)
                        .observe('blur', this.onBlur.bind(this))
                        .observe('focus', this.onFocus.bind(this))
                        .observe('change', this.onChange.bind(this));
        if (this.reactOnKeyUp) {
            this.field.observe('keyup',this.onChange.bindAsEventListener(this));
        }
        this.value = $F(this.field);
        this.fieldBox.insert(this.field);
    },
    onChange    : function(ev) {
        var runKeyUp = true;
        this.IGNORED_KEY_CODES.each(function(code) {
            if(ev.keyCode == code) {
                runKeyUp = false;
                throw $break;
            }
        });
        if(runKeyUp) {
           this.validate();
           if(!this.valid) {
               this.displayError();
           }
           this.triggerListeners(this.EV_FIELD_CHANGED);
        }
    },
    onFocus : function() {
        this.showTooltip();
        if(this.errorDisplayed) {
            this.displayError();
        }
    },
    onBlur  : function() {
        this.hideTooltip();
        this.triggerListeners(this.EV_FIELD_BLUR);
    },
    getValue : function() {
        return $F(this.field);
    },
    setValue : function(val) {
        this.field.value = val; 
    },
    validate    : function($super) {
        $super();
        if(this.valid) {
            if (this.minlength > 0 && this.maxlength > 0 && (this.minlength > this.field.getValue().length || this.maxlength < this.field.getValue().length)) {
                this.setMsg(Tauri.Lang.get('wrongLength'));
                this.valid = false;
            }
        }
    }
});

Tauri.RegistrationEmailField = Class.create(Tauri.RegistrationInputField,{
    EV_MESSAGE_DISPLAYED : 'messageDisplayed',
    
    initialize  : function($super) {
        this.reactOnKeyUp = false;
        this.msgTop = 133;
        this.tooltipTxt = Tauri.Lang.get('emailTooltip');
        this.apiFieldId = 'email';
        this.label = Tauri.Lang.get('emailLabel');
        this.required = false;
        $super({type : 'text'});
        this.fieldHandler.hide();
    },
    changeRequired : function(worlds) {
        var directWorldActivation = worlds.worlds.get(worlds.getValue()).get('directActivation');
        if(directWorldActivation) {
            this.required = false;
            this.fieldLabel.update(new Element('p').insert(Tauri.Lang.get('emailLabel')));
            this.fieldHandler.hide();
            this.valid = true;
            this.was_validated = true;
        } else {
            this.required = true;
            this.valid = false;
            this.fieldLabel.update(new Element('p').insert(Tauri.Lang.get('emailLabelRequired')));
            this.fieldHandler.show();
        }
    },
    
    showTooltip : function($super) {
        $super();
        this.triggerListeners(this.EV_MESSAGE_DISPLAYED);
    },
    showEmailField : function(){
        this.getHandler().show();
        this.showTooltip();
    },
    validate : function($super) {
        $super();
        if(this.required && !this.valid) {
            this.makeInvalid();
        } else if(this.required) {
            var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
            if(reg.test(this.getValue()) != false) {
                this.displayOk();
            } else {
                this.makeInvalid(Tauri.Lang.get('wrongEmail'));
            }
        } else {
            this.endCheck();
        }
        this.was_validated = true;
    }
});

Tauri.RegistrationLoginField = Class.create(Tauri.RegistrationInputField,{
    worlds   : null,
    invalidChars : ['<','>','\&'],

    initialize  : function($super,worlds) {
        this.msgTop = 102;
        this.tooltipTxt = Tauri.Lang.get('loginTooltip');
        this.apiFieldId = 'login';
        this.label = Tauri.Lang.get('loginLabel');
        this.minlength = 1;
        this.maxlength = 30;
        this.reactOnKeyUp = false;
        $super({type : 'text'});
        this.worlds = worlds;
    },
    validate : function($super) {
        $super();
        if(this.valid) {
            if(this.previousRequest) {
                this.previousRequest.cancel();
            }
            var post = {login : this.getValue(), world : this.worlds.selectedId};
            
            if(this.getValue().search(this.invalidChars.join('|')) != -1){
            	var data = new Object;
            	data.code = 1;
            	data.errors = new Object;
            	data.errors.login = [Tauri.Lang.get('loginInvalidChars').interpolate({invalidChars: this.invalidChars.join(' ').escapeHTML()})];
            	this.setFieldFromData(data);
            }else{
            	this.previousRequest = TauriAPI.request('login-exists', post, $H({onComplete : this.setFieldFromData.bind(this)}));
            }
            
        } else {
            this.endCheck();
        }
    }
});

Tauri.RegistrationCaptchaField = Class.create(Tauri.RegistrationInputField,{
    captcha : null,
    worlds  : null,
    captchaLength : 5,
    finished    : false,

    EV_FIELD_FINISHED   : 'captchaFilledIn',
    EV_FIELD_UNFINISHED : 'captchaFilledIn',

    initialize  : function($super,worlds) {
        this.msgTop = 104;
        this.tooltipTxt = Tauri.Lang.get('captchaTooltip');
        this.label = Tauri.Lang.get('codeLabel');
        this.apiFieldId = 'captcha';
        this.required = true;
        this.was_validated = true;
        this.valid = true;
        $super({type : 'text'});
        this.worlds = worlds;
        this.imageHandler = new Element('img').writeAttribute({id : 'r-captcha-img', width : 175, height : 45, src : ''});
        this.imageFieldHandler = new Element('div').addClassName('captcha').insert(this.imageHandler);
        this.innerFieldHandler = this.fieldHandler;
        this.fieldHandler = new Element('div').insert(this.imageFieldHandler).insert(new Element('div').addClassName('clear')).insert(this.innerFieldHandler);
        Event.observe(this.field,'keyup', this.onKeyup.bind(this));
        Event.observe(this.field,'blur', this.onBlur.bind(this));
        this.getCaptcha();
    },
    setCid  : function(cid) {
        this.cid = cid;
    },
    getCid : function(){
        return this.cid;
    },
    setSid  : function(sid) {
        this.sid = sid;
    },
    getSid : function() {
        return this.sid;
    },
    getCaptcha : function() {
       if(this.previousRequest) {
            this.previousRequest.cancel();
       }
       var post = {world : this.worlds.selectedId};
       this.previousRequest = TauriAPI.request('captcha', post, $H({onComplete : this.setCaptcha.bind(this)}));
    },
    getCaptchaLength : function() {
        return this.captchaLength;
    },
    getImageFieldHandler : function() {
        return this.imageFieldHandler;
    },
    setCaptcha : function(data) {
       if(data.code == 0) {
            this.imageHandler.setAttribute('src',data.captcha.src);
            this.setCid(data.captcha.cid);
            this.setSid(data.session);
       }
    },
    onKeyup : function($super) {
       this.validate();
    },
    onFocus : function($super) {
        this.clearField();
        this.setValue('');
        $super();
    },
    onBlur : function($super) {
        $super();
        this.validate();
    },
    isFinished : function() {
        return this.finished;
    },
    makeInvalid : function($super,msg) {
        $super(msg);
        this.innerFieldHandler.addClassName('red');
        this.getCaptcha();
    },
    getPostData : function($super) {
        var data = $super();
        data.set('cid', this.getCid());
        data.set('sessid', this.getSid());
        return data;
    },
    clearStatusClasses : function($super) {
        $super();
        this.innerFieldHandler.removeClassName('red');
        this.innerFieldHandler.removeClassName('green');
    },
    validate : function($super) {
        $super();
        if(this.valid) {
            if(this.getValue().length >= (this.getCaptchaLength()) ) {
               this.valid = true;
               this.was_validated = true;
               this.finished = true;
               this.triggerListeners(this.EV_FIELD_FINISHED);
            } else if(this.isFinished()) {
                this.valid = false;
                this.was_validated = true;
                this.triggerListeners(this.EV_FIELD_UNFINISHED);
            }
        }
        this.endCheck();
    }
});

Tauri.RegistrationPasswordField = Class.create(Tauri.RegistrationInputField,{
    
    initialize : function($super){
        this.msgTop = 129;
        this.tooltipTxt = Tauri.Lang.get('registrationPasswordTooltip');
        this.apiFieldId = 'password';
        this.label  = Tauri.Lang.get('passwordLabel');
        this.minlength   = 6;
        this.maxlength   = 30;
        $super({type : 'password'});
    },
    
    validate : function($super){
        $super();
        this.endCheck();
        if(!this.valid) {
            this.displayError();
        } else {
            this.was_validated = true;
            this.displayOk();
        }
    }
});

Tauri.RegistrationRePasswordField = Class.create(Tauri.RegistrationInputField,{
    password : null,

    initialize : function($super,password){
       this.msgTop = 157;
       this.tooltipTxt = Tauri.Lang.get('registrationRePasswordTooltip');
       this.label  = Tauri.Lang.get('retypePasswordLabel');
       $super({type : 'password'});
       this.password = password;
       this.password.addListener(this.password.EV_FIELD_CHANGED,this.validate.bind(this));
    },
    
    validate : function($super){
            $super();
            this.endCheck();
            if(this.getValue().length > 0 && (this.password.getValue().length > 0) ){
                if(this.getValue() != this.password.getValue()) {
                    this.setMsg(Tauri.Lang.get('passMismatch'));
                    this.valid = false;
                    this.displayError();
                } else {
                    this.was_validated = true;
                    this.displayOk();
                }
            }
    }
});

Tauri.Registration = Class.create({
	fields : null,
    stepsHash : null,
    nextStepHandler : null,
    registeredError : false,
    loaded			: false,
    rtl             : null,
    
    EV_REGISTRATION_FAILED : 'registrationFailed',

	initialize : function(showMailsFlag, autoShow, rtl) {
		Event.observe(window, 'load', this.init.bind(this, showMailsFlag, autoShow));
	    Event.observe(window, 'dom:loaded', this.init.bind(this, showMailsFlag, autoShow));
        this.rtl = rtl;
	},
    
	init : function(showMailsFlag, autoShow) {
		if (this.loaded) {
			return;
		}
		this.loaded = true;
        var password = new Tauri.RegistrationPasswordField();
        var worlds = new Tauri.RegistrationWorldsList();
        var login = new Tauri.RegistrationLoginField(worlds);
        var repass = new Tauri.RegistrationRePasswordField(password);
        var captcha = new Tauri.RegistrationCaptchaField(worlds);
        var email = new Tauri.RegistrationEmailField();
        var serverInfo = new Tauri.serverInformationField(worlds);
        var showRealMails = new Tauri.ShowRealMailsField(showMailsFlag, worlds);
        var acceptTerms = new Tauri.AcceptTermsField();
        this.fields = $A();
        this.fields.push($H({
                worlds   : worlds,
                login    : login,
                password : password,
                repass   : repass,
                serverInformation : serverInfo
         }));
         this.fields.push(
         $H({
            captcha  : captcha,
            email    : email,
            showRealMails : showRealMails,
            acceptTerms : acceptTerms
         }));
         this.firstFocusedField = login;
         worlds.addListener(worlds.EV_WORLD_CHANGED,login.validate.bind(login));
         worlds.addListener(worlds.EV_WORLD_CHANGED,captcha.getCaptcha.bind(captcha));
         worlds.addListener(worlds.EV_WORLD_CHANGED,serverInfo.toggleInfo.bind(serverInfo));
         worlds.addListener(worlds.EV_WORLD_CHANGED,showRealMails.toggleMailsNote.bind(showRealMails,worlds));
         worlds.addListener(worlds.EV_WORLD_CHANGED,email.changeRequired.bind(email,worlds));
         captcha.addListener(captcha.EV_FIELD_FINISHED,email.showEmailField.bind(email));
         captcha.addListener(captcha.EV_FIELD_FINISHED,this.validateStep.bind(this));
         captcha.addListener(captcha.EV_FIELD_UNFINISHED,this.validateStep.bind(this));
         captcha.addListener(captcha.EV_REGISTRATION_FAILED, captcha.getCaptcha.bind(captcha));
         worlds.addListener(worlds.SERVER_NOT_RESPONDING,worlds.setFieldFromData.bind(worlds,false));
         email.addListener(email.EV_MESSAGE_DISPLAYED,captcha.hideTooltip.bind(captcha));
         
         worlds.triggerListeners(worlds.EV_WORLD_CHANGED);
        
        
        this.stepsHash = $H();
        var t = this;
        var stepContent = null;
        var stepButtonHandler = null;
        var stepFocusedField = false;
        this.formContent = new Element('form');
        var firstStepFirstItem = true;

        this.fields.each(function(step,index) {
            stepContent = new Element('div').writeAttribute({id : 'step'+index});
            if(index > 0) {
              stepContent.hide();
            } else {
              t.step = index;
            }
            step.each(function(f) {
                stepContent.insert(f.value.getHandler());
                if(firstStepFirstItem) {
                    stepContent.insert(new Element('br'));
                    firstStepFirstItem = false;
                }
                f.value.addListener(f.value.EV_FIELD_CHANGED, t.validateStep.bind(t));
                f.value.addListener(f.value.EV_FIELD_BLUR, t.validateStep.bind(t));
                f.value.addListener(f.value.EV_FIELD_CHANGE_ERROR_DISPLAY, t.displayAtmostOneError.bind(t));
            });
            stepButtonHandler = new Element('input').addClassName('button gray')
                .writeAttribute({type : 'button', value : (index < t.fields.length-1 ? Tauri.Lang.get('NEXT') : Tauri.Lang.get('PLAY'))});
            Event.observe(stepButtonHandler, 'click', (index < t.fields.length-1 ? t.changeStep.bind(t, index+1) : t.register.bind(t)));
            if(index == 0) {
                stepFocusedField = login;
            } else if(index == 1) {
                stepFocusedField = captcha;
            }
            stepContent.insert(new Element('div').addClassName('buttonWrapper').insert(stepButtonHandler));
            t.formContent.insert(stepContent);
            t.setStep(index,stepContent,stepButtonHandler,stepFocusedField);
        });

        var regWindowWrapper = new Element('div').addClassName('regWindowWrapper')
                                    .insert(new Element('div').addClassName('regWindow')
                                        .insert(new Element('div').addClassName('head')
                                            .insert(new Element('div').addClassName('mid'))
                                            .insert(new Element('div').addClassName('corner cleft'))
                                            .insert(new Element('div').addClassName('corner cright'))
                                        )
                                        .insert(new Element('div').addClassName('body').writeAttribute({id : 'regBody'})
                                            .insert(new Element('a').writeAttribute({id : 'registrationClose', href : "javascript:void(0);"}).addClassName("xclose"))
                                            .insert(new Element('div').addClassName('lborder'))
                                            .insert(new Element('div').addClassName('content')
                                                .insert(new Element('h2').insert(Tauri.Lang.get('newRegistration')))
                                                .insert(this.formContent)
                                            )
                                            .insert(new Element('div').addClassName('rborder')))
                                        .insert(new Element('div').addClassName('foot')
                                            .insert(new Element('div').addClassName('mid'))
                                            .insert(new Element('div').addClassName('corner cleft'))
                                            .insert(new Element('div').addClassName('corner cright'))
                                        )
                                      );
        var registrationPage = new Element('div').addClassName('registrationPage');
        var registrationView = new Element('div').addClassName('registrationLayer')
                            .insert(new Element('div').writeAttribute({id : 'blackout'}).addClassName('blackout'))
                            .insert(registrationPage
                                .insert(regWindowWrapper)
                             ).hide();
        this.fields.each(function(step) {
            step.each(function(f){
                regWindowWrapper.insert(f.value.getTooltip());
                regWindowWrapper.insert(f.value.getErrorMsg());
            });
        });

        this.registrationView = registrationView;
        $('pagecontainer').insert({after : registrationView});
        Event.observe(window, 'keypress', this.monitorKeyPress.bind(this));
        Event.observe($('newAccount'), 'click', this.showRegistration.bind(this));
        Event.observe($('blackout'), 'click', t.hideRegistration.bind(t));
        Event.observe(registrationPage, 'click', t.hideRegistration.bind(t));
        Event.observe(regWindowWrapper, 'click', t.hideRegistration.bind(t));
        Event.observe($('regBody'), 'click', function(event) {
            event.stopPropagation();
        });
        Event.observe($('registrationClose'), 'click', t.hideRegistration.bind(t));
        
        if (autoShow){
        	this.showRegistration();
        }
    },
    showRegistration : function() {
       this.registrationView.show();
       this.getStepFocusedField(this.step).field.focus();
    },
    hideRegistration : function() {
        this.registrationView.hide();
    },
    monitorKeyPress : function(e) {
        if(e.keyCode == '27') {
            this.hideRegistration();
        }
    },
    isRtl : function() {
        return !!this.rtl;
    },
    setStep : function(step,content,buttonHandler,focusedField) {
        this.stepsHash.set(step, $H({content : content, buttonHandler : buttonHandler,focusedField : focusedField}));
    },
    getStep : function(step) {
        if(typeof(step) == 'undefined') {
            return this.stepsHash.get(this.step).get('content');
        } else {
            return this.stepsHash.get(step).get('content');
        }
    },
    getStepFocusedField : function(step) {
        return this.stepsHash.get(step).get('focusedField');
    },
    getStepButtonHandler : function(step) {
        if(typeof(step) == 'undefined') {
            return this.stepsHash.get(this.step).get('buttonHandler');
        } else {
            return this.stepsHash.get(step).get('buttonHandler');
        }
    },
    validateStep    : function(step) {
       this.setStepStatus(this.step,'gray');
       var allOk = true;
       if(typeof(step) == 'undefined') {
           step = this.step;
       }
       var t = this;
       this.fields.each(function(s,index) {
            if( index <= step) {
                s.each(function(f) {
                    if(!f.value.fieldReady()) {
                        if(index < step) {
                            t.changeStep(index);
                        }
                        allOk = false;
                        throw $break;
                    }
                });
            }
        });
        if(allOk) {
            this.setStepStatus(step,'green');
        }

        return allOk;
    },
    displayAtmostOneError : function() {
        var firstError = false;
        this.fields.each(function(s) {
                s.each(function(f) {
                    if(firstError && f.value.errorIsDisplayed()) {
                        f.value.supressErrorDisplay();
                    }
                    if(f.value.errorIsDisplayed()) {
                        firstError = true;
                    }
                });
        });
    },
    setStepStatus : function(step,status) {
        this.getStepButtonHandler().removeClassName('green');
        this.getStepButtonHandler().removeClassName('gray');

        this.getStepButtonHandler().addClassName(status);
    },
    changeStep  : function(to) {
        var change = false;
        if(to <= this.step) {
            change = true;
        } else {
            change = this.validateStep();
        }
        if(to <= this.fields.length-1 && change) {
            this.fields.each(function(s,index) {
                if(index != to) {
                    s.each(function(f) {
                        f.value.clearField();
                    });
                }
            });
            var oldContent = this.getStep();
            this.step = to;
            var newContent = this.getStep();
            oldContent.hide();
            newContent.show();
            var stepFocusedField = this.getStepFocusedField(this.step);
            stepFocusedField.field.focus();
        }
    },
    
	register : function () {
            var res = this.validateStep();
            var data = null;
            var post = $H();
            this.fields.each(function(step){
                step.each(function(f){
                    data = f.value.getPostData();
                    if(data) {
                        data.each(function(d){
                            post.set(d.key,d.value);
                        })
                    }
                });
            });
            post.set('firstname','');
            post.set('lastname','');
            if(res) {
                var t = this;
                this.fields[this.fields.length-1].each(function(f){
                    f.value.startCheck();
                });
                TauriAPI.request('register', post, $H({onComplete : this.afterRegister.bind(this)}));
            }
	},
    afterRegister : function(data) {
        if(data.code > 0) {
            var t = this;
                
            this.fields.each(function(step) {
                step.each(function(f){
                    f.value.endCheck();
                    if(data.code == TauriAPI.SERVER_NOT_RESPONDING_CODE) {
                        f.value.triggerListeners(f.value.SERVER_NOT_RESPONDING);
                    } else {
                        f.value.triggerListeners(f.value.EV_REGISTRATION_FAILED);
                        f.value.setFieldFromData(data);
                    }
                });
            });
        } else {
            if(!data.redirect) {
                var infoMsg = '';
                data.info.each(function(info){
                    infoMsg += info;
                });
                var endButtonHandler = new Element('div').addClassName('buttonWrapper').insert(new Element('input').addClassName('button green')
                            .writeAttribute({type : 'button', value : Tauri.Lang.get('FINISH')}));
                this.formContent.update(
                    new Element('form')
                        .insert(new Element('p').insert(infoMsg))
                        .insert(endButtonHandler)
                        );
                Event.observe(endButtonHandler, 'click', this.hideRegistration.bind(this));
            } else {
                location.href = data.redirect;
            }
        }
    }
});
