
function easydate() {
    var d = new Date();
    var yy = d.getFullYear();
    var mm = 1 + +(d.getMonth());
    var dd = +d.getDate();

    if (dd<10)
        dd = "0" + dd;
    if (mm<10)
        mm = "0" + mm;
    
    return ("" + yy + "-" + mm + "-" + dd);
}

//
// CataloguePage object - a catalogue page consisting of a table of icons that
// point to other catalogue pages, or catalogue search results pages.
// 
    CataloguePage.prototype.addNode = function (id, node) {
        node.imageElement = $('#catimage_' + node.ordinal);
        this.nodes[id] = node;
    } 

    CataloguePage.prototype.selectMultiImageNodes = function() {
        // first, locate all nodes that have multiple images
        var imageNodes = new Array();
        for (var i=0; i<this.nodes.length; i++)
        {
            var node = this.nodes[i];
            if (node.imageList && (node.imageList.length > 1))
            {
                imageNodes[imageNodes.length] = node;
                node.imageElement.addClass('debugBorder');
                node.imageIndex = 0;
            } 
        } 

        // now, shuffle them.
        var len = imageNodes.length;
        if (len>0)
        {   
            while ( --len ) 
            {
                var j = Math.floor( Math.random() * ( len + 1 ) );
                var t1 = imageNodes[len];
                var t2 = imageNodes[j];
                imageNodes[len] = t2;
                imageNodes[j] = t1;
            }
        }
        
        this.multiImageNodes = imageNodes;
        this.nextNode = 0;
    }

    CataloguePage.prototype.getNextMultiImageNode = function() {
        if (this.nextNode > this.multiImageNodes.length)
        {
            this.nextNode = 0;
        } 
        var n = this.nextNode;
        this.nextNode++;
        return this.multiImageNodes[n];
    } 


    CataloguePage.prototype.getNextImageFromNode = function(node) {
        var images = node.imageList;
        if (images && (images.length>0))
        {
            var n = node.imageIndex ? node.imageIndex : 0;
            if (n >= images.length)
            {
                n=0;
            } 
            node.imageIndex = n+1;

            var filename = images[ n ];
            if (filename.indexOf("/")==0)
                return filename;
            return "/pictures/" + node.category + "/" + filename;
        }  
        return 0;
    } 

    CataloguePage.prototype.fadeImageIn = function() {
        this.activeImage[0].src = this.newImageFile;
        this.activeImage[0].width=100;
        this.activeImage[0].height=100;

        this.activeImage.fadeTo('slow', 1.0);
    } 

    CataloguePage.prototype.changeImage = function(node) {
        var newImage = this.getNextImageFromNode(node);
        if (!newImage)
            return 0;

        var elem = node.imageElement[0];
        if (!elem)
            return 0;

        if (this.imageInUse(newImage))
        {
            return 0;
        } 
        var self = this;
        this.activeImage = node.imageElement;
        this.newImageFile = newImage;
        this.activeImage.fadeTo('slow', .40, function() { self.fadeImageIn() } );
    }

    CataloguePage.prototype.imageInUse = function(imagePath) {
        var txt = '';
        for (var i=0; i<this.allImages.length; i++)
        {
            var src = this.allImages[i].src;
            if (src.indexOf("://") > 0)
            {
                var split = src.indexOf("/", 12);
                src = src.substring(split);
            } 
            if (src==imagePath)
                return true;
        }
        return false;
    } 

    CataloguePage.prototype.doTimer = function () {
        var node = this.getNextMultiImageNode();
        if (node)
            this.changeImage(node);
        this.startTimer();
    } 

    CataloguePage.prototype.startTimer = function () {
        var me = this;
        window.setTimeout( function() { me.doTimer() }, 1000 )
    } 

    function CataloguePage() {
        this.nodes = new Array();
        this.multiImageNodes = null;
        this.nextNode = 0;
        this.nodes[0] = { ordinal: 0, category: '', imageList: [] }
        this.allImages = $('.cat_img');
    } 
// end catalogue-page.js

var allFormObjects = new Array();

function findFormObject(id, noisy) {
    var rv = allFormObjects[id];
    if (rv) 
        return rv;
    
    var f = document.getElementById(id);
    if (f && f.oolFormObject)
         return f.oolFormObject;
   
    if (noisy)
        alert("Cannot find form object: " + id);    

    return rv;
}

FormObject.prototype.getMasterDocument = function(noisy) {
    var mm = this.getMaster(noisy);
    return mm ? mm.document : null;
}

// return master window.
FormObject.prototype.getMaster = function(noisy) {
    if (! this.master)
    {
        if (window.opener && window.opener.document)
            this.master = window.opener;
        else if (window.parent && window.parent.document)
            this.master = window.parent;
        else if (noisy)
            alert("cannot determine master document");
    }
    return this.master;
}

// return a jquery object.
FormObject.prototype.getMasterField = function(id, noisy) {
    var m = this.getMaster();
  
    // m.$ means to call the jquery instance in the parent doc - if one exists. 
    var outfield = m.$ ? m.$('#'+id) : $(m.document).find('#' + id);
    if (outfield && outfield[0])
        return outfield;

    outfield = m.find('input[name='+id+']');
    if (outfield && outfield[0])
        return outfield;

    if (noisy)
    {
        alert("cannot find " + id + " in master document " + m[0].location); 
    } 
    return null;
}

// putIntoMaster (target-field-id, value, [ noisy:false ])
FormObject.prototype.putIntoMaster = function(id, val, noisy) {
    var outfield = this.getMasterField(id, noisy);
    if (outfield && outfield[0])
    {
        outfield[0].value = val;
        outfield.change();  // call event handler in parent doc
        return true;
    } 
    return false;
}

FormObject.prototype.getField = function(fieldname, noisy) {
    var rv = null;
    if (typeof fieldname == "string")
    {
        rv = this.form[0].elements[fieldname];
    } else if (typeof fieldname == "object") {
        rv = fieldname;
    } else {
        alert("getField:unknown type " + (typeof fieldname) + " for form field " + fieldname);
    } 

    if (rv)
	return rv;
    if (noisy)
	alert("cannot find form field " + fieldname);
    return null;
}

FormObject.prototype.getFieldValue = function(fieldname, noisy) {
	var f = this.getField(fieldname,noisy);
	if (f)
		return f.value;
	return undefined;
}

FormObject.prototype.putFieldValue = function(fieldname, newval) {
	var f = this.getField(fieldname, true);
	if (f)
	{
		f.value = newval;
		// don't call onchange as we may get into loops.
		// if (f.onchange) f.onchange();
	}
	return f;
}

FormObject.prototype.handleFocus = function(evt) {
	return this;
}

FormObject.prototype.handleChange = function(evt) {
    var target = evt.target ? evt.target : evt;
    this.markChanged(target);
    return this;
}

FormObject.prototype.handleBlur = function(evt) {
	return this;
}

FormObject.prototype.handleKeyUp = function(evt) {
	return this;
}

FormObject.prototype.handleSubmit = function(evt) {
	return true;
}

FormObject.prototype.dumpForm = function() {
// for debugging.
    for (var i=0; i < f.elements.length; i++)
    {
        var e = f.elements[i];
        if (console)
            console.log(e.name + " is '" + e.value + "'");
    }
	return true;
}

// called when you have a specific group of widgets that need to handleChange() etc.
// ordinarily, though, just call bindEverything, and let the form decide what to bind.
FormObject.prototype.bindWidgets = function(widgets) {
	var me = this;
    widgets.bind(
        'change', function(evt) { me.handleChange(evt) } ).bind(
        'keyup', function(evt) { me.handleKeyUp(evt) } ).bind(
        'blur', function(evt) { me.handleBlur(evt) } ).bind(
        'focus', function(evt) { me.handleFocus(evt) } 
    );
    
    widgets.filter('input[type=radio]').bind(
        'click', function(evt) { me.handleChange(evt) }
    );
    return widgets;
}

FormObject.prototype.bindEverything = function() {
    if (!this.allwidget)
    {
        this.allwidgets = this.form.find('input,select,textarea');
        //this.radios = this.form.find('input[type=radio]');
    }

	var me = this;
    this.bindWidgets(this.allwidgets);
    this.form.bind('submit', function(evt) { return me.handleSubmit(evt); } );

	return this;
}

FormObject.prototype.markChanged = function(f) {
    var field = this.getField(f, false);
    if (field)
    {
        if (field.value==field.defaultValue)
        {
            $(field).removeClass('changed');
            return false;
        } else {
            $(field).addClass('changed');
            return true;
        }
    }
    return void(0);
}

FormObject.prototype.assembleQueryString = function () {
    var elems = this.form[0].elements; 

    var qs = '';
    for (var i=0; i< elems.length; i++)
    {
        var e = elems[i];
        if (e.name)
        {
            qs = qs + e.name + '=' + escape( $(e).val() ) + '&';
        } 
    } 
    return qs;
}

FormObject.prototype.ajaxSubmitCallback = function(tree) {
    if (console)
        console.dir(tree);
    return void(0);
}


FormObject.prototype.ajaxSubmit = function() {
    this.throbber.show('fast');

    var qs = this.assembleQueryString();
    var url = this.form[0].action + '?' + qs;

    var me = this;
    jQuery.get(url, {}, function (xmltree) {
         return me.ajaxSubmitCallback(xmltree);
    });
    return this;
}

FormObject.prototype.setupAjaxSubmit = function(expr) {
    var button = this.form.find(expr);
    var me =this;
    button.bind('click', function() { me.ajaxSubmit(); });
    if (button[0] && button[0].form)
    {
        $(button[0].form).bind('submit', function() { me.ajaxSubmit(); return false;});
    } 

    this.throbber = $('#' + this.formid + '-throbber');
    this.throbber.hide('fast');

    return this;
}

function FormObject()
{
	return this;
}

FormObject.prototype.init = function(formid1) {
    this.formid = formid1;
    this.form = $('#' + formid1);

    allFormObjects[formid1] = this;

    this.allwidgets = this.form.find('input,select,textarea');

	if (!this.form[0])
	{
		alert("Cannot find form " + formid1);
		return this;
	} else {
		this.form.addClass("formObject");
        this.form.oolFormObject = this;
	}
	
	return this;
}


function ImageSwapper (aname)
{
    this.name = aname;
    this.addImage = ImageSwapper_addImage;
    this.addTarget   = ImageSwapper_addTarget;
    this.doRandomImage = ImageSwapper_doRandomImage;
    this.doRandomImageForTarget = ImageSwapper_doRandomImageForTarget;
    this.activateTimer  = ImageSwapper_activateTimer;
    this.timerCallback  = ImageSwapper_timerCallback;

    this.targets = new Array();     // index by name
    this.targetNames = new Array(); // index by number
    this.imageSets = new Array();
    this.targetsIndex = 0;

    return this;
}

function ImageSwapper_timerCallback()
{
    clearTimeout(this.timerID); 
    this.doRandomImage();
    this.activateTimer(this.swappername, this.timeValue);
    return void(0);
}

function ImageSwapper_activateTimer(swappername, t)
{
    this.swappername = swappername;
    this.timeValue = t;
    this.timerID = setTimeout(swappername + ".timerCallback()", t * 1000);
    return void(0);
}

function ImageSwapper_doRandomImage()
{
    var limit = this.targetNames.length;
    var thisTarget = this.targetNames[ Math.floor(Math.random() * limit) ];
    if (thisTarget)
    {
        this.doRandomImageForTarget(thisTarget);
    }
    return void(0);
}

function ImageSwapper_doRandomImageForTarget(targetname)
{
    var listname = this.targets[targetname];
    var theList = this.imageSets[listname];
    if (! theList)
        return 0;

    var filename = theList[ Math.floor(Math.random() * theList.length) ];
    if (! filename)
        return 0;

    var img = document.getElementById(targetname);
    img.src=filename;
    return void(0);
}

function ImageSwapper_addImage(setname, imagepath)
{
    if (! this.imageSets[setname])
    {
        this.imageSets[setname] = new Array();
    } 

    var imgs = this.imageSets[setname];
    imgs[imgs.length] = imagepath;
}

function ImageSwapper_addTarget(targetname, range)
{
    this.targets[targetname] = range;
    this.targetNames[ this.targetNames.length ] = targetname;
}


$(document).ready(function() {
    $("a.big-image").fancybox({'overlayShow': true });
});

