// JavaScript Document
<!-- hide from none JavaScript Browsers

function findTarget(e, nodeName) {
    var target;
    nodeName = nodeName.toLowerCase();

    if (window.event && window.event.srcElement) {
        target = window.event.srcElement;
    } else if (e && e.target) {
        target = e.target;
    }
    if (!target) {
       return null;
    }

    while (target != document.body &&
           target.nodeName.toLowerCase() != nodeName) {
        target = target.parentNode;
    }

    if (target.nodeName.toLowerCase() != nodeName) {
        return null;
    }

    return target;
}

// Cross-browser event handling for IE5+, NS6+ and Mozilla/Gecko 
// By Scott Andrew
function addEvent(elm, evType, fn, useCapture) {
    if (elm.addEventListener) {
        elm.addEventListener(evType, fn, useCapture);
        return true;
    } else if (elm.attachEvent) {
        var r = elm.attachEvent('on' + evType, fn);
        return r;
    } else {
        elm['on' + evType] = fn;
    }
}

function removeEvent( elm, evType, fn )
{
    if (elm.removeEventListener)
	elm.removeEventListener( evType, fn, false );
    else if (elm.detachEvent) {
	elm.detachEvent( "on"+evType, elm[evType+fn] );
	elm[evType+fn] = null;
	elm["e"+evType+fn] = null;
    }
}

function basename(f) {
    return (f.match(/[\/|\\]([^\\\/]+)$/))[1];
}

function removeAllChildNodes(el) {
    if (el.hasChildNodes()) {
        while (el.childNodes.length >= 1) {
            el.removeChild(el.firstChild);
        } 
    }
}

function hCentre(el) {
    var offset = (el.parentNode.clientWidth - el.clientWidth) / 2;
    el.style.position = "relative";
    el.style.left = offset + "px";
}

function PhotoSelector(photolist, current, baseUrl, navContainerId, photoIdPrefix, storePhotoId) {
    this.photolist = photolist;
    this.current = current;
    this.baseUrl = baseUrl;
    this.navContainerId = navContainerId;
    this.photoIdPrefix = photoIdPrefix;
    this.storePhotoId = storePhotoId;

    if (this.current >= this.photolist.length) {
        this.current = this.photolist.length-1;
    } else if (this.current < 0) {
        this.current = 0;
    }
}

PhotoSelector.prototype.findById = function(id) {
    for (var i=0; i<this.photolist.length; ++i) {
        if (id == (this.photoIdPrefix + this.photolist[i].id)) {
            return i;
        }
    }

    return -1;
}

PhotoSelector.prototype.selectMainPhoto = function(id) {
    var index = this.findById(id);
    if ((-1 != index) && (index != this.current)) {
        this.setMainImage(index);
    }
}

PhotoSelector.prototype.changeMainPhoto = function(incr) {
    var index = this.current + incr;
    if (index < 0) {
        index = this.photolist.length-1;
    } else if (index >= this.photolist.length) {
        index = 0;
    }
    
    if (index != this.current) {
        this.setMainImage(index);
    }
}

PhotoSelector.prototype.setMainImage = function(index) {
    this.current = index;
    var selector = this;

    var width = this.photolist[this.current].width;
    var height = this.photolist[this.current].height;
    var name = this.photolist[this.current].name;
    var ref = this.photolist[this.current].reference;

    var newImage = new Image(width, height);
    var swapper = function() {selector.swapMainPhoto(newImage, width, height, name); }

    newImage.loaded = false;
    newImage.disappearing = true;
    newImage.onload = function() { selector.mainLoaded(newImage, swapper); };
    newImage.src = this.baseUrl + this.photolist[this.current].id;

    new Effect.Opacity('main_photo', 
                       {duration:0.5, from:1.0, to:0.0, 
                        afterFinish: function(o) { selector.mainDisappeared(newImage, swapper);} });

    if (("" != this.storePhotoId) && $(this.storePhotoId)) {
        $(this.storePhotoId).value = this.photolist[this.current].id;
    }

    var relm = $('photo_reference');
    if (relm) {
        relm.innerHTML = ref;
    }
}

PhotoSelector.prototype.swapMainPhoto = function(img, width, height, title) {
    var main_photo = document.getElementById('main_photo');
    var cover_photo = document.getElementById('bigphoto');
    main_photo.width = width;
    main_photo.height = height;
    main_photo.alt = title;
    main_photo.src = img.src;
    cover_photo.width = width;
    cover_photo.height = height;
    cover_photo.style.top = "-" + height + "px";
    cover_photo.style.marginBottom = "-" + height + "px";
    hCentre(cover_photo);
    new Effect.Opacity('main_photo', 
                       {duration:0.5, from:0.0, to:1.0});

    // adjust next/prev arrow position
    var photoNav = $(this.navContainerId);
    photoNav.style.top = "-" + (photoNav.clientHeight/2 + height/2)+"px";
}

PhotoSelector.prototype.mainLoaded = function(img, action) {
    img.loaded = true;
    if (!img.disappearing) {
        action();
    }
}

PhotoSelector.prototype.mainDisappeared = function(img, action) {
    img.disappearing= false;
    if (img.loaded) {
        action();
    }
}

PhotoSelector.prototype.setNavVisibility = function(isVisible) {
    var photoNav = $(this.navContainerId);
    if (isVisible) {
        photoNav.style.visibility="visible";
    } else {
        photoNav.style.visibility="hidden";
    }
}

function initClientPhotoPage(photolist, curIndex, mainId, thumbnailContainerId, navContainerId, prevId, nextId, storePhotoId, baseUrl) {
    var mainEl = $(mainId);

    var selector = new PhotoSelector(photolist, curIndex, baseUrl, navContainerId, "photo", storePhotoId);
    mainEl.selector = selector;

    // add select action to all thumbnails
    if ("" != thumbnailContainerId) {
        var containerEl = $(thumbnailContainerId);
        if (containerEl) {
            $A(containerEl.getElementsByTagName("img")).each(
                function(value, index) {
                    if (Element.hasClassName(value, "clickable_thumbnail")) {
                        addEvent(value, "click", 
                                 function() {
                                     selector.selectMainPhoto(value.id);
                                 }
                        );
                    }
                }
            );
        }
    }

    // when the main photo is clicked (actually the transparent image 
    // covering it) then treat that as next also
    addEvent($('bigphoto'), "click", function() { selector.changeMainPhoto(1); });

    // now prev & next buttons
    addEvent($(prevId), "click", function() { selector.changeMainPhoto(-1); });
    addEvent($(prevId), "mouseover", function() { selector.setNavVisibility(true); });
    addEvent($(nextId), "click", function() { selector.changeMainPhoto(1); });
    addEvent($(nextId), "mouseover", function() { selector.setNavVisibility(true); });
    
    // make prev & next buttons only visible when mouse over photo
    addEvent($('main_photo_holder'), "mouseover", function() { selector.setNavVisibility(true); });
    addEvent($('main_photo_holder'), "mouseout", function() { selector.setNavVisibility(false); });

}

// string method functions from 
// http://www.crockford.com/javascript/remedial.html

// entityify() produces a string in which '<', '>', and '&' are replaced with
// their HTML entity equivalents. This is essential for placing arbitrary 
// strings into HTML texts
String.prototype.entityify = function () {
    return this.replace(/&/g, "&amp;").replace(/</g,
        "&lt;").replace(/>/g, "&gt;");
};


// quote() produces a quoted string. This method returns a string that is
// like the original string except that it is wrapped in quotes and all quote
// and backslash characters are preceded with backslash.
String.prototype.quote = function () {
    var c, i, l = this.length, o = '"';
    for (i = 0; i < l; i += 1) {
        c = this.charAt(i);
        if (c >= ' ') {
            if (c === '\\' || c === '"') {
                o += '\\';
            }
            o += c;
        } else {
            switch (c) {
            case '\b':
                o += '\\b';
                break;
            case '\f':
                o += '\\f';
                break;
            case '\n':
                o += '\\n';
                break;
            case '\r':
                o += '\\r';
                break;
            case '\t':
                o += '\\t';
                break;
            default:
                c = c.charCodeAt();
                o += '\\u00' + Math.floor(c / 16).toString(16) +
                    (c % 16).toString(16);
            }
        }
    }
    return o + '"';
};

// supplant() does variable substitution on the string. It scans through the
// string looking for expressions enclosed in { } braces. If an expression is
// found, use it as a key on the object, and if the key has a string value or
// number value, it is substituted for the bracket expression and it repeats.
// This is useful for automatically fixing URLs.
String.prototype.supplant = function (o) {
    return this.replace(/{([^{}]*)}/g,
        function (a, b) {
            var r = o[b];
            return typeof r === 'string' || typeof r === 'number' ? r : a;
        }
    );
};

//The trim() method removes whitespace characters from the beginning and end of the string.
String.prototype.trim = function () {
    return this.replace(/^\s+|\s+$/g, "");
}; 

// - stop hiding -->
