/*
 * Title: Flash Lightbox
 *
 * Description: Opens a full-window DHTML lightbox containing a flash movie at the given URL and of the given
 * dimensions. If the client browser does not support lightbox functionality, then a full-screen popup window is
 * opened containing the flash
 *
 *
 */

/*
 * #################################################################################################
 * Global Variables
 * #################################################################################################
 */

// Browsers that do not support lightboxes
var unsupportedBrowsers = [
    {
        OS: 'Mac',
        browser: 'Firefox'
    },
    {
        OS: 'an unknown OS',
        browser: 'An unknown browser'
    }
];

/*
 * Lightbox Variables
 */

// Variables to store current lightbox dimensions
var currentFlashWidth, currentFlashHeight, currentWidth, currentHeight;

// The lightbox
var lightbox;

// Current lightbox URL
var currentURL;

var deepLink = "none";

// Define lightbox flash template
var myTemplate =
'<div class="bbcjsUiLightBoxDefault"> ' +
        '<div id="lightbox-content">' +
            '<OBJECT classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" ' +
                'WIDTH="{l_width}" ' +
                'HEIGHT="{l_height}" ' +
                'id="{l_id}"> ' +
                '<PARAM NAME=movie VALUE="{l_url}?deepLink='+ deepLink +'"> ' +
                '<PARAM NAME=quality VALUE=high> ' +
                '<EMBED  src="{l_url}?deepLink='+ deepLink +'" ' +
                    'quality=high ' +
                    'WIDTH="{l_width}" ' +
                    'HEIGHT="{l_height}" ' +
                    'NAME="{l_id}" ' +
                    'TYPE="application/x-shockwave-flash" ' +
                '</EMBED> ' +
            '</OBJECT> ' +
        '</div>' +
'</div> ';

function updateTemplate()
{
    myTemplate =
'<div class="bbcjsUiLightBoxDefault"> ' +
        '<div id="lightbox-content">' +
            '<OBJECT classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" ' +
                'WIDTH="{l_width}" ' +
                'HEIGHT="{l_height}" ' +
                'id="{l_id}"> ' +
                '<PARAM NAME=movie VALUE="{l_url}?deepLink='+ deepLink +'"> ' +
                '<PARAM NAME=quality VALUE=high> ' +
                '<EMBED  src="{l_url}?deepLink='+ deepLink +'" ' +
                    'quality=high ' +
                    'WIDTH="{l_width}" ' +
                    'HEIGHT="{l_height}" ' +
                    'NAME="{l_id}" ' +
                    'TYPE="application/x-shockwave-flash" ' +
                '</EMBED> ' +
            '</OBJECT> ' +
        '</div>' +
'</div> ';
}



/*
 * #################################################################################################
 * Functions
 * #################################################################################################
 */




/*
 * Popup new window
 */
function popupFullScreenWindow(URL, this_width, this_height)
{

    var x = 10, y = 10; // default position

    // If browser supports screen object
    if (window.screen) {
        // Get screen width & height
        var aw = window.screen.availWidth;
        var ah = window.screen.availHeight;

        // If the available screen width or height is smaller than the current flash movie, scale the window
        if (ah < this_height || aw < this_width)
        {
            this_width = parseInt(Math.floor(aw / (this_width/this_height)));
            this_height = ah;
        }

        // Calculate x,y coordinates based on size
        x = (aw - this_width) / 2;
        y = (ah - this_height) / 2;
    }


    // Open in new window
    var pop_window = window.open(
        'popup.shtml?url=' + escape(URL) + '&width=' + this_width + '&height=' + this_height,
        'Me_and_my_movie',
            'width=' + this_width +
            ',height=' + this_height +
            ',left=' + x +
            ',screenX=' + x +
            ',top=' + y +
            ',screenY=' + y +
            ',fullscreen=no' +
            ',toolbar=no' +
            ',location=no' +
            ',directories=no' +
            ',status=no' +
            ',menubar=no' +
            ',scrollbars=no' +
            ',resizable=no'
            );

    // Name current window in case popup wants to talk back to it
    self.name = "main";

} // popWindow()

/* Opens a flash movie in a full screen lightbox
 *  url - the URL of the flash movie
 *  flashWidth - current width of the flash movie (used for aspect ratio calculation)
 *  flashHeight - current height of the flash movie (used for aspect ratio calculation)
 */
function openFullWindowFlashbox (url, flashWidth, flashHeight)
{
    var cl_bounds = getClientBounds();
    var clWidth = cl_bounds[0];
    var clHeight = cl_bounds[1];
    var flashAspectRatio = flashWidth / flashHeight;
    var lightBoxBorderWidth = 0;
    var box_height;
    var box_width;
    var fullscreen = false;

    // If the available window width or height is smaller than the current flash movie, scale the flash
    if (clHeight - (2 * lightBoxBorderWidth) < flashHeight || clWidth - (2 * lightBoxBorderWidth) < flashWidth)
    {
        // Resize box to full window
        fullscreen = true;
        box_height = clHeight - (2 * lightBoxBorderWidth);
        box_width = clWidth - (2 * lightBoxBorderWidth);

        flashHeight = box_height - lightBoxBorderWidth;
        flashWidth = parseInt(Math.floor((box_height - lightBoxBorderWidth) * flashAspectRatio));

        box_height = flashHeight;
        box_width = flashWidth;
    }
    else{
        // Set box at flash size minus border
        box_height = flashHeight - (2 * lightBoxBorderWidth);
        box_width = flashWidth - (2 * lightBoxBorderWidth);
        lightBoxBorderWidth = 3;
    }

        // create the JS lightbox
        lightbox = new bbcjs.ui.LightBox(
                [{
                    l_width: flashWidth,
                    l_height: flashHeight,
                    l_id: "mymovie",
                    l_url: url
                }], {
                showNav: false,
                width: box_width,
                height: box_height,
                top: document.body.scrollTop,
                borderWidth: lightBoxBorderWidth,
                boxBackground: '#000',
                template:myTemplate });


        // Open the light box (on 1st page)
        lightbox.open();				


     // Style the lightbox

     $('lightbox-content').style.width = flashWidth + 'px';

     if (!fullscreen)
     {
         $('bbcjsUiLightBoxOuter').style.top = '' + document.body.scrollTop + parseInt(Math.floor(((clHeight - box_height)/2))) + 'px';
         $('bbcjsUiLightBoxOuter').style.left = parseInt(Math.floor((clWidth - box_width)/2)) + 'px';
     }

     // Make lightbox opacity mask clickable to close lightbox
     function handleMaskClick(e)
     { 
	 	// Clean up the flash, to prevent ghost audio in IE
		cleanUpFlash();
		
	 	lightbox.close(); 				
	 }
     var mask = $('bbcjsUiLightBoxMask');
     mask.style.cursor = 'pointer';
     bbcjs.dom.addEventListener( mask, 'click', handleMaskClick );
	
}

function openPopupFlashbox (url, boxWidth, boxHeight, initialFlashWidth, initialFlashHeight, deep, fullscreen)
{
    openFullFlash (url, initialFlashWidth, initialFlashHeight, deep);
}

/*
 * Open full-window lightbox (if supported), else open full-screen popup window
 *
 *  url - the URL of the flash movie
 *  initialFlashWidth - current width of the flash movie (used for aspect ratio calculation)
 *  initialFlashHeight - current height of the flash movie (used for aspect ratio calculation)
 */
function openFullFlash (url, initialFlashWidth, initialFlashHeight, deep)
{
    //  HARDCODED DIMENSIONS TO AVOID CHANGING IN MANY PLACES
    initialFlashWidth = 800;
    initialFlashHeight = 550;

    // Store the current URL
    currentURL = url;
    deepLink = deep;
    updateTemplate();

    /*
     * Check browser compatibility for lightboxes
     */

    var unsupported = false;

    // for each unsupported browser
    for (var i=0; i<unsupportedBrowsers.length; i++)
    {
        // if this is an unsupported browser
        if (unsupportedBrowsers[i].OS == BrowserDetect.OS
            && unsupportedBrowsers[i].browser == BrowserDetect.browser)
        {
            // flag unsupported
            unsupported = true;
            break;
        }
    }

    if(!unsupported) {
        if(!getClientBounds()) {
            unsupported = true;
        }
    }

    // Open the flash in the form the browser supports
    if (unsupported)
        popupFullScreenWindow(url + '?deepLink=' + deep, initialFlashWidth, initialFlashHeight);
    else
        openFullWindowFlashbox(url, initialFlashWidth, initialFlashHeight);
}

/*
 * THIS FUNCTION ATTEMPTS TO CORRECTLY DETERMINE CLIENT BROWSER WINDOW BOUNDS.
 * IF UNABLE TO RELIABLY DO SO, IT WILL RETURN FALSE, CAUSING A POPUP TO BE USED
 * IN PLACE OF A LIGHTBOX.
*/
function getClientBounds()
{
    var clientWidth = null;
    var clientHeight = null;
    switch(BrowserDetect.browser) {
        case 'Explorer' :
            if (document.documentElement && document.documentElement.clientWidth)
                clientWidth = document.documentElement.clientWidth;
            else if (document.body)
                clientWidth = document.body.clientWidth;
            if (document.documentElement && document.documentElement.clientHeight)
                clientHeight = document.documentElement.clientHeight;
            else if (document.body)
                clientHeight = document.body.clientHeight;
            break;
        case 'Safari' :
            if(window.innerWidth && window.innerHeight) {
                clientWidth = window.innerWidth;
                clientHeight = window.innerHeight;
            }
            break;
        case 'Opera' :
        case 'Firefox' :
            if(window.innerWidth && document.body.clientWidth) {
                clientWidth = Math.min(window.innerWidth, document.body.clientWidth);
                clientHeight = Math.min(window.innerHeight, document.body.clientHeight);
            }
            break;
        default:
            if(window.innerWidth && document.documentElement.clientWidth) {
                clientWidth = Math.min(window.innerWidth, document.documentElement.clientWidth);
                clientHeight = Math.min(window.innerHeight, document.documentElement.clientHeight);
            }
            break;
    }

    return (clientWidth ? new Array(clientWidth, clientHeight) : false);
}

// This function cleans up the flash object on lightbox closing to avoid multiple layers of "ghost" audio in IE
function cleanUpFlash() {
  // Get the lightboxed flash object
  var object = $('mymovie');
  	// for each of its properties
	for (var x in object) {
		// try to null it
		try {object[x] = null;} 
		// ignoring exceptions thrown by those that are only getters
		catch (e) {};
	}
	// finally, null the object itself
	object = null;
}