var loginWidget = function (options) {
    this.logged = options.logged || false;
    this.registerMode = options.registerMode || false;
    this.timeOutLocked = options.timeOutLocked || 15000;
    var that = this;
    var idWidget = options.idLoginWidget || '#login-widget';
    this.el = $(idWidget);
    this.token = '';
	
    this.field = {};
    this.field.email = $(idWidget + ' #email');
    this.field.email_fb = $(idWidget + ' #fb-email');
    this.field.password = $(idWidget + ' #password');
    this.field.nickname = $(idWidget + ' #nickname');
    this.field.nickname_fb = $(idWidget + ' #fb-nickname');
    this.field.privacy = $(idWidget + ' #privacy');
    this.field.newsletter = $(idWidget + ' #input-newsletter');
    this.field.mail_forgot_pass = $(idWidget + ' #mail-forgot-password');
    this.elLogin = $(idWidget + ' #login');
    this.elRegister = $(idWidget + ' #register');
    this.elError = $(idWidget + ' .error');
    this.elMsgLogin = $(idWidget + ' #message-login');
    this.elMsgRegister = $(idWidget + ' #message-register');
    this.elSpanNickname = $(idWidget + ' span.nickname');
    this.elNewUser = $(idWidget + ' #new-user');
    this.elNewUserFb = $(idWidget + ' #new-user-fb');
    this.elFBPanel = $(idWidget + ' #fb-panel');
    this.elLoginPanel = $(idWidget + ' #login-panel');
    this.elPrivacyPanel = $(idWidget + ' #privacy-panel');
    this.elNewsletterPanel = $(idWidget + ' #newsletter-panel');
    this.elFbPic = $(idWidget + ' #fb-pic');
    this.elFbLogin = $(idWidget + ' #fb-login');
    this.elUPLogout = $('#up-logout');
    this.elTitle = $(idWidget + ' .title');
    this.elBackLogin = $(idWidget + ' .back-login');
    this.elDX2 = $(idWidget + ' .dx2');
    this.elDX = $(idWidget + ' .dx');
    this.elPrivacyTextArea = $(idWidget + ' #privacy-panel textarea');
    this.elPrivacyShowContent = $(idWidget + ' a#show-privacy-content');
    this.elFbWelcome = $(idWidget + ' .fb-welcome');
    this.elFbWelcomeNome = $(idWidget + ' .fb-welcome b.nome');
    this.elLoader = $(idWidget + ' #loader');
    this.elFbLogout = $(idWidget + ' #fb-logout');
    this.elForgotPasswordPanel = $(idWidget + ' #forgot-panel');
    this.elToggleForgotPassword = $(idWidget + ' #forgot-panel .toggle');
    this.elWidgetForgotPassword = $(idWidget + ' #forgot-panel .widget');
    this.elSendForgotPassword = $(idWidget + ' #forgot-panel .send');
    this.elLoaderForgotPassword = $(idWidget + ' #forgot-panel .loader');
    this.elSuccessForgotPassword = $(idWidget + ' #forgot-panel .success');
    this.elFailureForgotPassword = $(idWidget + ' #forgot-panel .failure');
    this.elCloseWidget = $(idWidget + ' #close-login-widget');
	this.elAssociateFB = $(idWidget + ' .associate-fb');
	this.elWrapperFbNickname = $(idWidget +  ' #fb-panel .wrapper-nickname');
	this.elAssociateActionsPanel = $(idWidget +  ' .actions-fb-associate');
	this.elAssociateAction = $(idWidget +  ' .actions-fb-associate .action');
	this.elAssociateOutput = $(idWidget +  ' .actions-fb-associate .output');
	this.elAssociateCancel = $(idWidget +  ' .actions-fb-associate .cancel');
	
	
    
	
	
	this.elCloseWidget.click(function(){
		that.hide();
	})
	
    this.elLoader.css('opacity', 0.25)
    this.elPrivacyTextArea.css('opacity', 0)
    this.elPrivacyTextAreaOpen = false;
    this.elPrivacyShowContent.click(function () {
        if (that.elPrivacyTextAreaOpen) {
            that.elPrivacyTextArea.animate({
                height: 0,
                opacity: 0,
                padding: 0
            }, 200);
            that.elPrivacyTextAreaOpen = false;
        } else {
            that.elPrivacyTextArea.animate({
                height: 100,
                opacity: 1,
                padding: 4
            }, 200);
            that.elPrivacyTextAreaOpen = true;
        }
    })
    //token			
    $.get("service/token.php", function (txt) {
        that.token = txt;
    });
    var h3Login = 'Stai effettuando il log-in a ultimoprezzo.com';
    var h3Register = 'Ti stai registrando gratis a ultimoprezzo.com';
    var user = {};
    this.facebookMode = false;
    this.fbData = null;
    that.elTitle.html(h3Login)
    this.elFbLogout.click(function () {
        that.lock()
                
        FB.logout(function(){
            that.fbLogout();
        })
    })
    this.fbLogout = function () {
        that.hideFBPanel();
        that.showLoginPanel();
        if (!that.registerMode) {
            that.hidePrivacyPanel();
            that.elDX2.addClass('hide');
            that.elDX.removeClass('hide');
           // that.elBackLogin.removeClass('hide');
            that.hideNewsletterPanel()
        } else {
            that.elDX.addClass('hide');
            that.elDX2.removeClass('hide');
            ///that.showRegPanel();
        }
        that.setFacebookMode(false);
        that.unlock()
        
    }
    this.elFbLogin.click(function () {
        //that.lock();
    })
    this.checkLocked = function () {
        if (this.isLocked()) this.unlock();
    }.setScope(that)
    this.lock = function () {
        if (this.isLocked()) return false;
        this.elLoader.fadeIn()
        this.locked = true;
        setTimeout(this.checkLocked, this.timeOutLocked)
    }
    this.unlock = function () {
        this.elLoader.css('display', 'none')
        this.locked = false;
    }
    this.isLocked = function () {
        return this.locked;
    }
    this.setFacebookMode = function (bool) {
        this.facebookMode = bool;
        if (bool) {
            this.showFBPanel();
            this.hideLoginPanel();
            this.field.nickname_fb.focus();
           // this.elBackLogin.addClass('hide');
            this.showNewsletterPanel();
        }
    }
	this.elAssociateFB.click(function(){
		that.hideNewsletterPanel();
		that.hidePrivacyPanel();
		that.elWrapperFbNickname.addClass('hide');
		that.elDX2.addClass('hide');
		that.elAssociateActionsPanel.removeClass('hide');
	})
	
	this.elAssociateCancel.click(function(){
		that.showNewsletterPanel();
		that.showPrivacyPanel();
		that.elWrapperFbNickname.fadeIn();
		that.elDX2.removeClass('hide');
		that.elAssociateActionsPanel.addClass('hide');

	})
	
	this.elAssociateAction.click(function(){		
		that.elAssociateOutput.css('display','none');
		that.elAssociateOutput.removeClass('failure');
		var $fbEmail = that.field.email_fb.attr('value')
		
		if(!axura.uility.isValidMail($fbEmail) || $fbEmail ==''){
			that.elAssociateOutput.html('Inerire una mail valida.')
			that.elAssociateOutput.addClass('failure');
			that.elAssociateOutput.fadeIn();
			return false;
		}
		that.elLoader.fadeIn();
		var data = {};
        data.fn = 'requestAssociationFB';
		data.uid = that.fbData.uid;
		data._m = $fbEmail;			
        $.ajax({
            type: 'POST',
            url: 'service/access.php?r=' + new Date().getTime(),
            data: data,
            dataType: 'json',
            success: function (json) {
				that.elLoader.fadeOut()
				that.elAssociateOutput.html(json.data)
				if (json.succes) {
                  	that.hideDelay(5000);
                } else {
                   that.elAssociateOutput.addClass('failure');
                }
				that.elAssociateOutput.fadeIn();
            }
        });
						
	})
	
	this.hide = function(){
		that.el.fadeOut(function(){
      	  if (typeof options.onHide != 'undefined') {
                    options.onHide();
          }
          
         that.fireEvent('close');
		});
		try{
			axura.UI.unblock();		
        }catch(e){}
		 $(window).unbind('resize', this.centerWidget);
	}
	
    this.hideDelay = function () {
		var delay  = (typeof arguments[0]=='number') ? arguments[0] : 2000 
		setTimeout(this.hide, delay);
    }
    this.show = function (position,force) {       
		if(this.isLogged() && !force) return false;
	 	this.elMsgLogin.css('display','none')
	 	this.elMsgRegister.css('display','none')
		if(position === 'center'){
			$(window).bind('resize', this.centerWidget);
			$(document).bind('keydown', function(e){
				if(e.keyCode == 27){
					that.hide();
				}
			});
			this.centerWidget()
		}
		try{
			axura.UI.block();		
        }catch(e){}
        this.el.fadeIn();
		
    }
    
    this.elBackLogin.click(function () {
		that.setRegisterMode(false);
    })
    this.elLogin.click(function () {
        that.hideError();
        if (that.field.email.attr('value') == '') {
            that.field.email.addClass('error');
            that.field.email.focus()
            that.showError('Inserire l\'indirizzo e-mail');
            return false;
        } else if (!axura.uility.isValidMail(that.field.email.attr('value'))) {
            that.field.email.addClass('error');
            that.field.email.focus()
            that.showError('Inserire un indirizzo e-mail valido');
            return false;
        } else if (that.field.password.attr('value') == '') {
            that.showError('Inserire la password');
            that.field.password.toggleClass('error');
            that.field.password.focus()
            return false;
        }
        that.login();
    })
    this.elRegister.click(function () {
		that.setRegisterMode(true);
    })
	
	this.setRegisterMode = function(bool){
    	if(that.facebookMode) bool = true;
    	if(bool){
            that.registerMode = true;
            that.elSpanNickname.removeClass('hide');
            that.elTitle.html(h3Register);
            that.elDX2.removeClass('hide')
            that.elDX.addClass('hide')
            that.showPrivacyPanel();
            that.showNewsletterPanel();
            
		}else if(!that.facebookMode){
            that.elSpanNickname.addClass('hide');
            that.registerMode = false;
            that.elTitle.html(h3Login)
            that.elDX.removeClass('hide')
            that.elDX2.addClass('hide')
            that.hidePrivacyPanel();
            that.hideNewsletterPanel();
		}	
		that.elAssociateActionsPanel.addClass('hide');
	}
    this.elNewUser.click(function () {
        that.hideError();
        if (that.facebookMode) {
            if (that.field.nickname_fb.attr('value') == '') {
                that.field.nickname_fb.addClass('error');
                that.showError('Inserire un nickname');
                return false;
            } else if (that.field.email_fb.attr('value') == '') {
                that.field.email_fb.addClass('error');
                that.showError('Inserire l\'indirizzo e-mail');
                return false;
            } else if (!axura.uility.isValidMail(that.field.email_fb.attr('value'))) {
                that.field.email_fb.addClass('error');
                that.showError('Inserire un indirizzo e-mail valido');
                return false;
            } else if (!that.field.privacy.attr('checked')) {
                that.showError('Per usufrire del servizio devi indicare di aver visto e accettato le norme sulla privacy e le condizioni di servizio.');
                return false;
            }
        } else {
            if (that.field.nickname.attr('value') == '') {
                that.field.nickname.addClass('error');
                that.showError('Inserire un nickname');
                return false;
            } else if (that.field.email.attr('value') == '') {
                that.field.email.addClass('error');
                that.showError('Inserire l\'indirizzo e-mail');
                return false;
            } else if (!axura.uility.isValidMail(that.field.email.attr('value'))) {
                that.field.email.addClass('error');
                that.showError('Inserire un indirizzo e-mail valido');
                return false;
            } else if (that.field.password.attr('value') == '') {
                that.showError('Inserire la password');
                that.field.password.toggleClass('error');
                return false;
            } else if (!that.field.privacy.attr('checked')) {
                that.showError('Per usufrire del servizio devi indicare di aver visto e accettato le norme sulla privacy e le condizioni di servizio.');
                return false;
            }
        }
        that.register();
    })
    this.elUPLogout.click(function () {
       that.logout();
    })
	
	this.logout = function(){
 		that.lock();
       
        var data = {};
        data.fn = 'logout'
        $.ajax({
            type: 'POST',
            url: 'service/access.php?r=' + new Date().getTime(),
            data: data,
            dataType: 'json',
            success: function (json) {
                that.unlock();
                that.setLogged(false);
                that.hidePrivacyPanel();
                that.hideFBPanel();
                that.showLoginPanel();
                that.elMsgLogin.fadeOut();
                that.elMsgRegister.fadeOut();
                that.setFacebookMode(false);
                that.elTitle.removeClass('hide');
                that.elTitle.html(h3Login)
                that.elSpanNickname.addClass('hide');
                that.hideNewsletterPanel();
                that.showForgotPasswordPanel();
                if (typeof options.onLoggedOut != 'undefined') {
                    options.onLoggedOut();
                }                
//                $.cookie('not_autologin_facebook','1',{ path: '/', expires: 10 })
            }
        });
         if(FB){
                
            FB.logout(function(){
                that.fbLogout();
            })            
        }
	}
		
    this.login = function () {
        that.lock();
        var data = {};
        data._m = that.field.email.attr('value');
        data._p = that.field.password.attr('value');
        data.fn = 'login'
        $.ajax({
            type: 'POST',
            url: 'service/access.php?r=' + new Date().getTime(),
            data: data,
            dataType: 'json',
            success: function (json) {
                that.unlock();
                if (json.succes) {
                    that.user = json.data;
                    that.setLogged(true);
                    that.loginSuccess();
                    if (typeof options.onLoggedIn != 'undefined') {
                        options.onLoggedIn();
                    }
//                     $.cookie('not_autologin_facebook',null)
                    
                } else {
                    that.showError('Mail o password non valide');
                }
            }
        });
    }
    this.getUserData = function () {
        return this.user;
    }
    this.register = function () {
        var data = {};
        data._n = that.field.nickname.attr('value');
        data._m = that.field.email.attr('value');
        data._p = that.field.password.attr('value');
        data._nwl = (that.field.newsletter.attr('checked')) ? '1' : '';
        data.fn = 'register'
        if (this.facebookMode) data._fb = true;
        if (this.facebookMode) data._m = that.field.email_fb.attr('value');
        if (this.facebookMode) data._n = that.field.nickname_fb.attr('value');
        if (this.facebookMode && typeof this.fbData === 'object') {
            $.extend(data, this.fbData);
        }
        that.lock();
        data.token = that.token
        $.ajax({
            type: 'POST',
            url: 'service/access.php?r=' + new Date().getTime(),
            data: data,
            dataType: 'json',
            success: function (json) {
                that.unlock();
                if (json.succes) {
                    that.user = json.data;
                    that.setLogged(true);
                    that.registerSuccess();
                    if (typeof options.onLoggedIn != 'undefined') {
                        options.onLoggedIn();
                    }
                    that.fireEvent('login');
                } else {
                    that.showError(json.error);
                }
            }
        });
    }
    this.setLogged = function (logged) {
        if(logged){
            that.fireEvent('login');
        }else{
            that.fireEvent('logout');
        }
        this.logged = logged;
    }
    this.isLogged = function () {
        return this.logged;
    }
    this.showError = function (errors) {
        this.elError.html(errors)
        //this.elError.removeClass('hide');
        this.elError.fadeIn()
    }
    this.hideError = function (xt) {
        this.elError.html('')
        this.elError.css('display', 'none');
        this.field.email.removeClass('error');
        this.field.password.removeClass('error');
        this.field.nickname.removeClass('error');
    }
    this.loginSuccess = function () {
        that.elMsgLogin.fadeIn('hide');
        that.success();
    }
    this.registerSuccess = function () {
        that.elMsgRegister.fadeIn('hide');
        this.elDX2.addClass('hide');
        that.success();
    }
    this.success = function () {
        that.hideLoginPanel();
        that.hideFBPanel();
        that.elTitle.addClass('hide');
        that.hidePrivacyPanel();
        that.hideNewsletterPanel()
        that.closeWidgetPassword();
        that.hideForgotPasswordPanel();
        that.closeElFailureForgotPassword();
		that.hideDelay();
		
		//todo gestire eventi multipli

		

		
    }
    this.showPrivacyPanel = function () {
        that.elPrivacyPanel.removeClass('hide');
	    //   that.elPrivacyPanel.fadeIn();
    }
    this.hidePrivacyPanel = function () {
        that.elPrivacyPanel.addClass('hide');
        //that.elPrivacyPanel.fadeOut();
    }
    this.setFbData = function (data) {
        this.fbData = data;
    }
    this.showFBPanel = function () {
        this.elFBPanel.removeClass('hide');
    }
    this.hideFBPanel = function () {
        this.elFBPanel.addClass('hide');
    }
    this.hideLoginPanel = function () {
        this.elLoginPanel.addClass('hide');
        this.elDX.addClass('hide');
    }
    this.showLoginPanel = function () {
        this.elLoginPanel.removeClass('hide');
        this.elDX.removeClass('hide');
    }
    this.showNewsletterPanel = function () {
        this.elNewsletterPanel.removeClass('hide');
		//this.elNewsletterPanel.fadeIn();
    }
    this.hideNewsletterPanel = function () {
        this.elNewsletterPanel.addClass('hide');
		//this.elNewsletterPanel.fadeOut();
    }
    this.showForgotPasswordPanel = function () {
        this.elForgotPasswordPanel.removeClass('hide');
    }
    this.hideForgotPasswordPanel = function () {
        this.elForgotPasswordPanel.addClass('hide');
    }
    this.setFbPic = function (urlImg) {
        if (urlImg !== null) {
            this.elFbPic.attr('src', decodeURIComponent(urlImg));
        }
        this.elFbPic.removeClass('hide')
    }
    this.getUserFromUidFb = function (uidFb, avatar, nome,email) {
        
        var data = {};
        data._uid = uidFb;
        data._avatar = encodeURIComponent(avatar);
	
        data.fb_name = nome;
        
        data.fn = 'getUserFromFb';
        $.ajax({
            type: 'POST',
            url: 'service/access.php?r=' + new Date().getTime(),
            data: data,
            dataType: 'json',
            success: function (json) {
                if (json.succes) {
                    that.user = json.data;
                    that.setLogged(true);
                    that.loginSuccess();
                    if (typeof options.onLoggedIn != 'undefined') {
                        options.onLoggedIn();
                    }
                    
                } else {
                    that.showPrivacyPanel();
                    that.elFbWelcome.effect("pulsate", {}, 300);
                    that.elFbWelcomeNome.html(nome);
                    that.elDX2.removeClass('hide');
                    that.field.email_fb.val(email)

                    //that.elFbWelcome.animate({backgroundColor: '#DCE4E9'}, 3000);
                }
            }
        });
    }
    this.widgetForgotPasswordOpen = false;
    this.elToggleForgotPassword.click(function () {
        if (that.widgetForgotPasswordOpen) {
            that.closeWidgetPassword();
        } else {
            that.openWidgetPassword();
            that.closeElSuccessForgotPassword();
            that.closeElFailureForgotPassword();
        }
    })
    this.closeWidgetPassword = function () {
        this.widgetForgotPasswordOpen = false;
        this.elWidgetForgotPassword.animate({
            height: 0
        }, 500);
    }
    this.openWidgetPassword = function () {
        this.widgetForgotPasswordOpen = true;
        this.elWidgetForgotPassword.animate({
            height: 92
        }, 500);
    }
    this.closeElSuccessForgotPassword = function () {
        this.elSuccessForgotPassword.animate({
            height: 0
        }, 300);
    }
    this.openElSuccessForgotPassword = function () {
        this.elSuccessForgotPassword.animate({
            height: 15
        }, 1000);
    }
    this.closeElFailureForgotPassword = function () {
        this.elFailureForgotPassword.animate({
            height: 0
        }, 300);
    }
    this.openElFailureForgotPassword = function (text) {
		 this.elFailureForgotPassword.html(text)
        this.elFailureForgotPassword.animate({
            height: 15
        }, 300);
    }
    this.elSendForgotPassword.click(function () {
		that.elFailureForgotPassword.css('height', 0)
        var _m = $.trim(that.field.mail_forgot_pass.attr('value'));
        if (_m == '' || !axura.uility.isValidMail(_m)) {
            that.field.mail_forgot_pass.focus();
            that.field.mail_forgot_pass.addClass('error');
			if (_m == '' ){
				that.openElFailureForgotPassword('Inserire un indirizzo e-mail');
			}else if(!axura.uility.isValidMail(_m)){
				that.openElFailureForgotPassword('Indirizzo e-mail non valido');
			}
            return false;
        }
        var data = {};
        data._m = $.trim(that.field.mail_forgot_pass.attr('value'));
        data.fn = 'forgotPassword';
        that.elLoaderForgotPassword.fadeIn();
        $.ajax({
            type: 'GET',
            url: 'service/access.php?r=' + new Date().getTime(),
            data: data,
            dataType: 'json',
            success: function (json) {
                that.elLoaderForgotPassword.fadeOut();
                if (json.succes) {
                    that.closeWidgetPassword()
                    that.openElSuccessForgotPassword();
                } else {
                    that.openElFailureForgotPassword('Indirizzo e-mail non valido');
                }
            }
        });
    })
	
	this.bind = function(event,cb){
		if(typeof cb === 'function'){
			options[event] = cb;	
		}
	}
	this.fbOnLogin = function(){
	   that.lock();
       try{               
    	   var user_id = FB.getSession().uid; 
    	   var query = FB.Data.query('SELECT uid,email,first_name,last_name,sex,birthday_date, pic_square from user where uid={0}',user_id);
             query.wait(function(results) {           
                that.fireEvent('facebook_results',results);
                that.unlock()     
                results = results[0]
                that.hideError();
                var avatar = null;
                if (results.pic_square != null) {
				results.pic_square = encodeURIComponent(results.pic_square);
				
                    avatar = results.pic_square.replace(/&amp;/g, "&");
                }
                that.getUserFromUidFb(results.uid, avatar, results.first_name + ' ' + results.last_name,results.email);
                that.setFacebookMode(true);
                that.setFbData(results);
                that.setFbPic(avatar);
             });
        }
        catch(e){
            if(console) console.log(e)            
        }
        finally
        {
          that.unlock();
        }
	}
	this.getDimension = function(){
		return {
			h:this.el.height(),
			w:this.el.width()
		};
	}
	this.centerWidget = function(){
		that.el.css('position','fixed');
		that.el.css('z-index','9999');
		var coo = that.getDimension();
		that.el.css('top',($(window).height()-coo.h)/2);
		that.el.css('left',($(window).width()-coo.w)/2);       		
	}	
	
	var events = {};	
	this.addEventListener=function(nameEvent,fn){
        if(!events[nameEvent]){
            events[nameEvent] = [];
        }
	    events[nameEvent].push(fn); 
	    return that;
	}
	
	this.fireEvent = function(nameEvent,cb_data){
        if(events[nameEvent]){
           for(i=0;i<events[nameEvent].length;i++){
              events[nameEvent][i](that,cb_data)
           }
         }	
	}
	

	
}




