var registrationLightbox = null;
var enabledRefreshOnRegistrationClose = false;
var registrationIframeUrl = undefined;
var loginLightbox;
var tutorialLightbox;
var introVideoLightbox;

// FIXME: this function seems to be unecessary. used only on verify_email.js
// It could just call loginLightbox.hide()
function closeLoginLightBox(isRefresh, redirect_to) {
    if (loginLightbox) {
        loginLightbox.hide();
        glow.dom.get("#loginLightbox").css("display", "none");
    }
    if (isRefresh) {
        if (redirect_to) {
            window.location.href = redirect_to;
        } else {
            window.location.reload();
        }
    }
}


function showRegistrationBox() {
    var url = window.location.href;
    //jsvar_is_production is defined in the footer
    if (jsvar_is_production && url.indexOf("https://") == -1) {
        var registration_url = "https://" + window.location.host + "/register?opener=" + encodeURIComponent(window.location.href.replace(/#.*$/, "")) + "&lightbox=true";
    }
    else {
        var registration_url = "/register?opener=" + encodeURIComponent(window.location.href.replace(/#.*$/, "")) + "&lightbox=true";
    }
    var focusing_needed = true;
    var frame_obj = e$('newfo_registration_iframe');
    //Do not recreate the lightbox object multiple times - but if the user used
    //the backspace/back button to navigate back to the empty page, reload
    if (!frame_obj) {
        //load the registration content - use oldfo resource, as the fo resource is the same
        var iframe_tag = document.createElement('iframe');
        iframe_tag.id = "newfo_registration_iframe";
        iframe_tag.name="newfo_registration_iframe";
        iframe_tag.src= registration_url;
        iframe_tag.frameBorder = 0;
        iframe_tag.width = "720px";
        iframe_tag.height= "515px";
        iframe_tag.scrolling = "no";
        e$('registration_lightbox_container').appendChild(iframe_tag);
        frame_obj = e$('newfo_registration_iframe');
        focusing_needed = false;
    }
    if (registrationLightbox == null) {
        registrationLightbox = new glow.widgets.Panel('#registration_lightbox_container', {
            width: 792,
            closeOnMaskClick: false,
            template: "<div class='registration_lightbox'>" +
                      glow.dom.get("#regLightboxTemplate").html() + "</div>"
        });

        glow.events.addListener(".registration_lightbox .panel-close", "click", function() {
            destroyRegistrationBox();
        });
        showById("registration_lightbox_container");
    }
    registrationLightbox.show();
    if (focusing_needed) {
        //Make it harder in IE to use the backspace as the back button with
        //setting the focus on the first visible field
        //If we do not create the lightbox, the content is not reloaded so the
        //focus must be set from outside
        jQuery.pm({target: window.frames['newfo_registration_iframe'],
            url: registrationIframeUrl,
            type: 'registration_focusByStep'
        });
    }
}

function showLoginLightBox(isReset, loginFor) {
    var link = isReset ? '/reset_user_password' : login_link;
    if (loginFor != undefined) {
        link += '?loginFor=' + loginFor;
    }
    var temp = "<iframe id='newLoginIFrame' name='newLoginIFrame' frameborder='0' width='410px' height='240px' scrolling='no' src='" + link + "'></iframe>";
    e$('newLoginIFrame').parentNode.innerHTML = temp;
    glow.dom.get("#loginLightbox").css("display", "block");
    loginLightbox.show();
}


/**
 * Destroys the registration lightbox not only hides it.
 * @return
 */
function destroyRegistrationBox() {
    if (registrationLightbox!=null) {
        registrationLightbox.hide();
        delete registrationLightbox;
        if (enabledRefreshOnRegistrationClose) {
            //After login, we should be under https
            if (jsvar_is_production) {
                window.location.href = "https://" + window.location.host + newfo_prefix + "/home_page";
            }
            else {
                window.location.href = newfo_prefix + "/home_page";
            }
        }
    }
}

function enableRefreshOnRegistrationClose() {
    enabledRefreshOnRegistrationClose = true;
}

function setRegistrationIframeUrl(url) {
    registrationIframeUrl = url;
}

/**
 * Implements the change to the registration box, assuming that the
 * login box is open. The login box must be hidden to show the registration
 * box.
 * @return - undefined
 */
function goFromLoginToRegistration() {
    loginLightbox.hide();
    showRegistrationBox();
}


/**
 *  All windowed Flashes will show on the top of everything, even lightbox,
 *  need to set wmode to transparent or opaque.
 */
function setFlashWMode() {
    // Object.innerHTML doesn't work in IE6, so hide windowed flashes in IE6
    if (glow.env.ie < 7) return;
    var flashes = document.getElementsByTagName("embed");
    var flashes_number = flashes.length;
    for (var i = 0, flashesLen = flashes_number; i < flashesLen; i++) {
        var wmode = flashes[i].getAttribute('wmode');
        if (wmode == null || wmode.toLowerCase() == 'window') {
            flashes[i].setAttribute('wmode', 'opaque');
            flashes[i].setAttribute('src', flashes[i].getAttribute('src'));
        }
    }

    flashes = document.getElementsByTagName("object");
    flashes_number = flashes.length;
    for (var i = 0, flashesLen = flashes_number; i < flashesLen; i++) {
        var fParent = flashes[i].parentNode,
            flashHTML = fParent.innerHTML,
            lowerCaseFlashHTML = flashHTML.toLowerCase(),
            search_re = /<param[^>]*name="wmode"[^>]*>/,
            s_start = lowerCaseFlashHTML.search(search_re),
            s_end, newFlashHTML;
        if (s_start != -1) {
            s_end = lowerCaseFlashHTML.indexOf('>', s_start);
            if (lowerCaseFlashHTML.substring(s_start, s_end).search(/value="window"/) != -1) {
                newFlashHTML = flashHTML.substring(0, s_start) + '<param name="wmode" value="opaque">' + flashHTML.substring(s_end + 1, flashHTML.length);
            }
        } else {
            s_end = lowerCaseFlashHTML.indexOf('</object>');
            newFlashHTML = flashHTML.substring(0, s_end) + '<param name="wmode" value="opaque">' + flashHTML.substring(s_end + 10, flashHTML.length);
        }
        if (newFlashHTML) {
            fParent.innerHTML = newFlashHTML;
        }
    }
}


function createLightbox(content, template, hide_close_button, width)
{
    // get default template
    if (!template){
        template = glow.dom.get("#lightboxTemplate").html();
    }
    if (!width) width = 460;
    // create panel widget
    var panel = new glow.widgets.Panel(content, {
        width: width,
        closeOnMaskClick: false,
        template: template
    });
    // hide close button
    if (hide_close_button){
        panel.content.get(".lightbox-close").css("display", "none");
    }
    return panel;
}

function showTutorialLightbox(swfUrl) {
    var template = "<div class='tutorial-panel'>" + glow.dom.get("#lightboxTemplate").html() + "</div>";
    tutorialLightbox = createLightbox("#tutorialLightbox", template, false, 635).show();
    glow.dom.get("#tutorialLightbox").css("display", "block");
    var so = new SWFObject(swfUrl, "tutorial_lightbox_content_swf", "640", "360", "8", "#000000");
    so.addParam("allowScriptAccess", "always");
    so.addParam("allowFullScreen", "true");
    so.addParam("wmode", "opaque");
    glow.dom.get('.tutorial_lightbox_content_swf_container').html(so.getSWFHTML());

}

function closeTutorialLightbox() {
    if (tutorialLightbox) {
        tutorialLightbox.hide();
        glow.dom.get("#tutorialLightbox").css("display", "none");
    }
}


function showIntroVideoLightbox(swfUrl) {
    var widgets = nb.homepage.widgets;
    if (widgets.objstore.user.skip_intro_video) {
        return;
    }

    var template = "<div class='intro-video-panel'>" + glow.dom.get("#lightboxTemplate").html() + "</div>";
    introVideoLightbox = createLightbox("#introVideoLightbox", template, false, 640);
    // first time user show "not again" checked by default
    if (widgets.objstore.user.skip_intro_video === undefined) {
        introVideoLightbox.content.get("input")[0].checked = true;
    }
    else {
        introVideoLightbox.content.get("input")[0].checked = false;
    }
    glow.dom.get("#introVideoLightbox").css("display", "block");
    var so = new SWFObject(swfUrl, "intro_video_lightbox_content_swf", "640", "360", "8", "#000000");
    so.addParam("allowScriptAccess", "always");
    so.addParam("allowFullScreen", "true");
    so.addParam("wmode", "opaque");
    glow.dom.get('.intro_video_lightbox_content_swf_container').html(so.getSWFHTML());
    glow.events.removeAllListeners($('.intro-video-panel .panel-close'));
    glow.events.addListener('.intro-video-panel .panel-close', "click", closeIntroVideoLightbox);
    introVideoLightbox.show();
}

function closeIntroVideoLightbox() {
    var not_again = introVideoLightbox.content.get("input")[0].checked;
    var widgets = nb.homepage.widgets;
    widgets.objstore.user.skip_intro_video = not_again;
    widgets.saveCustomizedObject(null, "user", widgets.objstore.user);
    if (introVideoLightbox != null) {
        introVideoLightbox.hide();
    }
}

glow.ready(function() {
    var loginLightboxTemplate = "<div class='login-panel'>" +
        glow.dom.get("#lightboxTemplate").html() + "</div>";
    loginLightbox = createLightbox("#loginLightbox", loginLightboxTemplate);

    glow.events.addListener("#login", "click", function () {
        showLoginLightBox();
    });

    glow.events.addListener("#freeRegistration", "click", function () {
        showRegistrationBox();
    });

    setFlashWMode();
});


function showPokerClientWarningLightBox(isReset, loginFor) {
    createLightbox("#pokerClientWarningLightbox").show();
}

/**
 * Creates the confirm lightbox for some operations on the widgets.
 *
 * @param content: (str - CSS selector) of the lightbox's template part
 * @param onConfirm(panel, notAgain): (function reference) for the action of confirm button
 *         panel: the light box instance
 *         notAgain: whether the "not again" checkbox is ticked
 * @param onDiscard(panel): (function reference) for the action of discard/cancel button
 *         panel: the light box instance
 * @param hide_close_button: (boolean) hide the close button on the right-top corner
 * @param width: (int) the width of the lightbox
 */
function createConfirmLightBox(content, onConfirm, onDiscard, hide_close_button, width) {
    if (!width) width = 460;
    var template = "<div class='confirmation-dialog'>" +
            g$('#lightboxTemplate').html() + "</div>";
    var panel = createLightbox(content, template, hide_close_button, width);
    panel.content.get("input")[0].checked = false;

    var confirm_btn = g$(content + ' .roll_over_reg_go_to_btn_middle');
    glow.events.removeAllListeners(confirm_btn);
    if (onConfirm)
        glow.events.addListener(confirm_btn, "click", function() {
            onConfirm(panel, panel.content.get("input")[0].checked);
        });

    var discard_btn = g$(content + ' .roll_over_discard_change_btn_middle');
    glow.events.removeAllListeners(discard_btn);
    if (onDiscard)
        glow.events.addListener(discard_btn, "click", function() {
            onDiscard(panel);
        });
    panel.show();
}
