include( "com/karaszewski/ajaxlib.js" );

/**
 * http://www.quirksmode.org/blog/archives/2005/09/xmlhttp_notes_r.html
 * /
function loadXML( url ) {
  //alert(url);
  var xhReq = newXMLHttpRequest();
  xhReq.open( "GET", url, false );
  //xhReq.overrideMimeType('text/xml');
  xhReq.send(null);
  
  var xml = xhReq.responseXML;

  //
  // The following is for local testing with IE.
  //
  //if ( xIE4Up && url.substr(0, 7) == "file://" ) {
  //alert( location.href );
  var fileProtocolStr = "file://";
  if ( xIE4Up && ( location.href.substr( 0, fileProtocolStr.length ) == fileProtocolStr ) ) {
    var doc = new ActiveXObject("Msxml2.FreeThreadedDOMDocument.3.0");
    doc.async = false;
    //doc.load( "file:///C:/var/tmp/test.xml" );
    doc.load( url );
    //alert( "node? " + doc.childNodes[0].getAttribute("src") );
    xml = doc;
  }

  

  //xhReq.responseXML.loadXML( xhReq.responseText );

  //alert( xhReq.responseText );
  //alert( xhReq.responseXML );

  stripWhiteSpace( xml );
  return xml;
}
*/

var currentSection = null;

function Section( sectionDiv, isFirst ) {
  this._div = sectionDiv;
  this._isFirst = isFirst;
  this._galleryDiv = xGetElementsByClassName("gallery", sectionDiv)[0];
  this._imagesDiv = xGetElementsByClassName("images", sectionDiv)[0];
  this._navigatorDiv = xGetElementsByClassName("navigator", sectionDiv)[0];
  this._lineDiv = xGetElementsByClassName("line", sectionDiv)[0];

  var titleDiv = xGetElementsByClassName("title", sectionDiv)[0];

  this._titleImg = xGetElementsByTagName( "img", titleDiv )[0];
  this._titleHighlight = new Highlight( this._titleImg );
  

  var _this = this;
  titleDiv.onclick = function() {_this.showGallery(); };

  this.showGallery = Section_showGallery;
  this.transit = Section_transit;
  this.scrollRight = Section_scrollRight;
  this.scrollLeft = Section_scrollLeft;
  this.newShowTransition = Section_newShowTransition;
  this.newHideTransition = Section_newHideTransition;
  this.refreshThumbnails = Section_refreshThumbnails;
}

var isTransitioning = false;

function Section_newShowTransition() {
  var _this = this;
  var actions = new Array();
  actions[0] = new ShowTransition( new LineTransitionable( this._galleryDiv ), 600, 20 );
  actions[1] = new ShowTransition( this, 300, 20 );
  actions[2] = new Event( new function() {
      var r = new Object();
      r.run = function() {
	new Effect.Appear( _this._imagesDiv, { duration: 0.3 } );
	if ( _this._navigatorDiv ) {
	  new Effect.Appear( _this._navigatorDiv, { duration: 0.3 } );
	}
	isTransitioning = false;
      };
      return r;
    }()
			  );
  return new Serial( actions );
}

function Section_newHideTransition() {
  var _this = this;
  var actions = new Array();
  actions[0] = new Event( new function() {
      var r = new Object();
      r.run = function() {
	_this._imagesDiv.style.display = "none";
	_this._titleHighlight.setPinned( false );
	_this._titleHighlight.off();
	if ( _this._navigatorDiv ) {
	  _this._navigatorDiv.style.display = "none";
	}
      };
      return r;
    }()
			  );
  actions[1] = new HideTransition( this, 300, 20 );
  actions[2] = new HideTransition( new LineTransitionable( this._galleryDiv ), 300, 20 );
  return new Serial( actions );
}

function Section_scrollRight() {
  if ( isTransitioning )
    return;
  else
    setTransitionFor( 300 );

  var imagesDiv = this._imagesDiv;
  var imagesDivLeft = xLeft( imagesDiv );


  // Search for the rightmost image which is still visible
  var cutpoint = xClientWidth() - imagesDivLeft;


  //alert("left " + imagesDivLeft + " width " + xWidth( imagesDiv ) + " cutpoint " + cutpoint);

  var tds = xGetElementsByTagName( "td", this._imagesDiv );
  var target = null;
  for ( var i = 0; i < tds.length; ++i) {
    //alert( i + " ... " + tds[i].offsetLeft );
    if ( tds[i].offsetLeft < cutpoint ) {
      target = tds[i];
    } else {
      break;
    }
  }
  if ( target != null ) {
    new Effect.Move( imagesDiv, { x: 2 - (imagesDivLeft + target.offsetLeft), y: 0, mode: 'relative', duration: 0.3, fps: 25} );
  }
  
  this.refreshThumbnails();
}

function Section_refreshThumbnails() {
  // IE image loading interrupted by js bug workaround...
  if ( xIE4Up ) {
    var imgs = xGetElementsByTagName( "img", this._imagesDiv );
    for ( var i = 0; i < imgs.length; ++i) {
      imgs[i].src = imgs[i].src;
    }
  }
}

function setTransitionFor( msecs ) {
  isTransitioning = true;
  setTimeout( "isTransitioning = false", msecs );
}

function Section_scrollLeft() {
  if ( isTransitioning )
    return;
  else
    setTransitionFor( 300 );
 
  var imagesDiv = this._imagesDiv;
  var imagesDivLeft = xLeft( imagesDiv );

  // Search for the rightmost image which is NOT completely visible
  var cutpoint = - imagesDivLeft;
  var tds = xGetElementsByTagName( "td", this._imagesDiv );
  var target1 = null;
  for ( var i = 0; i < tds.length; ++i) {
    if ( tds[i].offsetLeft < cutpoint ) {
      target1 = tds[i];
    } else {
      break;
    }
  }
  if ( target1 != null ) {
    // Now we need to find the leftmost image that placed as first visible image allows the previous target 
    // to be completely visible. That is, 
    //
    //   target1.offsetLeft + xWidth( target1 ) < target2.offsetLeft + xClientWidth()
    //
    //
    
    var target2 = null;
    var cutpoint = target1.offsetLeft + xWidth( target1 ) - xClientWidth();
    for ( var i = 0; i < tds.length; ++i) {
      if ( tds[i].offsetLeft > cutpoint ) {
	target2 = tds[i];
	break;
      }
    }

    if ( target2 == null )
      target2 = target1;

    new Effect.Move( imagesDiv, { x: 2 - (imagesDivLeft + target2.offsetLeft), y: 0, mode: 'relative', duration: 0.3, fps: 25} );
  }

  this.refreshThumbnails();
}

function Section_showGallery() {
  if ( isTransitioning || currentSection == this )
    return;
  isTransitioning = true;

  createGallery( this._imagesDiv );
  this.refreshThumbnails();

  if ( currentSection != null ) {
    var actions = new Array();
    actions[0] = currentSection.newHideTransition();
    actions[1] = this.newShowTransition();
  } else {
    var actions = new Array();
    actions[0] = this.newShowTransition();
  }

  
  this._titleHighlight.setPinned( true );
  this._titleHighlight.on();

  currentSection = this;
  new Serial( actions ).start();
}

function Section_transit( k ) {
  if ( ! this._isFirst )
    this._div.style.marginTop = (40) * k + "px";
  this._galleryDiv.style.height = (200+20) * k + "px";

  if ( this._navigatorDiv )
    this._navigatorDiv.style.height = (70) * k + "px";
}

function LineTransitionable( lineDiv ) {
  this._lineDiv = lineDiv;
  this.transit = function( k ) {
    var c = Math.floor(k * 128);
    this._lineDiv.style.borderColor =  "rgb(" + c + "," + c + "," + c + ")";
  }
}

/////

/**
 *
 */
function createImage( galleryId, imageURL, thumbnailURL, caption ) {
  
  var a = document.createElement("a");
  a.setAttribute( "href", imageURL );
  a.setAttribute( "title", caption );
  a.setAttribute( "rel", "lightbox[" + galleryId + "]" );
  
  //a.setAttribute( "onclick", "javascript:alert('x');myLightbox.start(this); return false;" );
  // For some reason the previous doesnt work with IE6
  a.onclick = function () {myLightbox.start(this); return false;}
  
  var img = document.createElement("img");
  a.appendChild( img );
  img.setAttribute( "src", thumbnailURL );
  img.setAttribute( "alt", "" );
 
  return a;
}

function createGallery( imagesDiv ) {
  
  if ( imagesDiv.id == "contact" )
    return;

  var galleryId = imagesDiv.id;

  if ( xGetElementsByTagName( "table", imagesDiv ).length > 0 ) {
    //alert("gallery is there");
    return;
  }

  var table = document.createElement("table");
  imagesDiv.appendChild( table );

  var tbody =document.createElement("tbody");
  table.appendChild( tbody );
  
  var tr = document.createElement("tr");
  tbody.appendChild( tr );
  
  //var td = document.createElement("td");
  //tr.appendChild( td );
  //td.appendChild( document.createTextNode("alex") );

  //tr.appendChild( createTD( createImage( galleryId, "images/DSCF0732.jpg", "images/DSCF0732-small.jpg", "Arcola - bla bla") ) );
  //tr.appendChild( createTD( createImage( galleryId, "images/DSCF0732.jpg", "images/DSCF0732-small.jpg", "Arcola - bla bla") ) );
  //tr.appendChild( createTD(document.createTextNode("alex")) );
  
  //imagesDiv.appendChild( document.createTextNode("alex") );

  //var xml = loadXML( "file:///C:/var/tmp/test.xml" );
  

  //var xml = loadXML( "http://evangelista.tv/test/" + galleryId + ".xml" );
  var xml = loadXML( galleryId + ".xml" );

  var baseUrl = xml.childNodes[0].getAttribute( "baseUrl" );

  var imageElements = xml.childNodes[0].childNodes;

  for ( var i = 0; i < imageElements.length; ++i ) {

    var ie = imageElements[i];

    //var imageSrc = "images/" + galleryId + "/" + ie.getAttribute("src");
    var imageSrc = baseUrl + ie.getAttribute("src");
    //alert(imageSrc);

    var imageCaption = ie.getAttribute("caption");
    var thumbSrc = imageSrc.substr( 0, imageSrc.length - 4 ) + "-small" + imageSrc.substr( imageSrc.length - 4, imageSrc.length );
    // alert( "thumbSrc " + thumbSrc );
    //alert( imageSrc + " " + thumbSrc );
    tr.appendChild( createTD( createImage( galleryId, imageSrc, thumbSrc, imageCaption ) ) );
    //alert( ie.getAttribute("src") + " " + ie.getAttribute("caption") );
  }

}

function createTD( child ) {
  var td = document.createElement("td");
  td.appendChild( child );
  return td;
}


/////

function Page() {
  this.onLoad = Page_onLoad;
  this.onUnload = function() {
    ; //alert("onunload");
  }
}

function Page_onLoad() {

  var sectionDivs = xGetElementsByClassName("section");
  var firstSection;
  for (i = 0; i < sectionDivs.length; ++i) {
    var sectionDiv = sectionDivs[i];
    var section = new Section( sectionDiv, i == 0 );
    if ( i == 0 )
      firstSection = section;
  }
  // Do not call before here. showGallery changes the DOM...
  firstSection.showGallery();
  
  var navs = xGetElementsByClassName("highlight");
  for (i = 0; i < navs.length; ++i) {
    var nav = navs[i];
    new Highlight( nav );
  }

}

function Highlight( div ) {
  this._div = div;
  this._isOver = true;
  this._isPinned = false;
  this.setPinned = function( flag ) {
    this._isPinned = flag;
  }
  this.on = function() {
    Element.setOpacity( this._div, 1.0 );
  }
  this.off = function() {
    Element.setOpacity( this._div, 0.7 );
  }
  this.onOver = function() {
    if ( this._isOver && !this._isPinned ) {
      this.on();
      this._isOver = false;
    }
  }
  this.onOut = function() {
    if ( ! this._isOver && !this._isPinned ) {
      this.off();
      this._isOver = true;
    }
  }

  var _this = this;
  div.onmouseover = function() { _this.onOver(); };
  div.onmouseout = function() { _this.onOut();  };

  this.off();
}

var page = new Page();


/**
 * ShowTransition
 *
 * @param transitionable  an object implementing "void transit( k )" where k ranges within [0..1]
 *
 */
function ShowTransition_ctr( _this, transitionable, duration, period ) {
  Transition_ctr( _this, null, duration, period );
  _this._transitionable = transitionable;
  _this.doTransition = ShowTransition_doTransition;
}

function ShowTransition_doTransition( k ) {
  this._transitionable.transit( k );
}

function ShowTransition( transitionable, duration, period ) {
  ShowTransition_ctr( this, transitionable, duration, period );
}


/**
 * HideTransition
 *
 */
function HideTransition_ctr( _this, transitionable, duration, period ) {
  Transition_ctr( _this, null, duration, period );
  _this._transitionable = transitionable;
  _this.doTransition = HideTransition_doTransition;
}

function HideTransition_doTransition( k ) {
  this._transitionable.transit( 1-k );
}

function HideTransition( transitionable, duration, period ) {
  HideTransition_ctr( this, transitionable, duration, period );
}


/**
 * Event
 *
 * @param runnable
 */
function Event( runnable ) {
  this._runnable = runnable;
  this.start = function() {
    this._runnable.run();
    if ( this.onAfter ) {
      this.onAfter();
    }
  }
}

/**
 * Serial
 */

function Serial( actionArray ) {
  var _this = this;
  this._actions = actionArray;
  this._index = 0;

  this.startNext = function() {
    if ( ++(this._index) < this._actions.length ) {
      this._actions[ this._index ].start();
    } else if ( this.onAfter ) {
      this.onAfter();
    }
  };

  this.start = function() {
    this._actions[0].start();
  };

  for ( i in actionArray ) {
    actionArray[i].onAfter = function() {
      _this.startNext();
    };
  }
}

/**
 * Parallel
 */

function Paraller( actionArray ) {
  this._actions = actionArray;
  this._nCompleted = 0;
  this.start = function() {
    for ( i in this._actions ) {
      this._actions[ i ].start();
    }
  };

  this.notifyComplete = function( action ) {
    this._nCompleted++;
    if ( this._nCompleted == this._actions.length ) {
      if ( this.onAfter )
	this.onAfter();
    }
  };

  var _this = this;
  for ( i in actionArray ) {
    actionArray[i].onAfter = function() {
      _this.notifyComplete( this );
    };
  }
}

function scrollRight() {
  currentSection.scrollRight();
}

function scrollLeft() {
  currentSection.scrollLeft();
}

//change the opacity for different browsers
/**
 * @param alpha 0..100
 */
function setAlpha( element, alpha ) {
  element.opacity = (alpha / 100);
  element.MozOpacity = (alpha / 100);
  element.KhtmlOpacity = (alpha / 100);
  element.filter = "alpha(opacity=" + alpha + ")";
}


/**
 * Init
 */
window.onload = function() {
  page.onLoad();
  if (window.winOnLoad) {
    window.winOnLoad();
  }
}

window.onunload = function() {
  page.onUnload();
  if (window.winOnUnload) {
    window.winOnUnload();
  }
}



