// TODO for v2
//      - Make it loop
//      - Take the image size of all the images and take sizes out of the css  - DONE

Scrollers = { };
var Preloader = null;

function Scroller(images) {
  this.id = 'scroller'; 
  Scrollers[this.id]=this;
  this.name = "Scrollers."+this.id;
  this.images = images;
  this.numImages = this.images.length;  
  this.imageDivs = { };
  this.write_slideshow(this);

  var callback = this.onLoad; //var callback = Scroller.prototype.onLoad; 
  Preloader = new ImagePreloader(this.images, this, callback);
  this.Preloader = Preloader;
}
 
Scroller.prototype.onLoad = function (images, loaded) {
  this.setChildIds();
  this.updateSizes();
  this.updateInfo();
  this.setupEvents();
  //init_tmp();
}

Scroller.prototype.slideElement = function (x,y,inc) {

  elementId = this.id;
  if ((!document.getElementById) || (!document.getElementById(elementId))) 
    return false;
  var element = document.getElementById(elementId);

  if (element.sliding) clearTimeout(element.sliding);

  if (!element.xpos) element.xpos = 0;
  if (!element.ypos) element.ypos = 0;

  if (element.xpos == x && element.ypos == y) {
    element.isSliding = 0;
    this.updateInfo();
    //this.checkSides(); 
    return true;
  }

  if (element.xpos > x) { var dist = Math.ceil((element.xpos-x)/inc); 
                      element.xpos = element.xpos - dist; }
  if (element.xpos < x) { var dist = Math.ceil((x-element.xpos)/inc); 
                      element.xpos = element.xpos + dist; }
  if (element.ypos > y) { var dist = Math.ceil((element.ypos-y)/inc); 
                      element.ypos = element.ypos - dist; }
  if (element.ypos < y) { var dist = Math.ceil((y-element.ypos)/inc); 
                      element.ypos = element.ypos + dist; }

  element.style.left = element.xpos+'px';
  element.style.top  = element.ypos+'px';
  element.sliding = setTimeout(this.name+'.slideElement('+x+','+y+','+inc+')',
                               10);

}

Scroller.prototype.slideLeft  = function() { 
  this.slideRel( this.frameWidth, 0 ); 
}
Scroller.prototype.slideRight = function() { 
  this.slideRel( this.frameWidth * -1, 0); 
}

/* SlideElement takes an absolute X-X coordinate. what we want to do here is:
find out where we currently are calculate where we want to be make sure there
is enough image to move that way slide the element */
Scroller.prototype.slideRel = function (diffx,diffy) {
  elementId = this.id; 
  if (!document.getElementById) return false;
  if (!document.getElementById(elementId)) return false;
  var element = document.getElementById(elementId);

  if (!element.xpos) element.xpos = 0;
  if (!element.ypos) element.ypos = 0;

  var ci = this.currentImage();

  // comment to not stop at ends
  if ((ci == 1 && diffx > 0) || (ci == this.numImages && diffx < 0))  
   return true; 

  // make sure we aren't moving
  if (element.isSliding == 1) return true; 
  element.isSliding = 1;

  // set our new positions
  newx = element.xpos + diffx;
  newy = element.ypos + diffy;

  this.slideElement(newx, newy, 5);
}

Scroller.prototype.currentImage = function() {
  var element = document.getElementById( this.id );
  var w = this.frameWidth;   
  var x = element.xpos ? element.xpos : 0;
  //output_append(" x = " + x + " " + Math.abs(x) + "\n");   
  var n =  (x / w) % this.numImages;
  imageNum = x <= 0 ? n : (this.numImages - n) % 4;
  imageNum = Math.abs(imageNum) + 1;
  return imageNum;
}

Scroller.prototype.setChildIds = function() {
  var scroller = document.getElementById( this.id );
  var j = 1;
  if(scroller.hasChildNodes()) {
    for(i=0; i<scroller.childNodes.length; ++i) {
      if ( scroller.childNodes[i].tagName == "DIV")  {
        scroller.childNodes[i].id = this.id + j;
        this.imageDivs[j] = this.id + j
        //output_append(scroller.childNodes[i].id);
        ++j;
      }
    }
  }
}


Scroller.prototype.setupEvents = function() {
  var window = document.getElementById( "is_window" );   
  window.who = this;
  window.onmouseup = function() {
    var img = document.getElementById(this.who.id+this.who.currentImage()).firstChild;  
    var newsrc = img.src.replace(/medium/, "large");
    PopupPic(newsrc);   
  }
}

//Scroller.prototype.setNumImages = function() 
//{
// var scroller = document.getElementById( this.id );   
// if(scroller.hasChildNodes()) { return find_in(scroller, "DIV"); }
// return 0;
//}

Scroller.prototype.updateInfo = function () {
  var output = "Image " + this.currentImage() +" of " + this.numImages;
  document.getElementById('info').innerHTML = output;   
  this.updateButtons();
}

Scroller.prototype.updateButtons = function () {
  // if current image is 1 or lastImage than grey out the corresponding button  
  if(this.currentImage() == 1)  
    document.getElementById('is_prev').className = "is_button_off";
  if(this.currentImage() == this.images.length)  
    document.getElementById('is_next').className = "is_button_off";
  if(this.currentImage() == 2)  
    document.getElementById('is_prev').className = "is_button";
  if(this.currentImage() == this.images.length-1)  
    document.getElementById('is_next').className = "is_button";
}

Scroller.prototype.updateSizes = function() {
  var maxw = 0; var maxh = 0; 
  var width = 0;
  for(var i=1; i<=this.images.length; ++i) {
    var img = document.getElementById(this.id+i).firstChild;  
    if( img.width  > maxw ) maxw = img.width;
    if( img.height > maxh ) maxh = img.height;
  }
  this.frameWidth = maxw;
  fullwidth = this.frameWidth * this.images.length;

  // set scroll window width
  document.getElementById(this.id).style.width = fullwidth;

  // set holderdimensions 
  document.getElementById("is_holder").style.width  = maxw;
  document.getElementById("is_holder").style.height = maxh;
  
  // set window dimensions
  var win = document.getElementById("is_window");
  win.style.width = maxw; win.style.height = maxh;
  win.style.clip.top    = 0;    win.style.clip.right = maxw; 
  win.style.clip.bottom = maxh; win.style.clip.left  = 0; 

  // set internal divs
  for(var i=1; i<=this.images.length; ++i) {
    var div = document.getElementById(this.id+i);  
    div.style.width  = maxw; 
    div.style.height = maxh; 
  }

  // finally, center each of the images vertically
  for(var i=1; i<=this.images.length; ++i) {    
     var image = document.getElementById(this.id+i).firstChild;    
     newtop = (maxh - image.height) / 2; 
     image.style.position = "relative";
     image.style.top = newtop+"px";  
  } 
}

//function write_slideshow(scroller)
Scroller.prototype.write_slideshow = function(scroller)
{
  images = scroller.images;
  document.write('<div id="is_holder"><div id="is_window"><div id="scroller" class="content">');
  for( var i=0; i<images.length; ++i)
    document.write("<div><img src='"+ images[i] + "'/></div>" );
  document.write('</div></div></div>');
  document.write('<p id="info"></p>');

  var phref= 'href="javascript:;" onclick="scrollObj.slideLeft();return false"';
  var prev ='<a '+phref+' id="is_prev" class="is_button">&lt; Previous</a>&nbsp;';

  var nhref='href="javascript:;" onclick="scrollObj.slideRight();return false"';
  var next ='<a '+nhref+' id="is_next" class="is_button">Next &gt;</a>';

  document.write(prev + next);
}



function sde_img(v) { return eval(v) }

function init_tmp() 
{
  //var re = //; 
  //if( re.exec(window.location.toString()) ) 
  //{ 
  //f=document.getElementsByTagName("P"); 
  //f=document.getElementById("scroller"); 
  //alert(f.tagName);
  //f.innerHTML = "hello world";
  //}
}


// function find_in(col, tag)
// input collection:col, HTML tag: tag
// returns count of how many children of 'col' are 'tag'
function find_in(col, tag) 
{
  var results = 0;
  for( i=0; i<col.childNodes.length; ++i) {
    if( col.childNodes[i].tagName == tag) {
      ++results;
    } 
  }
  return results;
}

/*
function output(something)        { 
  document.getElementById('logger').firstChild.nodeValue  = something; 
  }
function output_append(something) { 
  document.getElementById('logger').firstChild.nodeValue += something; 
  }
function output_html(something)   { 
  document.getElementById('logger').innerHTML  = something; 
  }
function output_append_html(something) { 
  document.getElementById('logger').innerHTML  += something; 
  }

function inspect(elm){
  var str = "<pre>";
  for (var i in elm) str += i + ": " + elm.getAttribute(i) + "\n"; 
  str += "</pre>";
  output_html(str);
}
*/

//  Image Preloader - idea taken from: 
//  http://www.webreference.com/programming/javascript/gr/column3/ 
//  Simplified and modfied for OO

function ImagePreloader(images, who, callback)
{
   this.callback= callback; this.who = who;        // store the callback
   this.nLoaded = 0;        this.nProcessed = 0;   // initialize internal state.
   this.aImages = new Array;this.nImages = images.length;
   for ( var i = 0; i < images.length; i++ )
      this.preload(images[i]);
}

ImagePreloader.prototype.preload = function(image)
{
   var oImage = new Image; // create new Image object and add to array
   var thePreloader = this;

   oImage.onload  = function () { thePreloader.onload(); }
   oImage.onload  = function () { thePreloader.onload(); }
   oImage.onerror = function () { thePreloader.onload(); }
   oImage.onabort = function () { thePreloader.onload(); }
   oImage.src = image;     // assign the .src property of the Image object
   this.aImages.push(oImage);
}

ImagePreloader.prototype.onComplete = function()
{
   this.nProcessed++;
   if ( this.nProcessed == this.nImages )
      this.callback.call(this.who);
}

ImagePreloader.prototype.onload = function() {this.nLoaded++; this.onComplete()}


// Popup Functions, from sitepoint
function PopupPic(sPicURL) { 
     window.open( "http://www.cpocampbellhausfeld.com/popup.html?"+sPicURL, "",  
     "resizable=1,HEIGHT=200,WIDTH=200"); 
} 

function FitPic() { 
  var w = (NS)?window.innerWidth :document.body.clientWidth; 
  var h = (NS)?window.innerHeight:document.body.clientHeight; 
  var img = document.images[0]; 
  dW = img.width  - w; 
  dH = img.height - h; 
  window.resizeBy(dW, dH); 

  // center the image
  w = (NS)?window.innerWidth :document.body.clientWidth; 
  h = (NS)?window.innerHeight:document.body.clientHeight; 
  img.style.position = "relative";  
  img.style.top  = (h-img.height)/2+"px"; 
  img.style.left = (w-img.width)/2 +"px"; 
  self.focus(); 
} 

