#!/usr/bin/env kjscmd

//
// Script to create an image gallery for a set of images.
//

var default_title = 'Image Gallery';
var default_intro =   'Here are some images, the larger ones have been scaled down to '
                    + 'ensure this page loads quickly. Click on an image or filename '
                    + 'to see it full size.';
var default_width = 250;
var default_height = 160;

function write_header( title, intro )
{
    println( '<html>' );
    println( '<head>' );
    println( '<title>'+title+'</title>' );
    println( '</head>' );
    println( '<body>' );
    println( '<h1 align="center">'+title+'</h1>' );
    println( '<hr>' );
    println( '<p>'+intro+'</p>' );
    println( '<table border=0 width="90%" cellpadding="12" cellspacing="1">' );
}

function write_footer()
{
    println( '</table>' );
    println( '</body></html>' );
}

function write_image( name, w, h, thumb, tw, th, desc )
{
    println( '<tr>' );

    print( '<td align="center">' );
    print( '<a href="'+name+'">' );
    print( '<img border=0 width='+tw+' height='+th+' src="'+thumb+'">' );
    print( '</a>' );
    println( '</td>' );

    print( '<td width="60%" valign="top" align="justify">' );
    print( '<b><a href="'+name+'">'+name+'</a></b>'+' ('+w+'x'+h+')' );
//    println( '<hr>' );
    println( '<p>'+desc+'</p>' );
    println( '</td>' );

    println( '</tr>' );
}

// Create a thumbnail and write the img tag.
function process_image( name, desc )
{
    var img = new Image();
    img.load( name );
    if ( !img.isOk() ) {
	warn( 'Failed to load image '+name);
	return null;
    }

    var w = img.width();
    var h = img.height();

    if ( (w > default_width) || (h > default_height) ) {
	img.smoothScaleMin( default_width, default_height );
    }

    var tw = img.width();
    var th = img.height();

    var thumb = 'thumb-'+name;
    img.save( thumb );

    if ( !img.isOk() ) {
	warn( 'Failed to save thumbnail '+thumb);
	return null;
    }

    write_image( name, w, h, thumb, tw, th, desc );
}

if ( application.args.length == 0 ) {
    System.stderr.println( 'Usage:' );
    System.stderr.println( '\timagegallery imgfile ...' );
}
else {
    write_header( default_title, default_intro );

    for ( var i = 0 ; i < application.args.length ; i++ ) {
	var name = application.args[i];
	if ( name.match( /^thumb-/ ) ) {
	    // Ignore thumbnails
	}
	else {

	    var desc_file = name.replace( /\.[^\.]+$/, '.htm' );
	    var desc;
	    try {
		desc = System.readFile( desc_file );
	    }
            catch(x) {
		desc = '<i>No Description</i>';
            }
	    process_image( name, desc );
	}
    }

    write_footer();
}



