/* *****************************************************************************
** File:      slidebox.js
** Author:    Match Grun.
** Copyright: (c) 2008-2009.
** License:   SlideBox is freely distributable under the terms of an MIT-style
**            license.
** Permission is hereby granted, free of charge, to any person obtaining a copy
** of this software and associated documentation files (the "Software"), to deal
** in the Software without restriction, including without limitation the rights
** to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
** copies of the Software, and to permit persons to whom the Software is
** furnished to do so, subject to the following conditions:
**
** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
** OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
** SOFTWARE.
** *****************************************************************************
*/
var mgSlideBox = {

   init: function() {
      if( this.isSetup == null ) {
         this.idImageMain = "mgsImageMain";
         this.idLinkImage = "mgsLinkImage";
         this.idImageName = "mgsImageName";
         this.idImageDesc = "mgsImageDescription";
         this.idGallerySelect = "mgsGallerySelect";
         this.idGalleryName = "mgsGalleryNameText";
         this.idGalleryDesc = "mgsGalleryDescription";
         this.idContentSBar = "mgsContentSidebar";
         this.idGalleryBar = "mgsGallerySidebar";
         this.idImgHome = "mgsImgHome";
         this.idImgNext = "mgsImgNext";
         this.idImgPrev = "mgsImgPrevious";
         this.clsGalleryThumb = "mgsGalleryThumb";
         this.clsLinkThumb = "mgsLinkThumb";
         this.dirThumbs = "thumbs/";
         this.dirImages = "images/";
         this.purchaseSite = "contact.html";
         this.isSetup = "true";
         this.indGallery = 0;
         this.scrollTimerID = 0;
         this.scrollInterval = 100; // millisecs
         this.scrollAmount = 400;   // pixels
         this.isMobile = false;
         this.isIPhone = false;
         this.idScrollDown = "mgsScrollDown";
         this.idScrollUp = "mgsScrollUp";
         this.showSidebar = true;
         this.adjustClientY = 0;
         this.currGallery = null;
      }
      this.checkAdjustClient();
      // this.checkForMobile();
   },

   checkAdjustClient: function() {
      try {
         var userAgent = navigator.userAgent;
         if( userAgent.indexOf( ' MSIE ' ) > 0 ) {
            this.adjustClientY = 70;
         }
      }
      catch( err ) {
      }
   },

   checkForMobile: function() {
      var flagMobile = false;
      var flagIPhone = false;
   	var flagSidebar = true;
      var userAgent = navigator.userAgent;
      if( userAgent.indexOf( 'iPhone' ) > 0 ) {
      	flagMobile = true;
      	flagIPhone = true;
      	flagSidebar = false;
      }
      if( userAgent.indexOf( 'iPad' ) > 0 ) {
      	flagMobile = false;
      	flagIPhone = false;
      	flagSidebar = true;
      }
      if( userAgent.indexOf( 'iPod' ) > 0 ) {
      	flagMobile = true;
      	flagIPhone = true;
      	flagSidebar = false;
      }
      if( userAgent.indexOf( 'Android' ) > 0 ) {
      	flagMobile = true;
      }
      this.isMobile = flagMobile;
      this.showSidebar = flagSidebar;
      this.isIPhone = flagIPhone;
      // this.isIPhone = true;
      // this.showSidebar = false;
   },

   initHandlers: function() {
      // Setup main image handler
      Event.observe( $( this.idImageMain ), 'click', this.onClickImage.bindAsEventListener( this ) );

      // Setup button handler
      Event.observe( $( this.idImgNext ), 'click', this.buttonNext.bindAsEventListener( this ) );
      Event.observe( $( this.idImgPrev ), 'click', this.buttonPrevious.bindAsEventListener( this ) );
      Event.observe( $( this.idImgHome ), 'click', this.buttonHome.bindAsEventListener( this ) );

      if( this.isMobile )
      {
         // Setup scroll buttons
         Event.observe( $( this.idScrollUp ), 'click', this.buttonScrollDown.bindAsEventListener( this ) );
         Event.observe( $( this.idScrollDown ), 'click', this.buttonScrollUp.bindAsEventListener( this ) );
      }
      else
      {
         // Setup auto-scroll buttons
         Event.observe( $( this.idScrollUp ), 'mouseover', this.buttonAutoScrollDown.bindAsEventListener( this ) );
         Event.observe( $( this.idScrollUp ), 'mouseout', this.cancelScroll.bindAsEventListener( this ) );
         Event.observe( $( this.idScrollDown ), 'mouseover', this.buttonAutoScrollUp.bindAsEventListener( this ) );
         Event.observe( $( this.idScrollDown ), 'mouseout', this.cancelScroll.bindAsEventListener( this ) );
      }

		if( this.showSidebar ) {
	      Event.observe( $( window ), 'resize', this.setSidebarHeight.bindAsEventListener( this ) );
	   }

      // Setup purchase handler
      /*
      var element = $( this.idLinkImage );
      if( element != null )
      {
         Event.observe( element, 'click', this.buyMeButton.bindAsEventListener( this ) );
      }
      */

   },

   setupImages: function() {
      this.imgPointers = [];
      this.currentImage = null;
      this.currentIndex = -1;

      // Setup thumbnail handlers
      for( var i = 0; i < document.images.length; i++ ) {
         var element = document.images[i];
         if( element.className ) {
            if( element.className == this.clsGalleryThumb ) {
               Event.observe( element, 'click', this.onClickThumb.bindAsEventListener( this ) );
               this.imgPointers.push( element );
            }
         }
      }

      this.showFirst();
   },

   loadGallery: function() {
      // Initialize globals
      this.init();

		if( this.showSidebar ) {
			this.setSidebarHeight( 0 );
      	$( this.idGalleryBar ).scrollTop = 0;
		}

      // Load gallery and image data
      this.loadGalleryData();
      this.setupGallery();

      // Setup handlers
      this.initHandlers();

      // Load image data
      this.fetchImageData();

      // Load images
      this.loadImageData();

   },

   setPurchaseSite: function( baseURI ) {
      this.purchaseSite = baseURI;
   },

   onClickThumb: function( event ) {
      var clickedImage = Event.element( event );
      for( var i = 0; i < this.imgPointers.length; i++ ) {
         if( this.imgPointers[i] == clickedImage ) {
            this.currentIndex = i;
            break;
         }
      }
      Event.stop( event );
      this.displayImage( this.currentIndex  );
   },

   onClickImage: function( event ) {
      var element = Event.element( event );
      var clickX = Event.pointerX( event );
      var elemCenter = 0;
      var elemType = element.tagName.toLowerCase();
      if( elemType == "img" ) {
         if( element.x == null ) {
            elemCenter = 0;
         }
         else {
            elemCenter = element.x + ( element.clientWidth / 2 );
         }
      }
      if( clickX < elemCenter )
      {
         this.showWrapPrevious();
      }
      else
      {
         this.showWrapNext();
      }
      return false;
   },

   showFirst: function() {
      if( this.imgPointers.length > 0 ) {
         this.displayImage( 0 );
      }
   },

   showLast: function() {
      if( this.imgPointers.length > 0 ) {
         this.displayImage( this.imgPointers.length - 1 );
      }
   },

   showNext: function() {
      if( this.imgPointers.length > 0 ) {
         var ind = this.currentIndex;
         ind++;
         if( ind != this.imgPointers.length ) {
            this.displayImage( ind );
         }
      }
   },

   showPrevious: function() {
      if( this.imgPointers.length > 0 ) {
         var ind = this.currentIndex;
         ind--;
         if( ind < 0 ) {
            this.displayImage( ind );
         }
      }
   },

   showWrapNext: function() {
      if( this.imgPointers.length > 0 ) {
         var ind = this.currentIndex;
         ind++;
         if( ind == this.imgPointers.length ) {
            ind = 0;
         }
         this.displayImage( ind );
      }
   },

   showWrapPrevious: function() {
      if( this.imgPointers.length > 0 ) {
         var ind = this.currentIndex;
         ind--;
         if( ind < 0 ) {
            ind = this.imgPointers.length - 1;
         }
         this.displayImage( ind );
      }
   },

   displayImage: function( selectedIndex ) {
      this.currentIndex = selectedIndex;
      var element = this.imgPointers[ this.currentIndex ];
      var imgName = this.findImageName( element );
      this.setMainImage( element );
      this.setImageTitle( imgName );

      // Redirect buy me to purchase site
      this.setImageLink( imgName );

      var desc = this.findDescription( imgName );
      var elem = $( this.idImageDesc );
      if( elem != null )
      {
         elem.innerHTML = "<p>" + desc + "</p>";
      }

      var elem2 = $( this.idGalleryBar );
      var str = "" + elem2;

   },

   setMainImage: function( selectedImage ) {
      var parentLink = selectedImage.parentNode;
      var newImage = $( this.idImageMain );

      // Setup main image from selected thumbnail
      newImage.src = parentLink.href;
      newImage.title = selectedImage.title;
      newImage.style.visibility = "visible";
      newImage.name = selectedImage.name;

      this.currentImage = newImage;
   },

   setImageLink: function( imgName ) {
      var imgLink = $( this.idLinkImage );
      if( imgLink != null ) {
         imgLink.href = this.purchaseSite + "?image=" + imgName;
      }
   },

   buttonNext: function( event ) {
      this.showWrapNext();
      Event.stop( event );
   },

   buttonPrevious: function( event ) {
      this.showWrapPrevious();
      Event.stop( event );
   },

   buttonHome: function( event ) {
      this.showFirst();
      Event.stop( event );
   },

   getSelectedImageName: function() {
      var newImage = $( this.idImageMain );
      var imgName = newImage.src;
      var ipos = 1 + imgName.lastIndexOf( "/" );
      imgName = imgName.substr( ipos );
      ipos = imgName.indexOf( "." );
      imgName = imgName.substr( 0, ipos );
      return imgName;
   },

   findImageName: function( selectedImage ) {
      var parentLink = selectedImage.parentNode;
      var imgName = parentLink.attributes[ "href" ].nodeValue;
      var fileName = "";
      if( imgName != null ) {
         var ipos = 1 + imgName.lastIndexOf( "/" );
         fileName = imgName.substr( ipos );
      }
      return fileName;
   },

   setImageTitle: function( fileName ) {
      ipos = fileName.indexOf( "." );
      imgName = fileName.substr( 0, ipos );
      var element = $( this.idImageName );
      if( element != null )
      {
         element.innerHTML = imgName;
      }
      return fileName;
   },

   buyMeButton: function( event ) {
      // Event.stop( event );
      var imgName = this.getSelectedImageName();
      var url = this.purchaseSite + "?image=" + imgName;
      var msg = "Buying: " + imgName;
      msg += "\nfrom: " + this.purchaseSite;
      msg += "\nurl:\n   " + url;
      // alert( msg );
   },

   loadGalleryData: function() {
      var galleryData = mgGalleryData.init();
      this.currGallery = galleryData[ this.indGallery ];
      if( this.currGallery == null ) return;
      var elem = $( this.idGalleryDesc );
      if( elem != null )
      {
         elem.innerHTML = "" + this.currGallery.description;
      }
      elem = $( this.idGalleryName );
      if( elem != null )
      {
         elem.innerHTML = this.currGallery.contents;
         document.title = this.currGallery.contents;
      }
   },

   loadImageData: function() {
      try {
         var imageData = mgImageData.init();
         this.loadImageFromData( imageData );
      }
      catch( err ) {
      }
   },

   loadImageFromData: function( imageData ) {
      var textHTML = "\n";
      for( var i = 0; i < imageData.length; i++ ) {
         var o = imageData[i];
         if( o == null ) continue;
         var t = '<a xmlns="" href="';
         t += this.dirImages;
         t += o.file;
         t += '" class="';
         t += this.clsLinkThumb;
         t += '" >';
         t += '<img src="';
         t += this.dirThumbs;
         t += o.file;
         t += '" class="';
         t += this.clsGalleryThumb;
         t += '"';
         if( o.title != null ) {
            t += ' title="';
            t += o.title;
            t += '" alt="';
            t += o.title;
            t += '"';
         }
         t += '></img></a>\n';
         textHTML += t;
      }
      var elem = $( this.idGalleryBar );
      if( elem != null )
      {
         elem.innerHTML = textHTML;
      }
      this.dataMGImageData = imageData;
   },

   findDescription: function( name ) {
      var desc = "";
      if( typeof( mgImageData ) != 'undefined' ) {
         var imageData = mgImageData.init();
         for( var i = 0; i < imageData.length; i++ ) {
            var o = imageData[i];
            if( o.file == name ) {
               if( o.description != null ) {
                  desc = o.description;
                  break;
               }
            }
         }
      }
      return desc;
   },

   formatIndex: function( ind ) {
      var str = "0000" + ind;
      var sLen = str.length;
      str = str.substr( sLen - 2, 2 );
      return str;
   },

   setupGallery: function() {
      var galleryData = mgGalleryData.data;
      if( galleryData == null ) return;

      var elemSelect = $( this.idGallerySelect );
      if( elemSelect == null ) return;

      var iLen = mgGalleryData.data.length;
      for( var i = 0; i < iLen; i++ ) {
         var str = this.formatIndex( i );
         var item = mgGalleryData.data[i];
         var txtNode = document.createElement( "option" );
         txtNode.value = str;
         txtNode.innerHTML = item.contents;
         elemSelect.appendChild( txtNode );
      }
   },

   getFilename: function( str ) {
      var ipos = 1 + str.lastIndexOf( "/" );
      if( ipos > 0 ) {
         return str.substr( ipos );
      }
      return str;
   },

   selectGallery: function( elem ) {
      var strPage = elem.value;
      if( strPage == '' ) return false;
      this.indGallery = elem.selectedIndex - 1;
      this.loadGalleryData();
      this.fetchImageData();
      return true;
   },

   fetchImageData: function() {
      var url = "data/" + this.currGallery.file + ".js";
      new Ajax.Request(
         url,
         {
            method: 'get',
            onSuccess: function( transport ) {
               var strResp = transport.responseText;
               mgSlideBox.handleAjax( strResp );
            }
         }
      );
   },

   handleAjax: function( strResp ) {
      var imageData;
      try
      {
         eval( strResp );
         imageData = mgImageData.init();
         this.loadImageFromData( imageData );
         this.setupImages();
      }
      catch( err )
      {
         alert( "Caught Ya" );
      }
   },

   buttonScrollUp: function( event ) {
      this.scrollTimer = mgSlideBox.scrollThumb( 1 );
   },

   buttonScrollDown: function( event ) {
      this.scrollTimer = mgSlideBox.scrollThumb( -1 );
   },

   buttonAutoScrollUp: function( event ) {
      this.scrollTimerID =
         setInterval( function() { mgSlideBox.scrollThumb( 1 ) }, this.scrollInterval );
   },

   buttonAutoScrollDown: function( event ) {
      this.scrollTimerID =
         setInterval( function() { mgSlideBox.scrollThumb( -1 ) }, this.scrollInterval );
   },

   cancelScroll: function( event ) {
      clearInterval( this.scrollTimerID );
   },

   scrollThumb: function( direction ) {
      var elem = $( this.idGalleryBar );
      var xTop = elem.scrollTop;
      if( direction < 0 ) {
         xTop -= this.scrollAmount;
      }
      else {
         xTop += this.scrollAmount;
      }
      if( xTop < 0 ) {
         xTop = 0;
      }
      if( xTop > elem.scrollHeight ) {
         xTop = elem.scrollHeight;
      }
      elem.scrollTop = xTop;
   },

   setSidebarHeight: function( event ) {
      var elem = $( this.idGalleryBar );
      var winh = document.body.clientHeight;
      var scrh = winh - ( elem.offsetTop + this.adjustClientY + 20 );
      elem.style.height = scrh + "px";
   }

};


