var FacebookConnector = new Class({

    Implements: [Options],

    options: {
    },

    initialize: function(options) {
        this.setOptions(options);

        this.STATUS_WARNING = 1;
    },

    init: function(options) {

        if(options.identity) {
            this.identity = options.identity;
        }

        if(options.permissions) {
            this.permissions = options.permissions;
        }

        if(options.loginRedirectUrl) {
            this.loginRedirectUrl = options.loginRedirectUrl;
        }

        if(!this.isAuthenticated()) {
            FB.getLoginStatus(function(response) {
                if (response.authResponse) {
                    // could be used to automatically log in user
                    //alert("Facebook Session Connect");
                }
            });
        }

        if(undefined == this.subscribed || this.subscribed == false) {
            FB.Event.subscribe('auth.login', this.onFacebookLogin.bind(this));
            FB.Event.subscribe('auth.logout', this.onFacebookLogout.bind(this));
            this.subscribed = true;
        }
    },

    facebookLogin: function(callback) {
        var options = {};
        if(this.permissions) {
            options.perms = this.permissions;
        }
        //options.enable_profile_selector = 1;

        if(callback) {} else {callback = function(){alert('No callback defined')};};

        FB.login(callback.bind(this), options);
    },

    /**
     * Fires when the user logged into facebook while a session cookie already existed
     */
    onFacebookLogin: function(response) {
        if (!response) {
            Roar.alert('Connect to Facebook', 'Connection to your facebook account cancelled');
            return;
        }
        //alert('onFacebookLogin');
        //this.authenticate();
    },

    onFacebookLogout: function(response) {
        // user logged out, put local cleanup code here
    },

    /**
     * Display modal signup
     */
    signup: function() {
        if(this.isAuthenticated()){
//            if(console) console.log('Signup canceled, user already sign in');
            return false;
        }
        SqueezeBox.open('/register?format=html',{size: {x: 628, y: 410}, onClose: function(){this.onClose()}.bind(this)});

        return true;
    },

    /**
     * Display modal login
     */
    login: function(email) {
        //if(this.isAuthenticated()) return;

        if(undefined !== email) {
            url = '/login/html?email=' + email;
        } else {
            url = '/login/html';
        }

        //alert($('THISSUCKSTOTALLY').get('type'));

        //$('featured').get('id');

        if(FB.getAuthResponse()) {
            this.authenticate();
        } else {
            this.showLoginWindow();
        }
    },

    showLoginWindow: function() {
        SqueezeBox.open(url,{size: {x: 628, y: 290}, onClose: function(){this.onClose()}.bind(this)});
    },

    close: function() {
        SqueezeBox.close();
    },

    onClose: function() {
       //$('featured').setStyle('visibility', 'visible');
    },

    /**
     * Logout
     */
    logout: function() {
        FB.logout();
    },

    isAuthenticated: function() {
        if(this.identity.uid) {
            return true;
        };

        return false;
    },

    onWindowReady: function() {
        try{
            this.options.element.focus();
        } catch(err) {

        }
    },

    initSignup: function(options) {
        this.setOptions(options);
        this.options.element = $('SignupEmail');
        this.options.validationCallback = this.onSignUpValidationSuccess.bind(this);
        this.options.element.addEvent('keyup', function() {this.validateEmail();}.bind(this));
        this.options.element.addEvent('blur', function() {this.validateEmail();}.bind(this));
        this.options.element.addEvent('change', function() {this.validateEmail();}.bind(this));

        // prevent email validation form from submitting by using return
        $('SignupFormFull').addEvent('submit', function() {
            return false;
        });

        $('SignupForm').addEvent('submit', function() {
            this.validateEmail();
            return false;
        }.bind(this));

        $('SignupFormContinueLink').removeEvents();
        $('SignupFormContinueLink').addEvent('click', this.skipFacebookLogin.bind(this));
        $('SignupFacebookLoginButton').removeEvents();
        $('SignupFacebookLoginButton').addEvent('click', function() {this.facebookLogin(this.onSignUpFacebookLoginSuccess.bind(this))}.bind(this));
        this.signupFormValidator = new Form.Validator($('SignupFormFull'), {onFormValidate: this.onSignupFormValidate.bind(this), evaluateFieldsOnChange: false, evaluateFieldsOnBlur: false});

        this.disableSignupEmail();
        this.onSignUpValidationSuccess();
    },

    onSignUpValidationSuccess: function(response)
    {
        if(response && response.status) {
            var status = response.status;

            if(status.code == 0) {
                if(undefined != FB.getAuthResponse()) {
                    this.setModalWindowStatus(status.fbmessage, this.STATUS_WARNING);
                } else {
                    this.setModalWindowStatus(status.message, this.STATUS_WARNING);
                }
                $('VerificationImage').set('src', '/themes/highschoolseniorphotographers.com/images/signup-cross.jpg');
                this.disableSignupForm();
            } else {
               if(undefined != FB.getAuthResponse()) {
                    this.setModalWindowStatus(status.fbmessage);
                } else {
                    this.setModalWindowStatus(status.message);
                }
                $('VerificationImage').set('src', '/themes/highschoolseniorphotographers.com/images/signup-check.jpg');
                this.enableSignupForm();
            }
        } else {
            this.disableSignupForm();

            $('VerificationImage').set('src', '/images/spacer.gif');
            
            if(FB.getAuthResponse()) {
                this.setModalWindowStatus('please enter your email address!');
                this.enableSignupEmail();
            } else if(0 == $('SignupEmailOverlay').get('opacity')) {
                this.setModalWindowStatus('Enter Your E-mail Address to get started!');
            }
        }

//        switch(response) {
//            case 0:
//                this.setModalWindowStatus('Please enter a valid email address', this.STATUS_WARNING);
//                $('VerificationImage').set('src', '/themes/highschoolseniorphotographers.com/images/signup-cross.jpg');
//                //$('VerificationImage').set('src', 'images/spacer.gif');
//                if(undefined != FB.getAuthResponse()) {
//                    this.setModalWindowStatus('please enter a valid email address!', this.STATUS_WARNING);
//                }
//                this.disableSignupForm();
//            break;
//
//            case 1:
//                this.setModalWindowStatus('This E-mail Address is good to go ');
//                $('VerificationImage').set('src', '/themes/highschoolseniorphotographers.com/images/signup-check.jpg');
//                if(undefined != FB.getAuthResponse()) {
//                    this.setModalWindowStatus('please complete the short form below!');
//                }
//                this.enableSignupForm();
//            break;
//
//            case -1:
//                this.setModalWindowStatus('This E-mail Address seems to be already in use, please click <a onclick="FBConnect.login(\'' + this.options.element.value + '\')">here</a> to login!', this.STATUS_WARNING);
//                if(undefined != FB.getAuthResponse()) {
//                    this.setModalWindowStatus('if you already have an account please click <a onclick="FBConnect.login(\'' + this.options.element.value + '\')">here</a> to login!', this.STATUS_WARNING);
//                }
//                $('VerificationImage').set('src', '/themes/highschoolseniorphotographers.com/images/signup-cross.jpg');
//                this.disableSignupForm();
//            break;
//        }
    },

    enableSignupForm: function() {
        if($('SignupFormFull').get('opacity') == '1') return;
        $('SignupFormFull').set('opacity', '1');
        $('SignupFormFull').getElements('input').set('disabled', false);
        $('SignupFormFull').getElements('select').set('disabled', false);

        if(this.facebookuser) {
            if($('firstname')) {
                $('firstname').value = this.facebookuser.first_name;
                $('lastname').value = this.facebookuser.last_name;
                if(this.facebookuser.sex == 'male') {
                  $('sex-Male').checked = true;
                  $('sex-Female').checked = false;
                } else if(this.facebookuser.sex == 'female') {
                  $('sex-Male').checked = false;
                  $('sex-Female').checked = true;
                }
            }
        }
    
        this.enableSignupActionButton();
    },

    disableSignupForm: function() {
        if($('SignupFormFull').get('opacity') == '0.25') return;
        $('SignupFormFull').set('opacity', '0.25');
        $('SignupFormFull').getElements('input').set('disabled', true);
        $('SignupFormFull').getElements('select').set('disabled', true);
        this.disableSignupActionButton();
    },

    enableSignupEmail: function() {
        $('SignupEmailOverlay').set('opacity', '0');
        this.options.element.set('disabled', false);
        try{
            this.options.element.focus();
        } catch(err) {}

    },

    disableSignupEmail: function() {
        $('SignupEmailOverlay').set('opacity', '0.72');
        this.options.element.set('disabled', true);
    },

    skipFacebookLogin: function() {
        this.setModalWindowStatus('Enter Your E-mail Address to get started!');
        this.enableSignupEmail();
    },

    enableSignupActionButton: function() {
        $('ModalWindowActionButton').removeEvents();
        $('ModalWindowActionButton').addEvent('click', function() {$('email').set('value', this.options.element.value); this.signupFormValidator.validate()}.bind(this));//$('SignupFormFull').submit()
        $('ModalWindowActionButton').set('opacity', '1.00');
        $('ModalWindowActionButton').setStyle('cursor', 'pointer');
    },

    disableSignupActionButton: function() {
        $('ModalWindowActionButton').removeEvents();
        $('ModalWindowActionButton').set('opacity', '0.25');
        $('ModalWindowActionButton').setStyle('cursor', 'default');
    },

    onSignupFormValidate: function(passed, form, event) {
         if (passed) {
           var request = new Request.JSON({
                url: '/register?format=json',
                ajax: 1,
                onSuccess: function(response) {
                    if(response.status) {
                        if(response.status.code == 1) {
                            if(response.status.redirect) {
                                this.redirect(response.status.redirect);
                            }
                        } else {
                            Roar.alert('Registration Error', response.status.message);
                        }
                    }
//                    Roar.alert('Registration Successful', 'Please check your email inbox for an email with a link to validate your account!');
                }.bind(this)
            }).post(form);
            this.close();
            Roar.alert('Registration', 'Please wait while your registration is processed!');
         } else {
            this.setModalWindowStatus('Please check the form for input errors!', this.STATUS_WARNING);
         }
      },

    setModalWindowStatus: function(message, type) {
        
        switch(type) {
            case this.STATUS_WARNING:
                backgroundcolor = '#7B1613';
                color = 'white';
            break;
            default:
                backgroundcolor = '#3B5998';
                color = 'white';
        }
        if(undefined == backgroundcolor) backgroundcolor = '#3B5998';
        if(undefined !== FB.getAuthResponse() && null !== FB.getAuthResponse()) {
            if(undefined == this.facebookuser || null == this.facebookuser) {
                //if(console) console.log('requestion facebook identity');
                FB.api(
                {
                    method: 'fql.query',
                    query: 'SELECT name, pic_square, first_name, last_name, sex FROM user WHERE uid=' + FB.getAuthResponse().uid
                },
                function(response) {
                    if(null != response) {
                        if(response.error_code) {
//                            if(console) console.log(response.error_msg);
                        }

                        var user = response[0];
                        if(undefined != user) {
                            this.facebookuser = user;
                            this.setModalWindowStatus(message, type);
                        }
                    } else {
//                        if(console) console.log('No valid facebook response');
                    }
                }.bind(this));
            } else {
                $('ModalWindowStatus').setStyle('color', color);
                $('ModalWindowStatus').setStyle('background-color', backgroundcolor);
                //$('ModalWindowTitleCaption').set('html', '<img id="FacebookImage" src="' + this.facebookuser.pic + '">Welcome ' + this.facebookuser.name);
                //$('ModalWindowStatus').set('html', '<div style="padding-top: 4px; font-size: 12px; font-weight: bold;"><span id="UserInfoMessage">, ' + message + '</span></div>');
                $('ModalWindowStatus').set('html', '<div style="padding-top: 4px; font-size: 12px; font-weight: bold;"><img style="width: 25px; height: 25px; margin-right: 8px; padding: 2px; border: 1px solid #333; background-color: white; vertical-align: middle;" src="' + this.facebookuser.pic_square + '">' + this.facebookuser.name + '<span id="UserInfoMessage">, ' + message + '</span></div>');
            }
        } else {
            $('ModalWindowStatus').setStyle('background-color', backgroundcolor);
            $('ModalWindowStatus').set('html', '<div style="padding-top: 10px; font-size: 12px; font-weight: bold; color: ' + color + '">' + message + '</div>');
        }
    },

    /**
     *  Login Form Code
     */

    initLogin: function(options) {
        this.setOptions(options);
        this.options.element = $('email');
        this.options.validationCallback = this.onLoginValidationSuccess.bind(this);

        $('ModalWindowTitle').innerHTML = ('Login');

        $('SignupFacebookLoginButton').addEvent('click', function() {this.facebookLogin(this.onLoginFacebookLoginSuccess.bind(this))}.bind(this));
        if(undefined==FB.getAuthResponse() && this.options.element.value == '') {

            //$('SignupFacebookLoginButton').addEvent('click', function() {this.facebookLogin(this.onLoginFacebookLoginSuccess.bind(this))}.bind(this));
        } else {
//            this.setModalWindowStatus('please wait, checking your account status!');
//            this.authenticate();
        };

//        if(FB.getAuthResponse()) {
//            alert("!");
//            this.setModalWindowStatus('please log into your existing account!');
//        };

        // add events to validate login input
        this.options.element.addEvent('keyup', this.validateLoginForm.bind(this));
        this.options.element.addEvent('blur', this.validateLoginForm.bind(this));
        $('password').addEvent('keyup', this.validateLoginForm.bind(this));
        $('password').addEvent('blur', this.validateLoginForm.bind(this));

        this.disableLoginActionButton();
    },

    enableLoginActionButton: function() {
        $('ModalWindowActionButton').removeEvents();
        $('ModalWindowActionButton').addEvent('click', this.authenticate.bind(this));
        $('ModalWindowActionButton').set('opacity', '1.00');
        $('ModalWindowActionButton').setStyle('cursor', 'pointer');
    },

    disableLoginActionButton: function() {
        $('ModalWindowActionButton').removeEvents();
        $('ModalWindowActionButton').set('opacity', '0.25');
        $('ModalWindowActionButton').setStyle('cursor', 'default');
    },

    validateLoginForm: function() {
        var email = $('email').value;
        var password = $('password').value;

        if(this.isValidEmail(email) && password.length > 5) {
            return this.enableLoginActionButton();
        }

        this.disableLoginActionButton();
    },

    onLoginValidationSuccess: function(response) {
        switch(response) {
            case -1:
                this.setModalWindowStatus('please log in to associate your existing account!');
            break;
            default:
                this.setModalWindowStatus('please click here to create an account!');
            break;
        }
    },

    authenticate: function(options) {
        var data = {};
        if($('email')) data.username = $('email').value;
        if($('password')) data.password = $('password').value;
        if(options) {
            if(options.permissions) data.permissions = options.permissions;
        }

        var request = new Request.JSON({
            url: '/login/json',
            ajax: 1,
            onSuccess: function(response) {
                if(response.status.code) {
                    this.onAuthenticationSuccess(response);
                } else {
                    this.onAuthenticationFailed(response);
                }
            }.bind(this)
        }).post(data);
    },

    onAuthenticationSuccess: function(response) {
        this.close();
        Roar.alert('Login', 'Please wait while your request is processed');
        if(response.status.redirecturl) {
            this.redirect(response.status.redirecturl);
        } else if(this.loginRedirectUrl) {
            this.redirect(this.loginRedirectUrl);
        } else {
            this.redirect('/');
        }
    },

    onAuthenticationFailed: function(response) {

        if(!$('ModalWindowStatus') || $('ModalWindowTitle').get('html') != 'Login') {
            this.showLoginWindow();
            return;
        }

        var status = response.status;

        if(undefined !== status.error) {
            this.setModalWindowStatus(status.error, this.STATUS_WARNING);
        }

        if(undefined !== status.uri) {
            this.redirect(status.uri);
        }

        if(undefined !== status.roar) {
            var options = {};
            if(undefined !== status.duration) {
                options = {duration: status.duration};
            }
            Roar.alert(status.roar, status.message, options);
        }
    },

    onSignUpFacebookLoginSuccess: function(response) {
        if (!response) {
            // either an error occured or the user cancelled the login
            //Roar.alert('Connect to Facebook', 'Connection to your facebook account cancelled');
            return;
        }
        
        this.enableSignupEmail();
    },

    onLoginFacebookLoginSuccess: function(response) {
        if (!response) {
            // either an error occured or the user cancelled the login
            Roar.alert('Facebook Connect Error', 'We were unable to connect to Facebook.')
            return;
        }

        if(response.perms) {
            this.authenticate({permissions:response.perms});
        } else {
            this.authenticate();
        }
    },

    onConnectFacebookLoginSuccess: function() {
         var request = new Request.JSON({
            url: '/login/json',
            ajax: 1,
            onSuccess: function(response) {
                if(response.status.code) {
                    this.redirect();
                } else {
                    Roar.alert('Facebook Connect Error', response.status.error);
                }
            }.bind(this)
        }).post({});
    },

    onLoginComplete: function() {
        this.redirect('/account');
    },

    validateEmail: function() {
        email = this.options.element.value;
        if (this.isValidEmail(email)) {
            if(undefined==this.request && null==this.request) {
                this.request = new Request.JSON({
                    url: '/register?format=json',
                    link: 'cancel',
                    ajax: 1,
                    onSuccess: this.options.validationCallback
                });
            }
            if(this.currentEmailValue != email) {
                this.currentEmailValue = email;
                this.request.post({'email':email});
            }
        } else {
            this.currentEmailValue = email;
            this.options.validationCallback();
        }
    },

    isValidEmail: function(email) {
        var filter=/^.+@.+\..{2,3}$/;
        if(filter.test(email)) {
            return true;
        }
        return false;
    },

    onValdidateEmailSuccess: function(response) {
        if(response == 0) {
            this.reset();
            $('ModalWindowStatus').set('html', 'Please enter a valid email address');
        } else if(response == 1) {
            $('ModalWindowStatus').set('html', 'This E-mail Address is good to go ');
            $('VerificationImage').set('src', '/themes/highschoolseniorphotographers.com/images/signup-check.jpg');
            $('ModalWindowStatus').setStyle('color', '#333');
            //this.enableUserInfo();
            if(undefined != FB.getAuthResponse()) {
                this.enableSignupForm();
            }
        } else if(response == -1) {
            this.reset();
            $('ModalWindowStatus').set('html', 'This E-mail Address seems to be already in use, click <a onclick="FBConnect.login(\'' + this.options.element.value + '\')" style="color: red; text-decoration:underline;">here</a> to login');
            $('ModalWindowStatus').setStyle('color', 'red');
            $('VerificationImage').set('src', '/themes/highschoolseniorphotographers.com/images/signup-cross.jpg');
        }
    },

    redirect: function(newuri) {
        var uri = null;
        if(newuri) {
           uri = new URI(newuri);
        } else {
           uri = new URI();
        }
        
        uri.go();
    }
});

var FBConnect = new FacebookConnector();
