_hcxd = window._hcxd || [];
IAM4 = window.IAM4 || {};
(function() {
    IAM4.Connector = function(id) {
        this.init(id);
    }; (function() {
        IAM4.Connector.prototype = function() {
            return {
                appId: '112564598793079',// Live
                apiKey: '0b8a21de1f9b2ad5591408c38100279a',// Live
                facebookPermissions: 'email,user_birthday,publish_stream',
                stylesheet: '/api/iam4-connector.css',
                URLs: {
                    base: 'http://iamnumberfourfans.com',
                    connect: '/api/facebook/connect/',
                    award: '/api/facebook/award/',
                    sweepstakes: '/activities/sweepstakes/'
                },
                sessionKey: '',
                itemsToDisplay: [],
                isLoggedIn: false,
                isLoaded: false,
                init: function(id) {
                    this.selector = '#' + id;
                    if (!this.isLoaded) {
                        var c = this;
                        jQuery(document).ready(function() {
                            c.isLoaded = true;
                            // Firefox is the 'slow cousin' of browsers...give him a lil more time
                            if (jQuery.browser.mozilla) {
                                window.setTimeout(function() {
                                    c._initFacebook();
                                }, 200);
                            } else {
                                c._initFacebook();
                            }
                        });
                    }
                },
                _initFacebook: function() {
                    var c = this;
                    FB.init({appId: c.appId, status: true, cookie: true, xfbml: true});
                    FB.Event.subscribe('auth.login', function(response) {
                        c._handleAuth();
                    });
                    FB.Event.subscribe('auth.logout', function(response) {
                        c._handleAuth();
                    });
                    FB.getLoginStatus(function(response) {
                        if (response.session) {
                            c.sessionKey = response.session.session_key;
                            c.isLoggedIn = true;
                            c._displayConnectedUI();
                        } else {
                            c._displayNoAuthUI();
                        }
                        // Delay for compatibility
                        window.setTimeout(function() {
                            c._triggerAuth();
                        }, 200);
                    });
                },
                logIn: function() {
                    var c = this;
                    FB.login(function(response) {
                        // alert(JSON.stringify(response));
                        if (response.session) {
                            if (response.perms) {
                                IAM4.Tracking.signIn();
                            } else {
                                // Do nothing
                            }
                        } else {
                            // Do nothing
                        }
                    }, {perms: this.facebookPermissions});
                    IAM4.Tracking.logIn();
                    return false;
                },
                logOut: function() {
                    // var url = 'https://www.facebook.com/logout.php?api_key=' + this.apiKey + '&session_key=' + this.sessionKey + '&next=' + escape(window.location.href);
                    jQuery('#im4c-me').html('Logging out...');
                    FB.logout(function() {
                        // alert('Bye!');
                    });
                    return false;
                },
                awardPoints: function(opts) {
                    var c = this;
                    jQuery.post(this.URLs.award, {opts: opts}, function(response) {
                        if (response.awarded) {
                            jQuery('#im4c-badge-awarded-points').html(response.score);
                            jQuery('#im4c-badge-original').fadeOut(500);
                            jQuery('#im4c-badge-awarded').fadeIn(500);
                            if (response.sweepstakes) {
                                c._displaySweepstakesMessage();
                                c._displaySweepstakesLink();
                                c._postToFacebookElder();
                            }
                        }
                    }, 'json');
                },
                bindAuth: function(selector, auth) {
                    var c = this;
                    jQuery(selector).bind('IAM4AUTH', {auth: auth}, function(event) {
                        if (event.data.auth == c.isLoggedIn) jQuery(this).show();
                    });
                    this.itemsToDisplay.push(selector);
                },
                _triggerAuth: function() {
                    jQuery.each(this.itemsToDisplay, function(index, value) {
                        jQuery(value).trigger('IAM4AUTH');
                    });
                },
                _handleAuth: function() {
                    // window.location.reload(true);
                    window.location.replace(window.location.href);
                },
                _displayNoAuthUI: function() {
                    this._guardSweepstakes(0, 0);
                    var c = this;
                    var markup = '<div id="im4c-not-connected"><div class="im4c-bar-holder"><div class="im4c-bar"><a href="#" class="im4c-sign-in">Sign in with Facebook</a></div></div></div>';
                    jQuery(this.selector).html(markup);
                    jQuery('.im4c-sign-in').click(function() {
                        return c.logIn();
                    });
                },
                _displayConnectedUI: function() {
                    var c = this;
                    var markup = '<div id="im4c-connected"><div class="im4c-bar-holder"><div class="im4c-bar"><div class="im4c-f">Logged in via Facebook</div><div class="im4c-info"><p id="im4c-me">...</p><br /><a href="#" id="im4c-enter" class="im4c-sweeps" style="display: none;"><span>[star]</span>Enter sweepstakes!</a><a href="#" id="im4c-build"><span>[key]</span>Build your points!</a></div><div id="im4c-badge-original" class="im4c-badge"><p id="im4c-badge-points">&nbsp;</p></div><div id="im4c-badge-awarded" class="im4c-badge im4c-awarding"><p id="im4c-badge-awarded-points">0</p></div><div class="im4c-log-out"><a href="#" id="im4c-log-out-button">Log out<span>&nbsp;&lt;</span></a></div></div></div></div><div id="im4c-key"><a href="/activities/learn-more/" id="im4c-key-learn">Points &ndash; Learn more</a></div>';
                    jQuery(this.selector).html(markup);
                    jQuery.post(this.URLs.connect, function(response) {
                        c._guardSweepstakes(response.score, response.sweeps);
                        jQuery('#im4c-me').html(c._getDisplayName(response.first_name, response.last_name));
                        jQuery('#im4c-badge-points').html(response.score);
                        if ((response.score > 24) && (response.score < 50)) {
                            jQuery('#im4c-badge-original').addClass('im4c-a-garde');
                        } else if (response.score > 49) {
                            jQuery('#im4c-badge-original').addClass('im4c-elder');
                        }
                        jQuery('#im4c-build').click(function() {
                            jQuery('#im4c-key').slideToggle(333, function() {
                                var copy = (jQuery('#im4c-key').css('display') == 'none') ? '<span>[key]</span>Build your points!' : '<span>[key]</span>Hide points key';
                                jQuery('#im4c-build').html(copy);
                            });
                            return false;
                        });
                        jQuery('#im4c-log-out-button').click(function() {
                            return c.logOut();
                        });
                        if (response.brand_new)
                            c._postToFacebookBrandNew();
                        if (response.sweepstakes)
                            c._displaySweepstakesLink();
                        if (response.fresh_session)
                            IAM4.Tracking.follow(response.email);
                    }, 'json');
                },
                _displaySweepstakesMessage: function () {
                    var c = this;
                    var markup = '<div id="im4s-congratulations"><p>You have scored 25 points! Click below to enter the official I AM NUMBER FOUR sweepstakes.</p><a href="#" id="im4s-enter-now">Enter now</a></div>';
                    jQuery('body').append(markup);
                    jQuery('#im4s-congratulations').fadeIn(500);
                    jQuery('#im4s-enter-now').click(function() {
                        window.location.replace(c.URLs.sweepstakes);
                        return false;
                    });
                },
                _displaySweepstakesLink: function() {
                    var c = this;
                    if (window.location.href.indexOf(c.URLs.sweepstakes) != -1)
                        return;
                    jQuery('#im4c-build').hide();
                    jQuery('#im4c-enter').show();
                    jQuery('#im4c-enter').click(function() {
                        window.location.replace(c.URLs.sweepstakes);
                        return false;
                    });
                },
                _guardSweepstakes: function(score, sweeps) {
                    if (window.location.href.indexOf(this.URLs.sweepstakes) != -1) {
                        if (score < 25) {
                            window.location.replace('/');
                        } else {
                            if (window.IAM4Sweepstakes)
                                window.IAM4Sweepstakes.present(score, sweeps);
                        }
                    }
                },
                _postToFacebookBrandNew: function() {
                    var post = {
                        message: 'has registered to join the Loriens on the I Am Number Four website as they fight to fulfill their destiny.',
                        picture: this.URLs.base + '/api/images/i-am-four-logo.jpg',
                        link: this.URLs.base,
                        name: this.URLs.base,
                        caption: 'I Am Number Four',
                        description: ' '
                    }
                    FB.api('/me/feed', 'post', post, function(response) {
                        // Facebook never fails!
                    });
                },
                _postToFacebookElder: function() {
                    var post = {
                        message: 'has fully developed their Legacies, and is ready to fight alongside Pittacus Lore as a Lorien Elder!',
                        picture: this.URLs.base + '/api/images/i-am-four-logo.jpg',
                        link: this.URLs.base,
                        name: this.URLs.base,
                        caption: 'I Am Number Four',
                        description: ' '
                    }
                    FB.api('/me/feed', 'post', post, function(response) {
                        // Facebook never fails!
                    });
                },
                _getDisplayName: function(first_name, last_name) {
                    var name = first_name;
                    var initial = last_name.charAt(0);
                    if (initial)
                        name += ' ' + initial + '.';
                    return name;
                }
            }
        }();
    })();

    IAM4.Sweepstakes = function(id) {
        this.init(id);
    }; (function() {
        IAM4.Sweepstakes.prototype = function() {
            return {
                URLs: {
                    enter: '/api/facebook/sweepstakes/'
                },
                isLoaded: false,
                init: function(id) {
                    var a = this;
                    this.selector = '#' + id;
                    this._disableForm();
                    jQuery('#im4s-copy-status').html('<p>Loading&hellip;</p>');
                    jQuery('#im4s-copy-status').show();
                },
                present: function(score, sweeps) {
                    jQuery('#im4s-copy-status').hide();
                    if (sweeps == 1) {
                        jQuery('#im4s-copy-duplicate').fadeIn(333);
                        this._hideForm();
                        return;
                    }
                    var s = this;
                    jQuery('#im4s-copy-welcome').fadeIn(333);
                    jQuery('#im4s-button-submit').click(function() {
                        s.enter();
                        return false;
                    });
                    this._enableForm();
                },
                enter: function() {
                    jQuery('#sweeps-copy div').hide();
                    if (!this._isValidForm())
                        return;
                    var s = this;
                    var data = jQuery(this.selector).serialize();
                    this._disableForm();
                    jQuery('#im4s-copy-status').html('<p>Sending&hellip;</p>');
                    jQuery('#im4s-copy-status').show();
                    jQuery.post(this.URLs.enter, data, function(response) {
                        jQuery('#im4s-copy-status').hide();
                        if (response.entered) {
                            jQuery('#im4s-copy-success').fadeIn(333);
                            s._hideForm();
                            return;
                        }
                        if (response.underage) {
                            jQuery('#im4s-copy-age-gate').fadeIn(333);
                            return;
                        }
                        // If we're here, something went wrong
                        jQuery('#im4s-copy-error').fadeIn(333);
                        s._enableForm();
                    }, 'json');
                },
                _isValidForm: function() {
                    var is_valid = true;
                    var message = '';
                    var email = jQuery.trim(jQuery('#im4s-input-email').val());
                    var month = jQuery('#im4s-input-month').val() - 1;
                    var day = jQuery('#im4s-input-day').val();
                    var year = jQuery('#im4s-input-year').val();
                    var birth_date = new Date(year, month, day);
                    if (!email || (email == '') || !(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test(email))) {
                        is_valid = false;
                        message += '<p>Please enter a valid e-mail address.</p>';
                    }
                    if ((month != birth_date.getMonth()) || (day != birth_date.getDate()) || (year != birth_date.getFullYear())) {
                        is_valid = false;
                        message += '<p>Please enter a valid date.</p>';
                    }
                    if (!is_valid) {
                        jQuery('#im4s-copy-status').html(message);
                        jQuery('#im4s-copy-status').show();
                    }
                    return is_valid;
                },
                _disableForm: function() {
                    jQuery(this.selector + ' input').attr('disabled', 'disabled');
                    jQuery(this.selector + ' select').attr('disabled', 'disabled');
                    jQuery('#im4s-button-submit').hide();
                    jQuery('#im4s-button-disabled').show();
                },
                _enableForm: function() {
                    jQuery(this.selector + ' input').removeAttr('disabled');
                    jQuery(this.selector + ' select').removeAttr('disabled');
                    jQuery('#im4s-button-submit').show();
                    jQuery('#im4s-button-disabled').hide();
                },
                _hideForm: function() {
                    jQuery('#im4s-button-back-to-home').fadeIn(333);
                    jQuery('#im4s-button-disabled').hide();
                    jQuery('#sweeps-form-container').hide();
                    jQuery('#sweeps-form-header').hide();
                    jQuery('#sweeps-legal').hide();
                }
            }
        }();
    })();

    IAM4.Activity = function(id) {
        this.init(id);
    }; (function() {
        IAM4.Activity.prototype = function() {
            return {
                URLs: {
                    events: '/api/facebook/events/'
                },
                statuses: {
                    game: 'Completed the <a href="/activities/in-plain-sight/">game</a>',
                    poll: 'Completed a <a href="/activities/pollsarchive/">poll</a>',
                    quiz: 'Completed a <a href="/activities/quizarchive/">quiz</a>',
                    horoscope: 'Checked this month\'s <a href="/activities/horoscope/">horoscope</a>'
                },
                eventsToDisplay: 5,
                isLoaded: false,
                init: function(id) {
                    var a = this;
                    this.selector = '#' + id;
                    jQuery.get(this.URLs.events + this.eventsToDisplay, function(response) {
                        jQuery.each(response, function(key, value) {
                            jQuery(a.selector).append('<div class="im4a-event"><img src="http://graph.facebook.com/' + value['id'] + '/picture?type=square" alt="' + value['name'] + '" /><p>' + value['name'] + ' &ndash; <span>' + a.statuses[value['type']] + '</span></p></div>');
                        });
                    }, 'json');
                }
            }
        }();
    })();

    IAM4.API = {
        logIn: function() {
            if (window.IAM4Widget)
                return window.IAM4Widget.logIn();
            return false;
        },
        displayIfLoggedIn: function(selector, auth) {
            if (window.IAM4Widget)
                window.IAM4Widget.bindAuth(selector, auth);
        },
        isLoggedIn: function() {
            if (window.IAM4Widget)
                return window.IAM4Widget.isLoggedIn;
            return false;
        },
        awardPoints: function(opts) {
            if (window.IAM4Widget)
                window.IAM4Widget.awardPoints(opts);
            return false;
        },
        enterSweepstakes: function() {
            if (window.IAM4Sweepstakes)
                window.IAM4Sweepstakes.enter();
            return false;
        }
    };

    IAM4.Tracking = {
        logIn: function() {
            if (window._gaq)
                _gaq.push(['_trackEvent', 'FBConnect', 'Login']);
        },
        signIn: function() {
            if (window._gaq)
                _gaq.push(['_trackEvent', 'FBConnect', 'Registration']);
        },
        follow: function(email) {
            if (window._hcxd)
                _hcxd.push(['email_reg', email]);
        }
    };
})();
