//
// This file contains all the JavaScript code necessary to 
// populate and maintain the active element:
//
//  gallery
//

// function: galleryPopulator
// 'data' node is expected in the following format:
//
// <data>
//   <gallery>
//     <image>
//       <url>url</url>
//       <title>text</title>
//       <height>nn</height>
//       <width>nn</width>
//     </image>
//       ...
//   </gallery>
// <data>
//
// Output is to be generated of the form (repeated once per image):
//
// <div id="gallery-image"><img src="./content/img1.jpg" /><p>title</p></div>


function galleryPopulator( activeElement, data )
{
    // (i) Update active element
    clearText( activeElement );

    var imageNodes = data.getElementsByTagName("image");
    var singleImageHTML;
    var galleryHTML = "";
    var IMGmaxHeight = 125; // maximum height of thumbnailed image
    var IMGmaxWidth = 75;  // maximum width of thumbnailed image
    
    for (i=0; i< imageNodes.length; i++)
    {
        var urlNode = imageNodes[i].getElementsByTagName("url")[0].firstChild.nodeValue;
        var titleNode = imageNodes[i].getElementsByTagName("title")[0].firstChild.nodeValue;
        var height = imageNodes[i].getElementsByTagName("height")[0].firstChild.nodeValue;
        var width = imageNodes[i].getElementsByTagName("width")[0].firstChild.nodeValue;
        var caption = imageNodes[i].getElementsByTagName("caption")[0].firstChild.nodeValue;

        // Need to calculate Thumbnail dimensions so that thumbnail will fit within an IMG tag of IMGmaxHeight X IMGmaxWidth
        // Compare scaling factor for width and height and take smaller factor (greatest reduction) to ensure both dimensions
        // fit.
        
        var heightScale = IMGmaxHeight / height;
        var widthScale = IMGmaxWidth / width;
        
        scale = Math.min(heightScale, widthScale);
        var IMGheight = Math.floor(scale * height + 0.5);
        var IMGwidth = Math.floor(scale * width+ 0.5);
 
        // frig: at the moment, I know the title text contains the name of a file. Remove the last 4 characters
        // (e.g. ".jpg") and use the remaining text.
        // var title = titleNode.substr(0,title.length-4);
        
        singleImageHTML = "<div class=\"gallery-image\">" +
			"<a href=\"../" +
			urlNode + 
                        "\" target=\"+blank\"><img src=\"./architecture/phpthumb/phpThumb.php?w=" + IMGwidth + "&h=" + IMGheight + "&src=/" + 
                        urlNode +
                        "\" alt=\"" + // for IE to display hint text (see http://drupal.org/node/35821)
                        caption + 
                        "\" title=\"" + // for Firefox to display hint text
                        caption + 
                        "\" /></a><p>" +
                        caption + 
                        "</p></div>";
      galleryHTML += singleImageHTML;
    }
    
    activeElement.innerHTML = galleryHTML;
}
