
var Room = (function(window, $) {
    var location = window.location;
    var is_in_iframe = function() { return (location !== window.parent.location); };
    var is_public = false;  // see go_public() and go_private()

    function get_swf_interface() {
        var swf_interface = $('#flashclient embed').get(0);
        if(!swf_interface) { swf_interface = $('#flashclient').get(0); }
        return swf_interface || null;
    }

    function flash_refresh_FB_session() {
        var swf = get_swf_interface();
        if (swf) { swf.fbSessionRefreshed(); }
    }

    // Called by flash, redirects the browser to the appropriate page.
    // Possible reason values: 'signup', 'login', 'booted', 'clash', null
    function redirect(reason) {
        reason = reason || '';
        if (is_in_iframe()) {
            location.replace('lobby?iframe=1' + (reason ? '&reason='+reason : ''));
        }
        else if (reason === 'signup' || reason === 'login') {
            location.replace('/login/?next=' + location.href);
        }
        else {
            location.replace('lobby?' + (reason ? 'reason='+reason : ''));
        }
    }

    // Open the pricing page in a new window.
    function open_pricing_page() {
        var new_window = window.open('http://mingleverse.com/pricing/', 'pricing',
                                     'height=850,width=1000,resizable=1,scrollbars=1');
        if (window.focus) { new_window.focus(); }
    }

    // Opens the avatar editor page in a new window.
    function open_avatar_editor() {
        var window_url = '/profile/avatar/';
        if (window.location.search.match('fbapp=1')) {
            window_url = 'http://apps.facebook.com/mingleverse/avatar/';
        }
        var new_window = window.open(window_url, 'avatar_editor', 'height=850,width=800,resizable=1,scrollbars=1');
        if (window.focus) { new_window.focus(); }
    }

    // Give the login box in the top right corner of the page focus.
    function login_focus() {
        var loginbox = $('#dropDownInputs');
        if (loginbox) {
            $(loginbox).show().find('input[name=username]').focus();
        }
    }

    function FB_photos_setup() {
        if (window.FB && FB.login) {
            FB.login(function(response) {
                if (response.perms.indexOf('user_photos') > -1) {
                    flash_refresh_FB_session();
                }
            }, {perms:"user_photos"});
        }
    }

    function FB_signup(require_photos) {
        var extra_permissions = require_photos ? ['user_photos'] : [];
        var login_options = {'next': window.location.pathname,
                             'extra_permissions': extra_permissions };
        fb_login(login_options, function() {
            flash_refresh_FB_session();
            $('#header').load(location.href + ' #header');   // Reload logged-in version of header
        });
    }

    function FB_feed_post(msg, link) {
        FB.login(function(response) {
            if (response.session) {
                FB.ui({ method: 'feed',
                        message: msg || '',
                        link: link || ''
                      }
                );
            }
        });
    }

    // Share the room link, using a shortened URL if possible:
    function share(service_name) {
        var share_msg = 'I just entered a MingleRoom. Join me there:',
            room_url = $('link[rel=canonical]').eq(0).attr('href') || window.location.href,
            share_window = null;

        function build_share_url(service, room_url) {
            var window_url = '';
            if (service_name === 'twitter') {
                window_url = "http://twitter.com/share?text=" + encodeURIComponent(share_msg) +
                                                      '&url=' + encodeURIComponent(room_url) +
                                                      '&via=mingleverse';
            }
            else if (service_name === 'linkedin') {
                window_url = "http://www.linkedin.com/shareArticle?mini=true&source=Mingleverse";
                window_url += '&summary=' + encodeURIComponent(share_msg);
                window_url += '&url=' + encodeURIComponent(room_url);
            }
            return window_url;
        }

        if (service_name !== 'facebook') {
            // Open new browser window with sharing info.
            // This must be done here (before waiting for the shortened url),
            // otherwise popup blockers will stop the window from opening.
            // We will update the window's location once we have a shortened URL.
            share_window = window.open(build_share_url(service_name, room_url), 'Share', 'height=300,width=500');
        }
        MV.Util.shorten_url(room_url, service_name, function(data) {
            var url_to_share = data.short_url || room_url;
            if (share_window) {
                // Update the url of the extra window we popped up earlier:
                share_window.location.href = build_share_url(service_name, url_to_share);
            }
            if (service_name === 'facebook') {
                // Post to facebook whether or not we received a shortened URL:
                FB_feed_post(share_msg, url_to_share);
            }
        });
    }

    return {
        'FB_signup': FB_signup,
        'is_in_iframe': is_in_iframe,
        'login_focus': login_focus,
        'open_avatar_editor': open_avatar_editor,
        'open_pricing_page': open_pricing_page,
        'redirect': redirect,
        'reload': function() { location.reload(true); },
        'require_FB_photos': FB_photos_setup,
        'share': share,
        'swf_interface': get_swf_interface
    }
})(window, jQuery);


/* Sub-module to handle rooms "going public" */
Room.publicity = (function() {
    var exports = {};
    var is_public = undefined;
    var status_endpoint_url = null;

    // Set up handler for links that change the room's publicity status:
    $('#public_modal a.go_public').live('click', function(e) {
        e.preventDefault();
        var public_status = $(this).data('makepublic');
        var post_params = {'makepublic': public_status };
        status_endpoint_url = this.href;
        $.post(status_endpoint_url, post_params, function(data) {
            $('#public_modal').hide();
            if (data === 'OK') {
                is_public = (public_status === 1);
            }
        });
    });

    // Remove from public room list (if possible) on unload:
    $(window).unload(function() {
        if (status_endpoint_url) {
            $.ajax({ url: status_endpoint_url,
                     type: 'POST',
                     data: {'makepublic': '0' },
                     async: false });    // async is false so request can complete before unload
        }
    });

    // Return the room's publicity status. Will return undefined unless the user set it during this session.
    exports.get_status = function() {
        return is_public;
    }

    // Open a modal dialog with public room options:
    exports.open_modal = function() {
        $('#public_modal').show().load('/rooms/public_list/');
    };

    return exports;
}());



var OOBE = (function(document, $) {
    var move_download_box = function(offset) {
        offset = offset || 0;   // Number of pixels right of center to move the download box
        var dl_box = $('#download_box');
        var half_box_width = dl_box.width()/2 + parseInt(dl_box.css('padding-left'), 10);
        var left_position = ($(document).width()/2 - half_box_width + offset);
        dl_box.css('left', left_position);
    }

    var show_download_box = function() {
        if (Room.is_in_iframe()) {
            $('#download_box').addClass('in_iframe');
        }
        $('#download_box').show();
        move_download_box(0);   // Center the download box

        var mac_re = /Mac/gi;
        if (mac_re.exec(navigator.platform)) {
            $('#download_box #windows').hide();
            $('#download_box #mac').show();
        }
    }

    var hide_download_box = function() {
        $('#download_box').hide();
    }

    var handle_download_click = function(id) {
        var swf_interface = Room.swf_interface();
        if (swf_interface !== null) {
            swf_interface.downloadStarted();
        }

        var _gaq = _gaq || [];
        var tracker_label = '' + id;
        var tracker_value = parseInt(id, 10) ? 1 : 0;
        _gaq.push(['_trackEvent', 'OOBEWizard', 'ClickDownloadLink', tracker_label, tracker_value]);
    }

    return {
        'handle_click': handle_download_click,
        'move_download': move_download_box,
        'show_download': show_download_box,
        'hide_download': hide_download_box
    }
})(document, jQuery);

$(document).ready(function() {
    function resize_room() {
        var min_height = 460;
        var iframe_mode = location.search.indexOf('iframe=1') > -1;
        var header_height = iframe_mode ? 38 : 80;
        var win_height = $(window).height();
        if (win_height > min_height + header_height) {
            $('#main').css('height', win_height - header_height);
        }
        else {
            $('#main').css('height', min_height);
        }
    }
    $('#header a').not('.logout').not('#cancelLink').attr('target', '_blank');  // open profile links in a new tab
    $('a.share').click(function(e) {
        var service = $(this).attr('data-service');
        if (service) { Room.share(service); }
        e.preventDefault();
    });
    $(window).resize(resize_room);
    resize_room();

    $(window).unload(function() {
        var swf_interface = Room.swf_interface();
        if (swf_interface !== null) {
            swf_interface.exit();
        }
    });
});

