/* Parts of this file use functions providing by the yahoo Dom scripts
 * so make sure it's included whenever this one is.
 */
// Global slide show params
var globScrollTimer = 0;
var globPosition = 0;
var slideImageRelSize=0.9;
var globFigCaptionID;
var globSlideNumber=0;
var globSlidesArray = new Array();
var globTitlesArray = new Array();
var globInlineSlideShow_callback;
var globRelSize = 0.95;
var globZoomIterations = 10;
var globZoomTimerInterval = 3;
var h_offset_for_centre;
var w_offset_for_centre;
var globH;
var globW;
var uniqCtr=0;
var padding=10;
var initTime = 0;

function scrubImages(tag)
{
    while(tag.getElementsByTagName("img").length > 0){
        tag.removeChild(tag.getElementsByTagName("img")[0]);
    }
    
}

// this function blows up a single image

function bigUpLink(link, dummy_pic)
{
    var slides_array = new Array(1);
    var title_array  = new Array(1);
    slides_array[0]  = link;
    title_array[0]   = '';

    slideShowEntryPoint(slides_array, 0, title_array, dummy_pic, function(){return;});
}

function bigMeUp(img)
{
    var slides_array = new Array(1), an_id;
    var title_array = new Array(1);
    
    var re = /(&width=[0-9]*)|(&height=[0-9]*)|(&maxHeight=[0-9]*)|(&maxWidth=[0-9]*)/gi
    slides_array[0] = img.src.replace(re, "");
    title_array[0] = img.title;
    
    if (!img.id)
    {
        an_id = "BlownUp" + uniqCtr++;
        img.id = an_id;
    }
    else
    {
        an_id = img.id;
    }
    
    slideShowEntryPoint(slides_array,
                        0, 
                        title_array, // figure_caption_array
                        "iamadummy", // this is a dummy id prefix - for blowing up single graph don't need explanation
                        function () { return; } 
                       );
    return;
}

// this function is called by the report section image onclick event
function slideShowEntryPoint(slides_array, slide_number, titles_array, explanation_prefix, callback)
{

    globInlineSlideShow_callback = callback;

    // if already in a slideshow then stop that one and do this one instead
    closeSlideShow();

    // setup transparent layer
    var float_layer = setupTransparentLayer();

    window.onresize = refreshSlide;
    
    globSlidesArray = slides_array;
    globTitlesArray = titles_array;
    globSlideNumber = slide_number;
    //globFigCaptionID = figure_caption_id;
    zoomTransparency(float_layer, 
                     1,
                     function () { updateFigureTitle(float_layer);
                                   insertButtons(float_layer, explanation_prefix);
                                   doSlideShow(explanation_prefix); }
                     );
    
}

function calculateHW()
{
    // get heights and widths
    var h, w;
    h = YAHOO.util.Dom.getViewportHeight();
    w = YAHOO.util.Dom.getViewportWidth();

    h_offset_for_centre = Math.round((1-globRelSize) * h / 2);
    w_offset_for_centre = Math.round((1-globRelSize) * w / 2);

    h *= globRelSize; h = Math.round(h);
    w *= globRelSize; w = Math.round(w);
    
    globH = h;
    globW = w;
}

function setupTransparentLayer()
{

    /*Time when the overlay was initialized*/
    var date1 = new Date();
    initTime = date1.getTime();

    calculateHW();

    // grab the imgfloatlayer where all the slideshow stuff goes on
    var float_layer = document.createElement("div");
    float_layer.id = "imgfloatlayer";
    float_layer.style.position = "absolute";
    //float_layer.style.backgroundAttachment = "fixed";
    float_layer.style.textAlign = "center";
    float_layer.style.left = 0 + "px";
    float_layer.style.top = 0 + "px";

    document.body.appendChild(float_layer);

    globPosition = document.documentElement.scrollTop;
    float_layer.style.top = document.documentElement.scrollTop + "px"; // Mozilla

    float_layer.onmousewheel = chkScroll;
    window.onscroll = chkScroll;
    globScrollTimer = setTimeout('chkScroll',10);

    return float_layer;

}

function updateFigureTitle(float_layer)
{

    var caption = document.createElement("h3");
    caption.id = "slide_title";
    caption.style.position = "absolute";
    caption.style.top = (h_offset_for_centre + padding) + "px";
    caption.style.left = (w_offset_for_centre + padding) + "px";
    // counted close button width as 30
    caption.style.width = (globW - 2*w_offset_for_centre - 2*padding - 30) + "px";
    caption.style.textAlign = "center";
    if (globSlidesArray.length > 1)
    {
        caption.innerHTML += "Slide " + (globSlideNumber+1) + " of " + globSlidesArray.length;
        if (globTitlesArray[globSlideNumber] != '')
        {
            caption.innerHTML += ": ";
        }
    }
    caption.innerHTML += globTitlesArray[globSlideNumber];

    // remove the title if one already exists
    if (document.getElementById(caption.id))
    {
        float_layer.removeChild(document.getElementById(caption.id));
    }
    
    // append title
    float_layer.appendChild(caption);
    
}

function zoomTransparency(float_layer, iteration, call_me_when_done)
{
   
    if (iteration == 1)
    {
        var transparent_bg = document.createElement("img");
        transparent_bg.setAttribute("src","/images/premier/whitepixel.gif")
//        transparent_bg.setAttribute("src","/images/premier/transpixel.png");
        transparent_bg.id = "SSTransparency";
        transparent_bg.style.border = "1px black solid";
        transparent_bg.style.position = "absolute";
        transparent_bg.style.top = (((globH / globRelSize) - globH) / 2) + "px";
        transparent_bg.style.left = (((globW / globRelSize) - globW) / 2) + "px";
        float_layer.appendChild(transparent_bg);
    }

    // remove the close, next, previous buttons
    var trans = document.getElementById("SSTransparency");
    trans.height = globH * (1/globZoomIterations) * iteration;
    trans.width = globW * (1/globZoomIterations) * iteration;
    
    if (iteration < globZoomIterations)
    {
        setTimeout(function () {zoomTransparency(float_layer, iteration+1, call_me_when_done); return false;}, globZoomTimerInterval);
    }
    else
    {
        call_me_when_done();
    }
   
}

function insertButtons(float_layer, explanation_prefix)
{

    // generic buttons - note the onclick has to be set in doSlideShow to get the slide count correct
    var close = document.createElement("img");
    close.setAttribute("src","/images/premier/close.png");
    close.setAttribute("height", 30);
    close.setAttribute("width", 30);
    close.setAttribute("alt","close slideshow");
    close.setAttribute("title","close slideshow");
    close.onclick = closeSlideShow;
    close.id = "SSCloseButton";
    close.style.zIndex = 10;
    close.style.display = "block";
    float_layer.appendChild(close);

    var prev = document.createElement("img");
    prev.setAttribute("src","/images/premier/prev.png");
    prev.setAttribute("height", 40);
    prev.setAttribute("width", 40);
    prev.setAttribute("alt","previous slide");
    prev.setAttribute("title","previous slide");
    prev.id = "SSPrevButton";
    prev.style.display = "none";
    prev.onclick = 
       function () { 
            if (globSlideNumber > 0) 
            {
                globSlideNumber--;
                doSlideShow(explanation_prefix); 
                setNextPrev();
                updateFigureTitle(float_layer);
            }
            return false;
       };    
    prev.style.zIndex = 10;
    float_layer.appendChild(prev);        

    var next = document.createElement("img");
    next.setAttribute("src","/images/premier/next.png");
    next.setAttribute("height", 40);
    next.setAttribute("width", 40);
    next.setAttribute("alt","next slide");
    next.setAttribute("title","next slide");
    next.id = "SSNextButton";
    next.style.display = "none";
    next.onclick = 
       function () { 
            if (globSlideNumber+1 < globSlidesArray.length) 
            {
                globSlideNumber++;
                doSlideShow(explanation_prefix);
                setNextPrev();
                updateFigureTitle(float_layer);
            }
            return false;
       };
    next.style.zIndex = 10;
    float_layer.appendChild(next);
    
    setNextPrev();
    positionButtons(float_layer);

    var loading_img = document.createElement("img");
    var loading_width= 400;
    var loading_height= 60;
    loading_img.setAttribute("src","/images/oxygen/loading-wait.gif");
    loading_img.setAttribute("height",loading_height);
    loading_img.setAttribute("width",loading_width);
    loading_img.setAttribute("alt","Please wait, loading image...");
    loading_img.setAttribute("title","Please wait, loading image...");
    loading_img.id = "LoadingImage";
    loading_img.style.display = "block";
    loading_img.style.position = "absolute";
    loading_img.style.left = ((globW - loading_width) / 2) + "px";
    loading_img.style.top = ((globH - loading_height) / 2) + "px";
    float_layer.appendChild(loading_img);
  
}

function doSlideShow(explanation_prefix)
{

    var h = globH;
    var w = globW;

    var float_layer = document.getElementById('imgfloatlayer');
    
    var actual_img = document.createElement("img");
    actual_img.style.position = "absolute";
    actual_img.onclick = function () { 
            if (globSlideNumber+1 < globSlidesArray.length) 
            {
                globSlideNumber++;
                doSlideShow(explanation_prefix);
                setNextPrev();
                updateFigureTitle(float_layer);
            }
            else
            {
                closeSlideShow();
            }
            return false;
        };
    actual_img.id = "slide_image";
    var title_height = 0;
    if (document.getElementById("slide_title"))
    {
        title_height = document.getElementById("slide_title").offsetHeight;
    }
    else if (document.layers["slide_title"])
    {
        title_height = document.layers["slide_title"].clip.height;
    }

    actual_img.style.top= (h_offset_for_centre + 3*padding + title_height) + "px";
    actual_img.style.display = "none";
    var existing_img = document.getElementById(actual_img.id);
    if (existing_img) {
        float_layer.removeChild(existing_img);
    }
    float_layer.appendChild(actual_img);

    var explanationHeight=0;
    var explanation = document.createElement("div");
    explanation.id = "slide_explanation";
    var explanation_id=explanation_prefix+globSlideNumber;
    if (document.getElementById(explanation_id))
    {
        explanation.innerHTML=document.getElementById(explanation_id).innerHTML;
        explanationHeight = 20 + Math.round(180 *  explanation.innerHTML.length / w);
    }
    
    explanation.style.position = "absolute";
    explanation.style.top = (h_offset_for_centre + h - explanationHeight) + "px";
    explanation.style.left = (w_offset_for_centre + 50) + "px";
    explanation.style.right = "100px";
    explanation.style.width = (w - 150) + "px";
    var existing_explanation = document.getElementById(explanation.id);
    if (existing_explanation) {
        float_layer.removeChild(existing_explanation);
    }
    float_layer.appendChild(explanation);

    var real_height = 0;
    if (document.getElementById(explanation.id))
    {
        real_height = document.getElementById(explanation.id).offsetHeight;
    }
    else if (document.layers[explanation.id])
    {
        real_height = document.layers[explanation.id].clip.height;
    }

    var prev_id = "SSPrevButton";
    var next_id = "SSNextButton";
    var button_height = 0;

    if (document.getElementById(prev_id))
    {
        button_height = document.getElementById(prev_id).height;
    }
    else if (document.layers[prev_id])
    {
        button_height = document.layers[prev_id].clip.height;
    }
    else if (document.getElementById(next_id))
    {
        button_height = document.getElementById(next_id).height;
    }
    else if (document.layers[next_id])
    {
        button_height = document.layers[next_id].clip.height;
    }

    if (button_height>real_height)
    {
        real_height = button_height;
    }

    // Adjust positioning if real height is greater than allowed for
    if (explanationHeight<real_height)
    {
        explanationHeight = real_height;
        document.getElementById(explanation.id).style.top = (h_offset_for_centre + h - explanationHeight) + "px";
        
    }

    // now we can actually set the src of the image because we know roughly how big the explanation is!
    var max_available_height = Math.round(h*slideImageRelSize - explanationHeight - title_height);
    actual_img.onload = function () { centreImage(actual_img.id, globW, max_available_height); actual_img.style.display = "block"; return false; };
    actual_img.src = globSlidesArray[globSlideNumber] + "&width=" + Math.round(w*slideImageRelSize) + "&height=" + max_available_height + "&bgcolour=ffffff";

    // update current graph on main page
    globInlineSlideShow_callback(globSlideNumber);
   
}

function refreshSlide()
{

    calculateHW();

    var float_layer = document.getElementById("imgfloatlayer");
    positionButtons(float_layer);
    updateFigureTitle(float_layer);    

    var explanationHeight=0;
    var explanation = document.getElementById("slide_explanation");
    if (explanation)
    {
        explanationHeight = 20 + Math.round(180 *  explanation.innerHTML.length / globW);
        explanation.style.position = "absolute";
        explanation.style.top = (globH - explanationHeight) + "px";
        explanation.style.left = "50px";
        explanation.style.right = "100px";
        explanation.style.width = (globW - 150) + "px";
    }

    var real_height = 0;
    if (document.getElementById(explanation.id))
    {
        real_height = document.getElementById(explanation.id).offsetHeight;
    }
    else if (document.layers[explanation.id])
    {
        real_height = document.layers[explanation.id].clip.height;
    }

    // Adjust positioning if real height is greater than allowed for
    if (explanationHeight<real_height)
    {
        explanationHeight = real_height;
        document.getElementById(explanation.id).style.top = (h_offset_for_centre + globH - explanationHeight) + "px";
    }

    var slide_image = document.getElementById("slide_image");
    if (slide_image)
    {
        var re = /(&width=[0-9]*)|(&height=[0-9]*)/gi
        var new_src = slide_image.src.replace(re, "");
        var max_available_height = Math.round(globH*slideImageRelSize - explanationHeight);
        new_src += "&width=" + Math.round(globW*slideImageRelSize) + "&height=" + max_available_height;
        slide_image.onload = function () { centreImage(slide_image.id, globW, max_available_height); return false; };
        slide_image.src = new_src;
    }
    
}

function setNextPrev()
{
    var prev = document.getElementById("SSPrevButton");
    if (prev)
    {
        if (globSlideNumber > 0)
            prev.style.display = "block";
        else
            prev.style.display = "none";
    }

    var next = document.getElementById("SSNextButton");
    if (next)
    {
        if (globSlideNumber+1 < globSlidesArray.length)
            next.style.display = "block";
        else
            next.style.display = "none";
    }
    
}

function positionButtons(float_layer)
{
    // remove the close, next, previous buttons
    var trans  = document.getElementById("SSTransparency");
    var prev   = document.getElementById("SSPrevButton");
    var next   = document.getElementById("SSNextButton");
    var close  = document.getElementById("SSCloseButton");
    var loader = document.getElementById("LoadingImage");
    
    if (trans)
    {
        trans.style.position = "absolute";
        trans.style.top = h_offset_for_centre + "px";
        trans.style.left = w_offset_for_centre + "px";
        trans.height = globH;
        trans.width = globW;
    }
    
    if (next)
    {
        next.style.position = "absolute";
        next.style.top = (h_offset_for_centre + globH - 40 - padding) + "px";
        next.style.left = (w_offset_for_centre + globW - 40 - padding) + "px";
    }
    
    if (prev)
    {
        prev.style.position = "absolute";
        prev.style.top = (h_offset_for_centre + globH - 40 - padding) + "px";
        prev.style.left = (w_offset_for_centre + globW - 80 - 2*padding) + "px";
    }
    
    if (close)
    {
        close.style.position = "absolute";
        close.style.top = (h_offset_for_centre + 4) + "px";
        close.style.left = (w_offset_for_centre + globW - 4 - close.width) + "px";    
    }

    if (loader)
    {
        loader.style.left = ((globW - loader.width)  / 2) + "px";
        loader.style.top  = ((globH - loader.height) / 2) + "px";
    }
}


function centreImage(id, screenWidth, availableHeight)
{
    var img = document.getElementById(id);
    if (img)
    {
        img.style.display = "block";
        img.style.position = "absolute";
        img.style.left = ((screenWidth - img.width) / 2) + "px";
        //img.style.top = 50 + (h_offset_for_centre + availableHeight  - img.height) / 2;
    }
}

function closeSlideShow()
{

    window.onscroll = null;
    window.onresize = null;
    clearTimeout(globScrollTimer);
    
    var float_layer = document.getElementById('imgfloatlayer');
    if (float_layer)
    {
        for (var idx=0; idx < float_layer.childNodes.length; idx++)
        {
            if (float_layer.childNodes[idx].id != "SSTransparency")
                float_layer.childNodes[idx].style.display = "none";
        }
        float_layer.onmousewheel = null;
        var transparency = document.getElementById("SSTransparency")
        if (transparency) {
            zoomOut(transparency, 
                    1, 
                    transparency.height/globZoomIterations, 
                    transparency.width/globZoomIterations, 
                    function () { document.body.removeChild(float_layer); }
                  );
        }
    }

}

function zoomOut(transparency, iteration, height_decrement, width_decrement, call_me_when_done)
{
    if (iteration < globZoomIterations)
    {
        transparency.height -= height_decrement;
        transparency.width -= width_decrement;
        setTimeout(function () { zoomOut(transparency, 
                                                 iteration+1, 
                                                 height_decrement, 
                                                 width_decrement, 
                                                 call_me_when_done);
                               },
                   globZoomTimerInterval);
    }
    else
    {
        call_me_when_done();
    }
}

function chkScroll()
{
    if (document.documentElement.scrollTop!= globPosition) 
    {
        /*fix for bug in firefox. When scrollbar is at the bottom, the overlay is automatically closed. 
        The below code make sure that the onScroll event is disregarded immediately after the overlay
        has been setup*/
        var date1 = new Date();
        if(date1.getTime()-initTime<400)
            return;

        closeSlideShow();
    }
    else
    {
        globScrollTimer = setTimeout('chkScroll',500);
    }
}

function swapLoadingImageForReal(tempID, elementID)
{
    if (document.getElementById(tempID))
    {
        document.getElementById(elementID).setAttribute('src', document.getElementById(tempID).getAttribute('src'));
        document.getElementById(tempID).parentNode.removeChild(document.getElementById(tempID));
    }
    var loading_img = document.getElementById("LoadingImage")
    if (loading_img)
    {
        loading_img.style.display = "none";
    }
}

function showSlide(elementID,explanation_prefix,numbering_element,srcs_array,titles_array,slide_number)
{
    var loadingImageURL = "/images/oxygen/loading-wait.gif";
    var loading_img = document.getElementById("LoadingImage")
    if (loading_img)
    {
        loading_img.style.display = "block";
    }
    
    var new_img = document.createElement("img");
    new_img.style.display = "none";
    new_img.id = uniqCtr++;
    new_img.onload = function() { swapLoadingImageForReal(new_img.id, elementID); };
    new_img.setAttribute('src',srcs_array[slide_number] + '&maxWidth=602');
    
    document.getElementById(elementID).parentNode.appendChild(new_img);
    
    document.getElementById(elementID).setAttribute('src', loadingImageURL);
    setTimeout( function() {swapLoadingImageForReal(new_img.id, elementID); }, 30000);

    if(new_img.complete)
        swapLoadingImageForReal(new_img.id, elementID);

    var explanation_id=explanation_prefix+slide_number;

    if (document.getElementById(explanation_prefix)
        && document.getElementById(explanation_id))
    {
        document.getElementById(explanation_prefix).innerHTML=document.getElementById(explanation_id).innerHTML;
    }

    if (document.getElementById(numbering_element) && srcs_array.length>1)
    {
        document.getElementById(numbering_element).innerHTML="Slide " + (slide_number+1) + " of " + srcs_array.length + ": " + titles_array[slide_number];
    }
}

