window.addEvent( 'domready', function () {
    if( document.id( 'login-block-form' )) {
        new NXC.nxcAjaxUser( 'login-block-form' );
    }
	if(document.id( 'top-login-box' )){
		topLoginBox=document.id( 'top-login-box' );
		if(document.id( 'top-login-area' )){
			loginAreaActive=document.id( 'top-login-area' ).hasClass('selected');
			document.id( 'top-login-area' ).dispose();
		}else loginAreaActive=false;
		if( Cookie.read('ezuser_name') ){
			loadLoginArea();
			topLoginBox.setStyle("display","block");
		}else{
			topLoginBoxHTML=topLoginBox.get('html');
			topLoginBox.dispose();
		}
	}
});
var loadLoginArea=function(){
	new Request({	url: siteAccessUri + '/userajax/top_menu_login_area',
								method: "get",
							onSuccess: function(response){
								var tempEl=new Element('div', { 'html': response } );
								var LoginArea=tempEl.getFirst("li");
								if(LoginArea){
									if($defined(loginAreaActive) && loginAreaActive) LoginArea.addClass("selected");
									LoginArea.inject(document.id( 'topmenu' ).getFirst('ul'),"bottom");
									LoginArea.setStyle("display","block");
									addLoginAreaEvents();
								}
							}
						}).send();
}
var addLoginAreaEvents=function(){
	var options = { 'itemCSSPath': 'li.wsub:last-child',
					'initialCSSClass': 'dd-noscript',
					'activeCSSClass': 'active',
					'fadeDuration': 1
	};
	var topMenuLoginArea = new NXC.DDMenu( 'topmenu', options );
	topMenuLoginArea.itemWSubLeave = function( e, item, subMenu ) {
		this.hideSubMenu( subMenu );
		item.removeClass( this.options.activeCSSClass );
	};
	topMenuLoginArea.subLeave = function( e, subMenu ) {
		this.hideSubMenu( subMenu );
	},
	document.getElements('#topmenu li.wsub:last-child a.not-link').each( function( a ){
		a.addEvent( 'click', function( e ) {
			e.stop();
		} );
	} );
}


var NXC = NXC || {};
NXC.nxcAjaxUser = new Class( {

    initialize: function( blockForm ) {
      this.blockForm = document.id( blockForm );
      this.blockWithForm = this.blockForm.getElement('div.attribute-form');
      this.blockResponse = this.blockForm.getElement('div.attribute-response');
      this.blockUserInfo = this.blockForm.getElement('div.attribute-user-info');
      this.blockForgotPassword = this.blockForm.getElement('div.attribute-forgotpassword');
      this.blockForgotPasswordRes = this.blockForm.getElement('div.forgotpassword-response');
      this.inputLogin = this.blockForm.getElement('input[name=Login]');
      this.inputPassword = this.blockForm.getElement('input[name=Password]');
      this.inputUserEmail = this.blockForm.getElement('input[name=UserEmail]');
      this.curUserRes = '';
      thisClassFun = this;
      this.run();
    },

    run: function() {
	  this.setLogoutRedirect();
      this.currentUserByHTML();
      thisClassFun.sendUserLogin();
      thisClassFun.addEventForgotpassword();
      thisClassFun.sendForgotpassword();
    },

	addLoginArea: function(){
		if(document.id( 'topmenu' )){
			loadLoginArea();
		}
	},

	disploseTopLoginBox: function(){
		if(topLoginBox)
		{
			topLoginBox.setStyle("display","none");
			topLoginBoxHTML=topLoginBox.get('html');
			topLoginBox.dispose();
		}
		if(document.id( 'top-login-area' )){
			loginAreaActive=document.id( 'top-login-area' ).hasClass('active');
			document.id( 'top-login-area' ).dispose();
		}
	},

	showTopLoginBox: function(){
		if(topLoginBox)
		{
			topLoginBox.inject(document.id( 'topsearch' ),"after").setStyle("display","block");
			topLoginBox.set('html',topLoginBoxHTML);
		}
	},

	setLogoutRedirect: function(){
		if(this.blockForm.getElement('#LogoutRedirectAjax')){
			this.LogoutRedirect=this.blockForm.getElement('#LogoutRedirectAjax').get("href");
			this.blockForm.getElement('#LogoutRedirectAjax').dispose();
		}
		else this.LogoutRedirect=false;
	},

    currentUserByHTML: function() {
          if( !(Cookie.read('ezuser_name')) ) {
            thisClassFun.blockUserInfo.empty();
            thisClassFun.blockWithForm.show();
            thisClassFun.blockForgotPassword.show();
          } else {
            thisClassFun.blockUserInfo.set('html', ( document.id( 'current-user-info' ).get('html').replace('ezuser_name', Cookie.read('ezuser_name').replace('+',' '))    ));
            thisClassFun.blockWithForm.hide();
            thisClassFun.blockForgotPassword.hide();
            thisClassFun.addLogoutEvent();
          }
    },

    checkEmptyLoginForm: function() {
      if( this.inputLogin.get('value') == '' ) this.inputLogin.addClass('empty');
      else this.inputLogin.removeClass('empty');
      if( this.inputPassword.get('value') == '' ) this.inputPassword.addClass('empty');
      else this.inputPassword.removeClass('empty');
    },

    checkEmptyForPassForm: function() {
      if( this.inputUserEmail.get('value') == '' ) this.inputUserEmail.addClass('empty');
      else this.inputUserEmail.removeClass('empty');
    },

    sendUserLogin: function() {
      thisClassFun = this;
      this.blockForm.getElement( 'form.login' ).addEvent('submit', function(e) {
      	e.stop();
      	thisClassFun.blockResponse.empty().addClass('ajax-loading');
      	this.set('send', {onComplete: function(response) {
      		thisClassFun.blockResponse.removeClass('ajax-loading');
      		thisClassFun.blockResponse.set('html', response);
      		/* hardcoded for motosport */
      		if( siteAccessName == 'ms_en' || siteAccessName == 'ms_de' ) {
      		  thisClassFun.sendCurrentUserWithRedirect();
      		}else{
      			thisClassFun.sendCurrentUser();
			}
      		thisClassFun.checkEmptyLoginForm();
      	}});
      	this.send();
      });
    },

    sendCurrentUser: function() {
    	new Request({ url: siteAccessUri + '/userajax/currentuser',
    		onSuccess: function(response){
          if( response == '' ) {
            thisClassFun.blockUserInfo.empty();
            thisClassFun.blockWithForm.show();
            thisClassFun.blockForgotPassword.show();
          } else {
			thisClassFun.showTopLoginBox();
            thisClassFun.blockUserInfo.set('html', response);
            thisClassFun.blockWithForm.hide();
            thisClassFun.blockForgotPassword.hide();
            thisClassFun.addLogoutEvent();
          }
    		},
    		onFailure: function(){
    			thisClassFun.blockUserInfo.set('text', 'The request failed.');
    		}
    	}).send();
    },

    sendCurrentUserWithRedirect: function() {
    	new Request({ url: '/userajax/currentuser',
    		onSuccess: function(response){
          if( response != '' ) {
            window.location = siteAccessUri + '/userajax/loginredirect';
          }else{
            thisClassFun.blockUserInfo.empty();
            thisClassFun.blockWithForm.show();
            thisClassFun.blockForgotPassword.show();
          }
    		}
    	}).send();
    },

    addLogoutEvent: function() {
      logoutLink =  this.blockForm.getElement('a.logout');
      if( logoutLink ){
        logoutLink.addEvent('click', function(e){
          e.stop();
        	new Request({ url: '/userajax/logout',
        		onSuccess: function(response){
					if(thisClassFun.LogoutRedirect) window.location=thisClassFun.LogoutRedirect;
					else thisClassFun.sendCurrentUser();
					thisClassFun.disploseTopLoginBox();
        		},
        		onFailure: function(){
        			thisClassFun.blockUserInfo.set('text', 'The request failed.');
        		}
        	}).send();
        });
      }
    },

    addEventForgotpassword: function() {
      forgotpasswordLink =  this.blockForm.getElement('a.forgotpassword');
      if( forgotpasswordLink ){
      VerticalSlide = new Fx.Slide( this.blockForgotPassword );
      VerticalSlide.hide();
        forgotpasswordLink.addEvent('click', function(e){
          e.stop();
          VerticalSlide.toggle();
        });
      }
    },

    sendForgotpassword: function() {
      this.blockForm.getElement( 'form.forgotpassword' ).addEvent('submit', function(e) {
      	e.stop();
      	thisClassFun.blockForgotPasswordRes.empty().addClass('ajax-loading');
      	this.set('send', {onComplete: function(response) {
      		thisClassFun.blockForgotPasswordRes.removeClass('ajax-loading');
      		thisClassFun.blockForgotPasswordRes.set('html', response);
      		thisClassFun.checkEmptyForPassForm();
      	}});
      	this.send();
    });
    }

} );
