/****************************************************************************
* Lucky Marble Photo Gallery
*
* Developed by Lucky Marble Solutions
* Copyright © 2006 Lucky Marble Solutiosn Corp - All rights reserved
* Last Modified: May 9, 2006
*
* Use of this script requires you provide a link back to our website:
*  www.i3dthemes.com
*  link code: <a href="http://www.i3dthemes.com">FrontPage Templates</a>
*
*****************************************************************************/

// PhotoGallery CONSTRUCTOR
// Given: configFile - path to xml config file
//        targetTagID  - DOM id of target gallery/image DIV tag
function PhotoGallery(configFile, targetTagID) {
  this.attributes    = new Array();

  // set up default configurations

  // general
  if (configFile == "") {
    this.setAttribute('configFile', PageQueryItem('gallery'));
  } else {
		this.setAttribute('configFile', configFile);
  }
  this.setAttribute('targetTagID', targetTagID);
  this.setAttribute('theme', 'ambition');

  // gallery page defaults
  this.setAttribute('imgWidth', 100);
  this.setAttribute('imgHeight', 80);
  this.setAttribute('imagesPerPage', 12);
  this.setAttribute('page', PageQueryItem('page'));

  // image viewer defaults
  this.setAttribute('img', parseInt(PageQueryItem("img")));
  this.setAttribute('totalMiniThumbs', 8);
  this.setAttribute('miniThumbWidth', 75);
  this.setAttribute('miniThumbHeight', 60);
  this.setAttribute('miniThumbSpace', 2);

}

// PhotoGallery Render Gallery
// Purpose: initiates the loading of the XML file passing a boolean declaring
//          that this is the gallery page
// Given: none
// Returns: none
PhotoGallery.prototype.renderGallery = function() {
  this.loadConfigFile(true);
}

// PhotoGallery Render Image
// Purpose: initiates the loading of the XML file passing a boolean declaring
//          that this not a gallery page
// Given: none
// Returns: none
PhotoGallery.prototype.renderImage = function() {
  this.loadConfigFile(false);
}

// PhotoGallery Set Attribute
// Purpose: stores a passed in value in a global associative array
// Given: name - name of the attribute (used to later reference the attribute)
//        value - value to be storeed
// Returns: none
PhotoGallery.prototype.setAttribute = function(name, value) {
	this.attributes[name] = value;
}

// PhotoGallery Get Attribute
// Purpose: retrieves attribute for given name from global associative array
// Given: name - name of the attribute to be returned
// Returns: value that is stored in the array for given name
PhotoGallery.prototype.getAttribute = function(name) {
	return this.attributes[name];
}

// PhotoGallery Load Config File
// Purpose: initiates the loading of the XML configuration file and invokes
//          the rendering of the gallery or image viewer
// Given: renderGallery - true/false - true=render gallery/false=render image
// Returns: none
PhotoGallery.prototype.loadConfigFile = function(renderGallery) {

	var myObj = this;
	var linkTag = document.createElement("link");
	linkTag.setAttribute("rel", "stylesheet");
	linkTag.setAttribute("type", "text/css");
	linkTag.setAttribute("href", "photo-gallery/themes/" + this.getAttribute('theme') + "/photo-gallery.css");
  var galleryContainer = document.getElementById("galleryStyling");
  galleryContainer.appendChild(linkTag);

	if (document.implementation && document.implementation.createDocument) {
	  this.xmlDoc = document.implementation.createDocument("", "", null);
	  this.xmlDoc.onload = function () {
			if (renderGallery == true) {
				myObj.displayGallery();
			} else {
				myObj.displayImage();
			}
	  }
	} else if (window.ActiveXObject) {
	  this.xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
	  this.xmlDoc.onreadystatechange = function() {
			if (myObj.xmlDoc.readyState == 4) {
				if (renderGallery == true) {
					myObj.displayGallery();
				} else {

					myObj.displayImage();
			  }
			}
		};
	} else  {
	  alert('Your browser can\'t render this photo gallery.');
	  return;
	}

  this.xmlDoc.load(this.getAttribute('configFile'));
}


// PhotoGallery Display Image
// Purpose: renders all aspects of the image viewer page
// Given: none
// Returns: none
PhotoGallery.prototype.displayImage = function() {
	var xmlDoc          = this.xmlDoc;
	var targetTagID     = this.getAttribute('targetTagID');
  var x               = xmlDoc.getElementsByTagName('image');
  var myImage         = document.createElement("IMG");
  var imageID         = this.getAttribute("img");

  /** RENDER LARGE IMAGE **/
  thisImageLargeSrc = x[imageID].getElementsByTagName("location");
	if (thisImageLargeSrc.length > 0) {
		myImage.setAttribute("src", thisImageLargeSrc[0].firstChild.nodeValue);
	} else {
	  myImage.setAttribute("src", "photo-gallery/images/no-image.png");
	}


  myImage.setAttribute('className', 'mainImage');
  myImage.setAttribute('class', 'mainImage');

  if (this.getAttribute("imagePreviewWidth") != undefined) {
    myImage.setAttribute('width', this.getAttribute("imagePreviewWidth"));
  }


  if (this.getAttribute("imagePreviewHeight") != undefined) {
		myImage.setAttribute('height', this.getAttribute("imagePreviewHeight"));
  }

  /** RENDER GALLERY DETAILS (name, author, last updated) **/
  var galleryDetails = xmlDoc.getElementsByTagName('details');

  if (galleryDetails[0] != null) {
	  var allGalleryInfo = galleryDetails[0].getElementsByTagName("info");
	  for (i = 0; i < allGalleryInfo.length; i++) {
			nodeID          = allGalleryInfo[i].getAttribute("id");
			if (allGalleryInfo[i].firstChild != null) {
  			nodeValue       = allGalleryInfo[i].firstChild.nodeValue;
  			destinationNode = document.getElementById(nodeID);

  			if (nodeID == "lastUpdated") {
  				nodeValue = "(" + nodeValue + ")";
  		  }

  			if (destinationNode != null) {
  			  document.getElementById(nodeID).innerHTML = nodeValue;
  		  }
		  }
		}
  }

  document.getElementById(targetTagID).innerHTML = "";
  document.getElementById(targetTagID).appendChild(myImage);

  document.getElementById("imagePosition").innerHTML    = "Image " + (imageID+1) + " of " + (x.length);

  /** RENDER IMAGE DETAILS **/
  mainImageTitle       = x[imageID].getElementsByTagName('title');
  mainImageDescription = x[imageID].getElementsByTagName('description');

  if (mainImageTitle.length > 0 && mainImageTitle[0].firstChild != null) {
		document.getElementById("imageTitle").innerHTML       = mainImageTitle[0].firstChild.nodeValue + " - ";
  } else {
		document.getElementById("imageTitle").innerHTML = "";
  }

  if (mainImageDescription.length > 0 && mainImageDescription[0].firstChild != null) {
	  document.getElementById("imageDescription").innerHTML = mainImageDescription[0].firstChild.nodeValue;
	} else {
		document.getElementById("imageDescription").innerHTML = "";
  }


  // build nav buttons
   buttons = document.createElement("table");
   buttons.setAttribute("cellPadding", 0);
   buttons.setAttribute("cellSpacing", 0);

   buttonTableBody = document.createElement("tbody");

   buttonRow = document.createElement("tr");

   buttonBbg = document.createElement("td");
   buttonNbg = document.createElement("td");
   spacerCell = document.createElement("td");

   buttonB = document.createElement("IMG");
   buttonN = document.createElement("IMG");

   buttonLink1 = document.createElement("A");
   buttonLink2 = document.createElement("A");



  if (imageID == 0) {
		previousImageID = x.length - 1;
  } else {
		previousImageID = imageID - 1;
  }

  if (imageID == x.length - 1) {
		nextImageID = 0;
	} else {
		nextImageID = imageID + 1;
  }


  buttonBbg.setAttribute("className", "backButton");
  buttonNbg.setAttribute("className", "nextButton");

  buttonBbg.setAttribute("class", "backButton");
  buttonNbg.setAttribute("class", "nextButton");

  buttonLink1.setAttribute("href", 'javascript:pg.setAttribute("img", ' + previousImageID + '); pg.displayImage();');
  buttonLink2.setAttribute("href", 'javascript:pg.setAttribute("img", ' + nextImageID + '); pg.displayImage();');


  buttonB.setAttribute("src", "photo-gallery/images/transparent.gif");
  buttonN.setAttribute("src", "photo-gallery/images/transparent.gif");
  buttonB.setAttribute("className", "backButton");
  buttonN.setAttribute("className", "nextButton");
  buttonB.setAttribute("class", "backButton");
  buttonN.setAttribute("class", "nextButton");

  buttonB.setAttribute("border", 0);
  buttonN.setAttribute("border", 0);

  buttonLink1.appendChild(buttonB);
  buttonLink2.appendChild(buttonN);

  buttonBbg.appendChild(buttonLink1);
  buttonNbg.appendChild(buttonLink2);

  spacerCell.setAttribute("className", "spacerCell");
  spacerCell.setAttribute("class", "spacerCell");

  buttonRow.appendChild(buttonBbg);
  buttonRow.appendChild(spacerCell);
  buttonRow.appendChild(buttonNbg);
  buttonTableBody.appendChild(buttonRow);
  buttons.appendChild(buttonTableBody);

  document.getElementById("navButtons").innerHTML = "";
  document.getElementById("navButtons").appendChild(buttons);
  startPosition = imageID - 2;
  position = startPosition;
  totalMiniThumbs = this.getAttribute("totalMiniThumbs");
  miniThumbWidth = this.getAttribute("miniThumbWidth");
  miniThumbHeight = this.getAttribute("miniThumbHeight");
  miniThumbSpace  = this.getAttribute("miniThumbSpace");
  document.getElementById("navThumbs").innerHTML = "";

  // build thumbnail navigation
  while (position < totalMiniThumbs + startPosition) {
   if (position < 0) {
			displayPosition = x.length + position;
		} else if (position >= x.length) {
			displayPosition = position - x.length;
	  } else {
	    displayPosition = position;
	  }

    var thisThumbContainer = document.createElement("DIV");
		var thisThumb          = document.createElement("IMG");

    thisThumb.setAttribute("src", this.getThumbSRC(displayPosition));
    thisThumb.setAttribute("border", 0);

		thisThumb.setAttribute("width", miniThumbWidth);
		thisThumb.setAttribute("height", miniThumbHeight);

		thisThumbContainer.setAttribute("className", "miniThumbContainer");
		thisThumbContainer.setAttribute("class",     "miniThumbContainer");

		var thisThumbLink = document.createElement("A");
		thisThumbLink.setAttribute("href", 'javascript:pg.setAttribute("img", ' + displayPosition + '); pg.displayImage();');

		if (position == imageID) {
      thisThumb.setAttribute("className", "miniThumb_selected");
      thisThumb.setAttribute("class", "miniThumb_selected");
	  } else {
      thisThumb.setAttribute("className", "miniThumb_regular");
      thisThumb.setAttribute("class", "miniThumb_regular");
	  }

		thisThumbLink.appendChild(thisThumb);
		thisThumbContainer.appendChild(thisThumbLink);

		document.getElementById("navThumbs").appendChild(thisThumbContainer);
		document.getElementById("navThumbs").appendChild(document.createTextNode(" "));

    position++;
  }

}


// PhotoGallery Get Thumb Source
// Purpose: gets the relative URI for the smaller thumbnail of the given image position
// Given: displayPosition - int - index position of image to reference
// Returns: relative URI of the thumbnail
PhotoGallery.prototype.getThumbSRC = function(displayPosition) {
	var x = this.xmlDoc.getElementsByTagName('image');

	var thisImageThumbSrc = x[displayPosition].getElementsByTagName("thumbnail");
	var thisImageLargeSrc = x[displayPosition].getElementsByTagName("location");
	var thumbSource = "";

	if (thisImageThumbSrc.length > 0 && thisImageThumbSrc[0].firstChild != null) {
		thumbSource = thisImageThumbSrc[0].firstChild.nodeValue;
	} else {
		if (thisImageLargeSrc.length > 0 && thisImageLargeSrc[0].firstChild != null) {
			thumbSource = thisImageLargeSrc[0].firstChild.nodeValue;
		} else {
			thumbSource = "photo-gallery/images/no-image.png";
		}
	}

	return thumbSource;
}

// PhotoGallery Display Gallery
// Purpose: renders all aspects of the photo gallery
// Given: none
// Returns: none
PhotoGallery.prototype.displayGallery = function() {
	xmlDoc        = this.xmlDoc;
	targetTagID   = this.getAttribute('targetTagID');
	imgWidth      = this.getAttribute('imgWidth');
	imgHeight     = this.getAttribute('imgHeight');
	imagesPerPage = this.getAttribute('imagesPerPage');
	page          = this.getAttribute('page');
	document.getElementById(targetTagID).innerHTML = "";
	document.getElementById("galleryNavigation").innerHTML = "";

  var x = xmlDoc.getElementsByTagName('image');

  if (page == 'false') {
    page = 0;
  }


  var navTable = document.createElement("TABLE");
  var navTBody = document.createElement("TBODY");
  var navTRow  = document.createElement("TR");
  navTable.setAttribute("cellSpacing", 0);
  navTable.setAttribute("cellPadding", 0);
  navTable.setAttribute("width", "100%");

  //set up first navigation cell
  // gallery name/author


  // set up middle navigation cell
	// set up pages quick links
  var pageLinkCell = document.createElement("TD");
  pageLinkCell.appendChild(document.createTextNode("Page: "));
	for (i = 0; i < Math.ceil(x.length/imagesPerPage); i++) {
		var pageLink = document.createElement('A');

		pageLink.setAttribute('href', 'javascript:pg.setAttribute("page", ' + i + '); pg.displayGallery();');

		if (page == i) {
			var pageLinkSpan = document.createElement("SPAN");
			var pageLinkText = document.createTextNode("[" + (i+1) + "]");
      pageLinkSpan.setAttribute("className", "pageLink");
      pageLinkSpan.setAttribute("class", "pageLink");
      pageLinkSpan.appendChild(pageLinkText);
			pageLinkCell.appendChild(pageLinkSpan);
		} else {
			var pageLinkText = document.createTextNode(i+1);
			pageLink.appendChild(pageLinkText);
			pageLinkCell.appendChild(pageLink);
		}
    pageLink.setAttribute("className", "pageLink");
    pageLink.setAttribute("class", "pageLink");
    pageLinkCell.appendChild(document.createTextNode("   "));

  }
  navTRow.appendChild(pageLinkCell);
  // set up left navigation cell (back/next buttons)

  var navButtonCell = document.createElement("TD");
  navButtonCell.setAttribute("align", "right");

  navButtonTable = document.createElement("table");
  navButtonTBody = document.createElement("tbody");
  navButtonTRow  = document.createElement("tr");

  navButtonTable.setAttribute("cellSpacing", 0);
  navButtonTable.setAttribute("cellPadding", 0);
  navButtonTable.setAttribute("className", "galleryNavTableIE");
  navButtonTable.setAttribute("class", "galleryNavTable");

  // set up "back" link
  if (page > 0) {

    var backCell = document.createElement("td");
    backCell.setAttribute("className", "backButton");
    backCell.setAttribute("class", "backButton");
    var backLink = document.createElement('A');
    backLink.setAttribute('href', 'javascript:pg.setAttribute("page", ' + (parseInt(page)-1) + '); pg.displayGallery();');

    var backLinkButton = document.createElement('IMG')
    backLinkButton.setAttribute('src', 'photo-gallery/images/transparent.gif');
    backLinkButton.setAttribute('border', 0);

    backLink.appendChild(backLinkButton);
    backCell.appendChild(backLink);
    navButtonTRow.appendChild(backCell);
  }


  // set up "next" link
  var displayNextButton = x.length > imagesPerPage * (parseInt(page)+1)
  if ((page == 0 && displayNextButton) || displayNextButton) {
		var spacerCell = document.createElement("td");
		spacerCell.setAttribute("className", "spacerCell");
		spacerCell.setAttribute("class", "spacerCell");
    navButtonTRow.appendChild(spacerCell);

    var nextCell = document.createElement("td");
    nextCell.setAttribute("className", "nextButton");
    nextCell.setAttribute("class", "nextButton");

    var nextLink = document.createElement('A');
    nextLink.setAttribute('href', 'javascript:pg.setAttribute("page", ' + (parseInt(page)+1) + '); pg.displayGallery();');

    var nextLinkButton = document.createElement('IMG')
    nextLinkButton.setAttribute('src', 'photo-gallery/images/transparent.gif');
    nextLinkButton.setAttribute('border', 0);
    nextLink.appendChild(nextLinkButton);

    nextCell.appendChild(nextLink);
    navButtonTRow.appendChild(nextCell);

  }

  navButtonTBody.appendChild(navButtonTRow);
  navButtonTable.appendChild(navButtonTBody);
  navButtonCell.appendChild(navButtonTable);
  navTRow.appendChild(navButtonCell);
  navTBody.appendChild(navTRow);
  navTable.appendChild(navTBody);
  document.getElementById("galleryNavigation").appendChild(navTable);



  // build thumbnails for photo gallery
  for (i=page*imagesPerPage; i<x.length && i < page * imagesPerPage + imagesPerPage; i++) {
    var newEl = document.createElement('DIV');

    newEl.setAttribute('className', 'photoimage');

    var imageLink = document.createElement('A');

    if (this.getAttribute("imageViewer") == "" || this.getAttribute("imageViewer") == undefined) {

			imageLink.setAttribute("href", x[i].childNodes[0].firstChild.nodeValue);
	  } else {
		  imageLink.setAttribute("href", this.getAttribute("imageViewer") + "?img=" + i + "&gallery=" + this.getAttribute("configFile"));
	  }
    imageLink.setAttribute("target", "_blank");

    var theImageDiv = document.createElement('DIV');
    theImageDiv.setAttribute('class', 'photoimage');
    theImageDiv.setAttribute('className', 'photoimage');

    var theImage = document.createElement('IMG');

    //theImage.setAttribute('src', x[i].childNodes[0].firstChild.nodeValue);
    theImage.setAttribute("src", this.getThumbSRC(i));
    theImage.setAttribute('border', 1);
    theImage.setAttribute('width', imgWidth);
    theImage.setAttribute('height', imgHeight);
    theImage.setAttribute('className', 'photoimage');
    theImage.setAttribute('class', 'photoimage');
    imageLink.appendChild(theImage);
    theImageDiv.appendChild(imageLink);
    newEl.appendChild(theImageDiv);
   // alert(newEl.innerHTML);
    document.getElementById(targetTagID).appendChild(newEl);
  }
}

/***************************************
* HELPER FUNCTIONS
***************************************/

// Page Query
// Purpose: parses the HTML page's query string
// Given: page's URI
// Returns: an array of name/value pairs
function PageQuery(q) {
  if(q.length > 1) this.q = q.substring(1, q.length);
  else this.q = null;

  this.keyValuePairs = new Array();

  if(q) {
    for(var i=0; i < this.q.split("&").length; i++) {
      this.keyValuePairs[i] = this.q.split("&")[i];
    }
  }

  this.getKeyValuePairs = function() { return this.keyValuePairs; }
  this.getValue = function(s) {

    for(var j=0; j < this.keyValuePairs.length; j++) {
      if(this.keyValuePairs[j].split("=")[0] == s)
        return this.keyValuePairs[j].split("=")[1];
    }
    return false;
  }

  this.getParameters = function() {
    var a = new Array(this.getLength());
    for(var j=0; j < this.keyValuePairs.length; j++) {
      a[j] = this.keyValuePairs[j].split("=")[0];
    }
    return a;
  }

  this.getLength = function() { return this.keyValuePairs.length; }
}

// PageQueryItem
// Purpose: retrieves the value for a given parameter of the page's querystring
// Given: key - name of the parameter to be returned
// Returns: value of the parameter
function PageQueryItem(key){
  var page = new PageQuery(window.location.search);
  return unescape(page.getValue(key));
}

