/* hidBox - All format displayer. */
/* CopyRight 2009, HID Digital Solutions <http://www.hid.nl>. */
/* Released: Feb, 16h 2009. */

/* Start of hidBox class. */
var hidBox = {


   /* Initialise method, called when the dom tree is ready. */
   init: function (oOptions) {

      /* Set default option values in options object. */
      this.oOptions = Object.extend({
         contentType: 0,               // Content type, 0 = unknown.
         overlayDuration: 500,         // Duration of the overlay to get to final % transparency.
         overlayTransparency: 0.85,    // Percentage covered with overlay (higher is darker).
         resizeDuration: 500,          // Duration of height and width resizing in ms.
         initialWidth: 150,            // Initial width of the box in px.
         initialHeight: 150,           // Initial height of the box in px.
         defaultWidth: 250,            // Default width (used when no required width is supplied) in px.
         defaultHeight: 250,           // Default height (used when no required height is supplied) in px.
         requiredWidth: 300,           // Required height (set in setup() method) in px.
         requiredHeight: 300,          // Required height (set in setup() method) in px.
         hidBoxBackground: '#FFFFFF',  // hidBox background color.
         loadingAnimation: 1,          // Display loading animation? 1 = Yes, 0 = No.
         offsetTop: 0,                 // Offset compared to centering (px).
         oPlayer: null,                // Required player instance (null is none).
         oPlayerAutostart: 'true',     // Autostart video, true by default.
         oImage: null,                 // Preloaded image (if available).
         oInnerHTML: null              // InnerHTML element. Null = none.
      }, oOptions || {});

      /* Alter webpage anchors. */
      this.alterAnchors();

      /* Create overlay div element and add it to the document. */
		this.divOverlay = new Element('div').setProperty('id', 'hidBoxOverlay').injectInside(document.body);
		this.divOverlay.onclick = this.close.bind(this);

      /* Create hidBox div, set it's styles and add it to the document. */
      this.divHidBox  = new Element('div').setProperty('id', 'hidBox').setStyles({width: this.oOptions.initialWidth + 'px', height: this.oOptions.initialHeight + 'px', marginLeft: '-' + (this.oOptions.initialWidth / 2) + 'px', display: 'none'}).injectInside(document.body);

      /* Create hidBox close button, set it's styles and add it to the document. */
      this.butClose   = new Element('img').setProperty('id', 'butClose').setStyles({width: "17px", height: "17px", display: 'none', src: '/js/tools/hidBox/1-0-0/images/button_popup_close.png'}).injectInside(document.body);
      this.butClose.onclick = this.close.bind(this);

      /* Create effect. */
      var nextEffect = this.nextEffect.bind(this);
      this.fx = {
			divOverlay: this.divOverlay.effect('opacity', {duration: this.oOptions.overlayDuration}).hide(),
			divHidBox: this.divHidBox.effects({duration: this.oOptions.resizeDuration, transition: Fx.Transitions.sineInOut, onComplete: nextEffect})
      };

	},


   /* Alter webpage anchors. */
   alterAnchors: function() {

      /* Array with webpage anchors. */
      this.aAnchors = [];

      /* Walk through all page anchors. */
		$A($$('a')).each(function(oAnchor){

         /* Find anchors with rel attributes starting with "hidBox". */
         if(oAnchor.rel && oAnchor.href && oAnchor.rel.test('^hidBox', 'i')) {

            /* Add onclick event to the specific anchor. */
				oAnchor.addEvent('click', function (oEvent) {

               // Retrieve "onclick event".
               oEvent = new Event(oEvent);

               // Stop click action (prevent href to be fired).
               oEvent.stop();

               // Call class "click" method when the anchor is clicked.
               this.click(oAnchor);

            }.bind(this));

            // Add anchor to anchor array.
				this.aAnchors.push(oAnchor);

			}

      }, this);

   },


   /* Called when the user clicks the specific anchor. */
   click: function(oLink) {

      // Open the hidBox.
      return this.open (oLink.href, oLink.title, oLink.rel);

	},


   /* Open the hidBox. */
	open: function(sLinkHref, sLinkTitle, sLinkRel) {

	   /* This is step 1 of the process. */
      this.step = 1;

      /* Link to the requested object. */
      this.href = sLinkHref;

      /* Title of the link. */
      this.title = sLinkTitle;

      /* Rel of the link. */
      this.rel = sLinkRel;

      /* Setup overlay position. */
		this.overlayPosition();

		/* Setup hidBox position and dimension. */
		this.hidBoxPosition();

      /* Start overlay animation (clear to x% transparency). */
		this.fx.divOverlay.start(this.oOptions.overlayTransparency);

		/* Add loading animation to the hidBox. */
		if (this.oOptions.loadingAnimation == 1) {
         this.divHidBox.setStyle('background', this.oOptions.hidBoxBackground + ' url(/js/tools/hidBox/1-0-0/images/loading.gif) no-repeat center');
		}

		/* Determine content type. */
      var aOptions = this.rel.match(/[A-z]+/g);
      this.oOptions.contentType = aOptions[1];
      
		/* Load inner element. */
      this.loadContent();

		/* Start resizing the height of the hidBox. */
      this.fx.divHidBox.start({'height': [this.oOptions.requiredHeight], 'marginTop' : [this.oOptions.requiredHeight / -2]});

   },


	/* Position the overlay. */
   overlayPosition: function(){

      /* Retrieve the current top position (calculating with scrollbar). */
      var iTop = window.getScrollTop() + 'px';

      /* Retrieve height. */
      if (window.opera) {
         var iHeight = window.innerHeight + 'px';
      } else {
         var iHeight = window.getHeight() + 'px';
      }

      /* Set overlay style (top offset and height). */
      this.divOverlay.setStyles({'top': iTop, 'height': iHeight});

   },


   /* Position the hidBox. */
	hidBoxPosition: function(){

	   /* Retrieve requested dimensions from "rel" anchor attribute in an array. */
      var aDimensions = this.rel.match(/[0-9]+/g);

      /* Set the box width & height. If no dimensions were supplied, use the default dimensions. */
      this.oOptions.requiredWidth  = (aDimensions && (aDimensions[0] > 0)) ? aDimensions[0] : this.oOptions.defaultWidth;
      this.oOptions.requiredHeight = (aDimensions && (aDimensions[1] > 0)) ? aDimensions[1] : this.oOptions.defaultHeight;

      /* Retrieve the current top position (calculating with scrollbar). */
      if (window.opera) {
         this.top = ((window.getScrollTop() + (window.innerHeight / 2))) - this.oOptions.offsetTop;
      } else {
         this.top = ((window.getScrollTop() + (window.getHeight() / 2))) - this.oOptions.offsetTop;
      }

      /* Set hidBox top offset and display the element. */
      this.divHidBox.setStyles({top: this.top + 'px', display: ''});

      /* */
	},



	loadContent: function() {

	   /* Select content type and corresponding action. */
	   switch(this.oOptions.contentType) {

	      /* Image. */
         case 'img':

            // "Preload" image.
            this.oOptions.oInnerHTML = '<img src="' + this.href + '" alt="' + this.title + '"  title="' + this.title + '" />'

            // End of image case.
            break;

	      /* Flash video (flv). */
         case 'flv':

            // Initialise JWPlayer to display flash video movie.
            this.oOptions.oPlayer = new SWFObject("/js/tools/jwplayer/player-viral.swf", "ply", this.oOptions.requiredWidth, this.oOptions.requiredHeight, "9", this.oOptions.hidBoxBackground);
            this.oOptions.oPlayer.addParam("allowfullscreen","true");
            this.oOptions.oPlayer.addParam("type","video");
            
            //this.oOptions.oPlayer.addParam("allownetworking","all");
            //this.oOptions.oPlayer.addParam("autostart","true");
            //this.oOptions.oPlayer.addParam("allowscriptaccess","always");
            this.oOptions.oPlayer.addParam("flashvars","file=/js/tools/jwplayer/earth.flv&autostart=" + this.oOptions.oPlayerAutostart + "&type=video&displayclick=none&quality=true");

            // End of flash movie case.
            break;

         /* YouTube. */
         case 'youtube':

            // Find youtube video id.
            var aVideo = this.href.split('=');
            var iVideoId = aVideo[1];

            // Setup Youtube flash player.
            this.oOptions.oPlayer = new SWFObject("http://www.youtube.com/v/" + iVideoId, "flvvideo", this.oOptions.requiredWidth, this.oOptions.requiredHeight, "0");
            this.oOptions.oPlayer.addParam("wmode", "transparent");

            // End of YouTube case.
            break;

         /* Inner HTML. */
         case 'innerhtml':

            // Create innerhtml object.
            this.oOptions.oInnerHTML = '<iframe src="' + this.href + '" style="border: 0px; width: ' + this.oOptions.requiredWidth + 'px; height: ' + this.oOptions.requiredHeight + 'px;"></iframe>';

            // End of innerHTML case.
            break;

	   }

   },


   /* Start the next effect in the list. */
	nextEffect: function() {

      // Determine the next effect based on the phase we're currently in.
      switch (this.step++) {

         // Phase 1; User clicked to open the window, need to set up hidBox dimension.
         case 1:

            // Setup the width of the hidBox.
            this.fx.divHidBox.start({'width': [this.oOptions.requiredWidth], 'marginLeft': [this.oOptions.requiredWidth / -2]});

            // End case.
            break;

         // Phase 2; The window is opened and ready for use, insert content.
         case 2:

            // Calculate margins for close button.
            if (window.opera) {
               var iCloseLeft = (window.getWidth() / 2) + (parseInt(this.oOptions.requiredWidth) / 2) + 10;
               var iCloseTop  = window.getScrollTop() + ((window.innerHeight / 2) - (this.oOptions.requiredHeight / 2) - 18);
            } else {
               var iCloseLeft = (window.getWidth() / 2) + (parseInt(this.oOptions.requiredWidth) / 2) + 10;
               var iCloseTop  = window.getScrollTop() + ((window.getHeight() / 2) - (this.oOptions.requiredHeight / 2) - 18);// - ($('hidBox').style.requiredHeight / 2);
            }

            // Display close button.
            this.butClose.setStyle('marginLeft', iCloseLeft + 'px');
            this.butClose.setStyle('marginTop', iCloseTop + 'px');
            this.butClose.setStyle('display', '');

            /* Select item to display. */
            switch(this.oOptions.contentType) {

               /* Display image. */
               case 'img':
                  $('hidBox').innerHTML = this.oOptions.oInnerHTML;
                  break;

               /* Flash video (flv), display JWPlayer. */
               case 'flv':
                  this.oOptions.oPlayer.write('hidBox');
                  break;

               /* YouTube. */
               case 'youtube':
                  this.oOptions.oPlayer.write('hidBox');
                  break;

               /* Inner HTML (iframe). */
               case 'innerhtml':
                  $('hidBox').innerHTML = this.oOptions.oInnerHTML;
                  break;

            }

            // Reset the background (remove loading images).
            this.divHidBox.setStyle('background', this.oOptions.hidBoxBackground);

            // End of case 2.
            break;

      }

   },


   /* Close hidBox. */
   close: function() {

      /* Remove close button. */
      this.butClose.style.display = 'none';

      /* Transform overlay back to 0 transparancy. */
      this.fx.divOverlay.start(0);

      /* Remove all hidBox inner HTML. */
      this.divHidBox.innerHTML = '';
      this.divHidBox.style.display = 'none';

      /* Return false. */
      return false;

   }


};

/* Load hidBox when the dom is ready loading. */
window.addEvent('domready', hidBox.init.bind(hidBox));