/**
 * show/hide loupe
 * These functions are triggered by event observers in the controller.js file
 *
 * @see js/controller.js                            (where the "e_loupe" class is observed)
 * @see app_ib/lib_image_list_controller.inc.php    (where the "e_loupe" class is applied)
 *
 * @date 13 Aug 2008
 * @author dePage
 */

function showLoupe() {

    // figure out the ID of the file we are targeting
    var imgID = cntrlr.id;
    var aftID = imgID.replace('imageThumb_', '');
    var puID = 'loupe_'+aftID;  // "pu" = PopUp (in case you were wondering)
    
    // if this is filetype 4 do not show anything, save some CPU cycles
    if (loupe['img_'+aftID].ShowThumb == 0) return;
    
    // create the popup div if it doesn't exist
    if (! $(puID)) createLoupe(aftID);

    // since the user may scroll the page or resize their browser, recalc the location of the loupe each time
    
    // viewport dimensions & position
    var vpDims = document.viewport.getDimensions();
    var vpPos = document.viewport.getScrollOffsets();
    
    // popup dimensions (of the image or flash obj)
    var puDims = $(puID).getDimensions();
    
    // set the offsets for positioning (includes additional spacing and viewport offsetting)
    var offset = [];
    offset['x'] = vpPos['left'] + 10;
    offset['y'] = vpPos['top'] - 10;
    
    // get the dimensions of the thumbnail
    var thmbPos = $(imgID).viewportOffset();
    var thmbDim = $(imgID).getDimensions();
    
    // determine if there is space to the right or left of the thumbnail for the mediumThumb popup (in this order, default to left)
    if ((thmbPos[0]+thmbDim['width']+puDims['width']+offset['x']) <= vpDims['width']) puDims['x'] = thmbPos[0]+thmbDim['width']+offset['x'];
    else puDims['x'] = thmbPos[0]-puDims['width']-offset['x'];

    // determine if there is space below or above the thumbnail for the mediumThumb popup (in this order) but don't set it above the viewport
    if ((thmbPos[1]+puDims['height']) <= vpDims['height']) puDims['y'] = thmbPos[1]+offset['y']
    else puDims['y'] = offset['y']+vpDims['height']-puDims['height'];
    if (puDims['y'] <= vpPos['top']) puDims['y'] = vpPos['top'] + 5;
    
    // position & show the loupe
    if ($(puID)) {
        $(puID).style.left = puDims['x']+'px';
        $(puID).style.top = puDims['y']+'px';
        $(puID).show();
    }
}

function createLoupe(aftID) {

    // create a template that will be populated by the "loupe" inline JSON
    var tmpl = '';
    
    // note: we need the width on this element or IE6 & IE7 mess-up the loupe display
    tmpl += '<div id="loupe_#{FileID}" class="loupe" style="display:none; width:#{DimX}px">';

        // show the flash player or image as req'd
        if (loupe['img_'+aftID].AFT == 8) {
            if( loupe['img_'+aftID].Aspect==169)
            {
            tmpl += '<object width="#{DimX}" height="#{VidHt}" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0">';
                tmpl += '<param name="movie" value="new-loupe-hd.swf?videoLocation=#{ImgSRC}&ratio=#{Aspect}">';
                tmpl += '<param name="quality" value="best">';
                tmpl += '<param name="loop" value="true">';
                tmpl += '<param name="wmode" value="transparent">';
                tmpl += '<param name="FlashVars" value="videoLocation=#{ImgSRC}&ratio=#{Aspect}">';
                tmpl += '<EMBED SRC="new-loupe-hd.swf" LOOP="true" QUALITY="best" FlashVars="videoLocation=#{ImgSRC}&ratio=#{Aspect}" WIDTH="#{DimX}" HEIGHT="#{VidHt}" wmode="transparent">';
            tmpl += '</object>';
            } else {
            tmpl += '<object width="#{DimX}" height="#{VidHt}" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0">';
                tmpl += '<param name="movie" value="new-loupe.swf?videoLocation=#{ImgSRC}&ratio=#{Aspect}">';
                tmpl += '<param name="quality" value="best">';
                tmpl += '<param name="loop" value="true">';
                tmpl += '<param name="wmode" value="transparent">';
                tmpl += '<param name="FlashVars" value="videoLocation=#{ImgSRC}&ratio=#{Aspect}">';
                tmpl += '<EMBED SRC="new-loupe.swf" LOOP="true" QUALITY="best" FlashVars="videoLocation=#{ImgSRC}&ratio=#{Aspect}" WIDTH="#{DimX}" HEIGHT="#{VidHt}" wmode="transparent">';
            tmpl += '</object>';
            }
        } else if (loupe['img_'+aftID].isAudio) {
            tmpl += loupe['img_'+aftID].audioFlashCode;
        } else {
            tmpl += '<img src="' + $('imageThumb_' + aftID).src + '" style="width:#{DimX}px; height:#{DimY}px" alt="" />';
            tmpl += '<img src="#{ImgSRC}" style="width:#{DimX}px; height:#{DimY}px;margin-left:-#{DimX}px; margin-top:-#{DimY}px" alt="" />';
        }
        
        // title - give a fixed width for display purposes (due to the .trnct class images cannot go in here)
        tmpl += '<p class="b wht trnct" style="padding-top:10px; font-size:12px; width:#{DimX}px">#{Title}</p>';

        // description - give a fixed width for display purposes
        if (loupe['img_'+aftID].Descr) tmpl += '<p style="font-size:11px; width:#{DimX}px; padding:2px 0">'+loupe['img_'+aftID].Descr+'</p>';
        
        // figure out how many cameras to show
        var fullCameras = parseInt(loupe['img_'+aftID].RatingsAverage);
        var halfCameras = loupe['img_'+aftID].RatingsAverage - fullCameras;
        var cameras = '';
        for (i=0; i<fullCameras; ++i) cameras += '<img src="/images/w_camera1.png" alt="" class="loupeCamera btm" />';
        if (halfCameras > 0) cameras += '<img src="/images/w_camera05.png" alt="" class="loupeCamera btm" />';
        for (i=Math.ceil(fullCameras+halfCameras); i<5; ++i) cameras += '<img src="/images/w_camera0.png" alt="" class="loupeCamera btm" />';
        
        // show rating & loupe icon        
        if(loupe['img_'+aftID].fileExclusivityText) {
            tmpl +='<img height="12" width="12" class="icons #{fileExclusivityText}Exclusive fr" src="/images/blank.gif"/>';
        }
        tmpl += '<p style="font-size:11px; width:#{DimX}px" class="btm">Rating: '+cameras+' (#{RatingsNumber} reviews)</p>';

    tmpl += '</div>';

    // populate the template (from page inline JSON), insert it after content area
    var loupeTemplate = new Template(tmpl);
    var html = loupeTemplate.evaluate(loupe['img_'+aftID]);
    $('contentArea').insert({bottom:html});
    
    // add the medium size thumb to the Google Gears file store
    if (window.publicFilestore) {
        publicFilestore.storeSingleFile(loupe['img_'+aftID].ImgSRC);
    }

}

function hideLoupe() {
    var loupeID = cntrlr.id.replace('imageThumb_', 'loupe_');
    var aftID   = cntrlr.id.replace('imageThumb_', '');
    
    if ($(loupeID)) {        
        //if the file is audio or video, we need to remove the div, because in IE it keeps playing the audio if we just hide the file
        if (loupe['img_'+aftID].isAudio || loupe['img_'+aftID].AFT == 8) {
            $(loupeID).remove();
        } else {
            $(loupeID).hide();
        }
    }
}


 
 /**
 * autofill search results page
 * the search results page tries to pad the table layout with extra images from the next page, this may change if browser is resized
 *
 * @see app_ib/lib_image_table_display.inc.php
 *
 * @date 2005 or 2006
 * @author Joe Jui
 *
 * @date 26 Jan 209
 * @author dePage - modified code to use Prototype, observers and inline JSON vs. a script mixed in with the PHP
 */

document.observe("dom:loaded", function() {
    showPreviewOfNextPage();
    
    Event.observe(window, 'resize', showPreviewOfNextPage);
});

function showPreviewOfNextPage() {

    // if info is missing, exit the function (this may happen if this file is requested for pages that don't show thumbs)
    if (typeof fillNfo == "undefined") {
        Event.stopObserving(window, 'resize', showPreviewOfNextPage);
        return;
    }
    
    // ensure required items on this page exist
    if (! $('nxtPg')) return;
    if (! $('imageTableDisplayPreviewItem_1')) return;
    
    // get the widths required to figure out how many extra images to show
    clientWidth = (document.viewport.getDimensions()['width'] - $('mainSearch').cumulativeOffset()['left'])-10;
    imageWidth = $('imageTableDisplayPreviewItem_1').previous().offsetWidth;
    imageHeight = $('imageTableDisplayPreviewItem_1').previous().getHeight();
    
    // do something about IE's miscalculations
    if (Prototype.Browser.IE) {
        clientWidth += 10;
    }
    
    var columns=Math.floor(clientWidth/imageWidth);
    
    // require a min of 6 cols wide
    if (columns < 6) columns = 6;
    
    // figure out how many images are needed to display properly
    var rows=Math.ceil(fillNfo.itemsPerPg/columns);
    var previewItems = (rows*columns) - fillNfo.itemsPerPg;
    
    // show all approriate items
    for(var i=1; i<=previewItems; i++){
        if($('imageTableDisplayPreviewItem_'+i)) {
            $('imageTableDisplayPreviewItem_'+i).show();
        }
    }
    
    // hide all non-required previews
    for(var i=previewItems+1; i<=fillNfo.qty; i++) {
        if($('imageTableDisplayPreviewItem_'+i)) {
            $('imageTableDisplayPreviewItem_'+i).hide();
        }
    }
    
    // we also need to appropriately position the Next page arrow & text
    $('nxtPg').hide();

    // determine the offset & size from browser top/left of the first preview item (subtract 4px from top, +5 to left for arrow positioning)
    var offset = $('imageTableDisplayPreviewItem_1').positionedOffset();
    offset['top'] += imageHeight - 4;
    offset['left'] += 5;

    // position the Next Page div per calculations above
    $('nxtPg').setStyle({
        position:'absolute',
        left:offset['left']+'px',
        top:offset['top']+'px'
    });
    
    // only show the "Next page" icon if there is at least 1 visible preview cell
    if ($('imageTableDisplayPreviewItem_1').visible()) $('nxtPg').show();
}
