// Copyright © 2006, Robert Kieffer
// 
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License.  You may obtain a copy
// of the License at
// 
// http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
// License for the specific language governing permissions and limitations
// under the License.
//
// For further information, please contact the author at robert(at)broofa.com


/**
 * Thumber supports automatically opening full-size versions of images based on
 * the presence of a thumbnail image in a document.  This eliminates the need
 * to constantly wrap images inside link tags.
 */

function Thumber() {}

/**
 * The patterns we look for when transforming thumbnail URLs into full-size
 * image urls.  The re(gular expression) is replaced with the substitution.
 *
 * Each entry in this array maps the arguments used by the javascript
 * String.replace() call.  For your example, you might want to add an entry to
 * the array that looks like this:
 * {re: /image-(\d+)a.jpg/, sub:'image-$1b.jpg'}
 *
 * This adds a rule that says anywhere an image url contains "image-[one or
 * more numeric digits]a.jpg", replace that with "image-[whatever digits
 * matched]b.jpg" to get the thumbnail path.
 */

Thumber.patterns = [
  
    {re: /(\d+)a.(jpg)/, sub:'$1b.jpg'}
];

/** The css class assigned to images in their default(initial) state */
Thumber.CLASS_DEFAULT = 'thumber-small';
/** The css class assigned to images in their active(expanded) state */
Thumber.CLASS_ACTIVE = 'thumber-large';
/** The css class to look for when identifying the container element of a thumb image  */
Thumber.PARENT_CLASS = 'film';
/** The css class to assign the container of default thumb images*/
Thumber.PARENT_CLASS_DEFAULT = 'film-small';
/** The css class to assign the container of active thumb images*/
Thumber.PARENT_CLASS_ACTIVE = 'film-large';



/**
 * Configure event handlers on all images that look like thumbnails
 */

Thumber.init = function() {
    // Loop through all images
    var imgs = document.getElementsByTagName('img');
    for (var i = 0; i < imgs.length; i++) {
        var img = imgs[i];

        // Loop through all patterns
        for (var j = 0; j < Thumber.patterns.length; j++) {
            var p = Thumber.patterns[j];

            // If the image matches a pattern ...
            if (img.src && p.re.test(img.src)) {
                // Gather interesting information about the image
                var info = Thumber.getInfo(img);
                info.origURL = img.src;
                info.newURL = img.src.replace(p.re,p.sub);
                info.title = img.title;
                info.width = img.width;
                info.height = img.height;

                Thumber.setClassname(img, false);
                img.onclick=Thumber.handleImage;
                img.onmouseover=Thumber.handleImage;
                img.onmouseout=Thumber.handleImage;
                img.title = img.title ? img.title + ' (Click to zoom)' : 'Click to zoom';
                break;
            }
        }
    }
}

/**
 * Set the CSS classname of an image
 */

Thumber.setClassname = function(el, active) {
    if (!Thumber._cnRE) {
        Thumber._cnRE = new RegExp('(' + Thumber.CLASS_DEFAULT+ '|' + Thumber.CLASS_ACTIVE + ')');
        Thumber._pcnRE = new RegExp('(' + Thumber.PARENT_CLASS_DEFAULT+ '|' + Thumber.PARENT_CLASS_ACTIVE + ')');
    }
    // Set the class of the image
    Thumber.replaceClassname(el,
        active ? Thumber.CLASS_ACTIVE : Thumber.CLASS_DEFAULT,
        Thumber._cnRE
        );

    // Set the class of any marked container

    do {
        el = el.parentNode;
        if (el
            && el.className
            && el.className.indexOf(Thumber.PARENT_CLASS) >= 0) {
            Thumber.replaceClassname(el,
                active ? Thumber.PARENT_CLASS_ACTIVE : Thumber.PARENT_CLASS_DEFAULT,
                Thumber._pcnRE
                );
            break;
        }
    } while (el);
}

Thumber.replaceClassname = function(el, newClass, oldClass) {
    var cn = el.className || '';
    if (oldClass) {
        cn = cn.replace(oldClass, '');
    }
    cn += ' ' + newClass;
    cn = cn.replace(/\s{2,}/, ' ').replace(/^\s*(.*?)\s*$/, '$1');
    el.className = cn;
}

/**
 * Array of information objects we keep for each image we're handling
 */

Thumber._imageInfo = [];

/**
 * Return an info object that is specific to the provided image
 */

Thumber.getInfo = function(img) {
    if (img._tidx == void 0) {
        img._tidx = Thumber._imageInfo.length;
        Thumber._imageInfo[Thumber._imageInfo.length] = {};
    }
    return Thumber._imageInfo[img._tidx];
}

/**
 * Handle an event on one of the thumbnail images
 */

Thumber.handleImage = function(e) {
    e = e || event;
    var img = e.target || e.srcElement;
    var type = e.type.replace(/^on/, '');
    var info = Thumber.getInfo(img);

    if (type == 'click') {
        // Toggle which URL we're showing
        info.showingNew = !info.showingNew;
        img.src = info.showingNew ? info.newURL : info.origURL;
        Thumber.setClassname(img, info.showingNew);
    } if (type == 'mouseover') {
        status = info.showingNew ? info.origURL : info.newURL;
    } if (type == 'mouseout') {
        status = '';
    }

    try {
        e.preventDefault();
    } catch (e) {
    }

    return false;
}

window.onload = Thumber.init;
