// in-situ image cycler
//
// (c) 2007-02-06 s1webmedia.co.uk - use AT YOUR OWN RISK keeping this notice with all copies.
//
// usage: <img class="img_cycler" src="foo_3_of_5.jpg" />...<div id="foo_ctrl"></div>
// observe naming conventions (no leading zeros) and ensure all image files exist!

var CTRL_LABEL = 'Next Image';
var USE_CACHE  = true;

function init_image_cyclers() {
 var imgs = document.getElementsByTagName('IMG');
 var re = new RegExp('(.*?)([^_/]+)_(\\d+)_of_(\\d+)(\\.\\w{3,4})$');
 for (var i = 0, n = imgs.length; i < n; i++) {
  var img = imgs[i];
  if (img.className != 'img_cycler') continue;
  var m = img.src.match(re);
  if (!m) continue;
  var path = m[1], ctrl_id = m[2], current = m[3] - 1, total = m[4], ext = m[5];
  var ctrl = document.getElementById(ctrl_id + '_ctrl');
  if (!ctrl || total < 2) continue;

  ctrl.cycler = { img:img, current:current, srcs:[], cache:[], cached:false };

  for (var j = 0; j < total; j++) {
   var src = path + ctrl_id + '_' + (1 + j) + '_of_' + total + ext;
   ctrl.cycler.srcs.push(src);
  } // alert([ctrl_id,ctrl.cycler.srcs])
  ctrl.innerHTML = '[ <a href="javascript:void(0);">' + CTRL_LABEL + '</a> ]';
  ctrl.title = '(' + total + ' images)';

  ctrl.onclick = function() {
   var total = this.cycler.srcs.length;
   if (!this.cycler.cached && USE_CACHE) { // cache all when ctrl first clicked
    for (var i = 0; i < total; i++) {
     if (i == this.cycler.current) continue;
     var img = new Image(); img.src = this.cycler.srcs[i]; this.cycler.cache.push(img);
    }
    this.cycler.cached = true; // (-ish)
   }

   if (++this.cycler.current >= total) this.cycler.current = 0;
   this.cycler.img.src = this.cycler.srcs[this.cycler.current];

   return false; // ignore href - ie6 wants this
  };
 }
}

// set external links target
//
// unused: usability issues, esp. w. ie6 prompting
// 'allow sub-frames to navigate across domains?'
// when TARGET set to 'external'

var TARGET = '_blank'; // 'external';

function init_external_links() {

 var local = window.location.host + ':'; // ie6 adds ':80'
 local = local.substring(0, local.indexOf(':'));

 for (var i = 0, n = document.links.length; i < n; i++) {
  var link = document.links[i];

  var remote = link.host + ':'; // ie6 adds ':80'
  remote = remote.substring(0, remote.indexOf(':'));

  if (local == remote) continue; // local link
  if (!remote)         continue; // javascript: link

  link.onclick = function() {
   var w = window.open(this, TARGET);
   w.focus();
   return false;
  };
 }
}

function init() {
 init_image_cyclers();
 //init_external_links(); // don't use!
}

window.addEventListener ? window.addEventListener('load', init, false) : window.attachEvent ? window.attachEvent('onload', init) : null;
