/*global $, $$, $F, Event, Element, window */
var Login = Login ? Login : {
    dialogID : '__embeditin_login',
    openid_endpoint : '/sessions/openid_new',
    twitter_endpoint : '/sessions/twitter_new',
    token_url : null,
    cookie_jar : null,
    on_cancel : null,

    methods : [
        {
            name : 'Google',
            image : '/images/login/google.png',
            openid : 'https://www.google.com/accounts/o8/id'
        },
        {
            name : 'Yahoo',
            image : '/images/login/yahoo.png',
            openid : 'http://yahoo.com'
        },
        {
            name : 'Twitter',
            image : '/images/login/twitter.png',
            twitter : true
        },
        {
            name : 'AOL',
            image : '/images/login/aol.png',
            prompt : 'AOL screenname',
            openid : 'http://openid.aol.com/<CREDENTIAL>'
        },
        {
            name : 'WordPress',
            image : '/images/login/wordpress.png',
            prompt : 'WordPress blog URL',
            openid : '<CREDENTIAL>'
        },
        {
            name : 'OpenID',
            image : '/images/login/openid.png',
            prompt : 'OpenID URL',
            openid : '<CREDENTIAL>'
        }
    ],

    selectedMethod : null,

    createInterface : function () {
        var overlay = new Element('div', {
            id : Login.dialogID,
            style : 'z-index: 10000; width: 100%; height: 100%; position: fixed; left: 0px; top: 0px; background-image: url(/images/login/background.png);'
        });
        var dialog = new Element('div', {
            id : Login.dialogID + '_dialog',
            style : 'margin: auto; width: 471px; height: 396px; background-color: transparent; position: fixed;'
        });
        
        var dialog_contents = new Element('div', {style : 'padding: 20px; background-color: #f7f7f7; float: left; width: 360px; height: 285px;'});
        
        // Create the chrome around the login dialog -- nearly identical to chrome around player, if this is updated, you should probably update that chrome too
        var images = [['top_left_plain', 'top', 'top_right'], ['left', '', 'right'], ['bottom_left', 'bottom', 'bottom_right']];
        for (var i=0; i<3; i++) {
            for (var j=0; j<3; j++) {
                if (i == 1 && j == 1) {
                    // Put the center element in place
                    dialog.insert(dialog_contents);
                    continue;
                }
                
                // Create the chrome
                var chrome = new Element('div', {id : Login.dialogID + 'Chrome' + i + j, style : 'background-color: transparent; float: left;'});
                chrome.style.backgroundImage = 'url(/images/overlay/' + images[i][j] + '.png)';
                
                if (j == 0 || j == 2) {
                    chrome.style.width = '35px'; // Left or right side are always 35px wide
                } else if (i != 1) {
                    // Login dialog is 470px wide (plus 1 px for fudge)
                    chrome.style.width = '400px';
                }
                
                if (i == 0 || i == 2) {
                    chrome.style.height = '35px'; // Same shiz down here except for height
                } else if (j != 1) {
                    chrome.style.height = '325px';
                }
                
                dialog.insert(chrome);
            }
        }

        dialog_contents.insert(new Element('div', {style : 'font-size: 2em;'}).update('Sign in'));

        var options = new Element('div', {id : Login.dialogID + '_options'});
        options.update('<p style="margin-bottom: 5px;">Choose one of these third-party accounts:</p>');

        Login.methods.each(function (method) {
            var button = new Element('div', {'class' : "__embeditin_login_option"});
            button.update('<img src="' + method.image + '" alt="' + method.name + '" style="width: 150px; height: 50px;" />');
            button.observe('click', Login.chooseMethod.curry(method));
            options.insert(button);
        });

        dialog_contents.insert(options);

        var prompt = new Element('div', {
            id : Login.dialogID + '_prompt',
            style : 'display: none;'
        });

        prompt.update('<div><img src="" alt="" /></div><form><div><label for="openid_credential"></label></div><div><input name="openid_credential" id="' + Login.dialogID + '_credential" type="text" /><button>Sign in &raquo;</button></div></form>');

        var linkBack = new Element('a', {href : '#'}).update('&laquo; Choose another account');
        linkBack.observe('click', Login.show);
        prompt.insert(linkBack);

        dialog_contents.insert(prompt);
        overlay.insert(dialog);
        $$('body')[0].insert(overlay);
        Event.observe(window, 'resize', Login.adjustSize);
        Login.adjustSize();
        prompt.down('form').observe('submit', Login.runSignIn);
        
        Login.cookie_jar = new CookieJar();
    },

    runSignIn : function (event) {
        if (event) {
            event.stop();
        }

        var method = Login.selectedMethod;
        if (!method) {
            return;
        }

        var options = {
            token_url : Login.token_url || document.location.href
        };
        if (method.openid) {
            var url = method.openid;
            if (method.prompt) {
                var credential = $F(Login.dialogID + '_credential');
                url = url.sub(/\<CREDENTIAL\>/, credential);
                var all_credentials = Login.cookie_jar.get('credentials') || {};
                all_credentials[method.name] = credential;
                Login.cookie_jar.put('credentials', all_credentials);
            }
            options.url = url;
            document.location.href = Login.openid_endpoint + '?' + Object.toQueryString(options);
        } else if (method.twitter) {
            document.location.href = Login.twitter_endpoint + '?' + Object.toQueryString(options);
        }
    },

    chooseMethod : function (method, event) {
        Login.selectedMethod = method;
        if (method.prompt) {
            var prompt = $(Login.dialogID + '_prompt');
            prompt.down('img').src = method.image;
            prompt.down('img').alt = method.name;
            prompt.down('label').update(method.prompt + ':');
            prompt.show();

            var all_credentials = Login.cookie_jar.get('credentials') || {};
            prompt.down('input').value = all_credentials[method.name] || '';
            prompt.down('input').activate();

            $(Login.dialogID + '_options').hide();
        } else {
            Login.runSignIn();
        }
    },

    adjustSize : function (event) {
        var overlay = $(Login.dialogID);
        var dialog = $(Login.dialogID + '_dialog');

        dialog.setStyle({
            left : ((overlay.getWidth() - dialog.getWidth()) / 2.0) + 'px',
            top : ((overlay.getHeight() - dialog.getHeight()) / 2.0) + 'px'
        });
    },

    show : function () {
        if (!$(Login.dialogID)) {
            Login.createInterface();
        }
        Login.selectedMethod = null;
        $(Login.dialogID + '_options').show();
        $(Login.dialogID + '_prompt').hide();
        $(Login.dialogID).show();
    },

    hide : function () {
        $(Login.dialogID).fade({duration : 0.5});
        if (Login.on_cancel) {
          Login.on_cancel();
        }
    }
};
