/** *************************************************************************************
 * "Pop-up window" emulator using Javascript and CSS.
 *
 * @author Justin Spargur
 * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
 ************************************************************************************* **/

// Note: Be sure to add the following attributes to your body tag.
// onload="initPopUpElements()"
// onresize="resetPageDimensions()"

/*********************************************************************
 * Below are the variables you can edit for this script. If you'd    *
 * like to modify the script more, feel free but do so at your own   *
 * risk.                                                             *
 *********************************************************************/

// Initialize the popup content var.
var popUpContent = "";

// Boolean switch for pop-up
//var popUpIsOpen = false;

var maskOpacity          = 80;                  // in percent. 90 = 90% visible. Default is 80.
var popUpDelay           = 250;                 // In milliseconds. Default is 500.
var maskBGColor          = "#000000";           // Default is gray

var startPopUpWidth      = 3;
var startPopUpHeight     = 3;

var stopPopUpWidth       = 2;
var stopPopUpHeight      = 2;

/** *******************************************************************
 *                    DO NOT EDIT BELOW THIS LINE                     *
 ******************************************************************* **/

// Resizing delay
var growthDelay = 5;
// Used for getting content via AJAX.
var popUpURL = "popUp.php";

var viewableScreenWidth;
var viewableScreenHeight;
var myMask;
var popWindow;

// Variable used to disable/enable scrolling
// without jumping all over the page.
var lastYVal;

var closeBtnContent = "<div class=\"popUpCloseBtn\"><a href=\"#\" onclick=\"hidePopUp(); return false\">X</a></div>";

/*******************************
 * Function to initialize the  *
 * necessary variables and to  *
 * create the elements used in *
 * the "pop-up".               *
 *******************************/
function initPopUpElements()
{
   // Set defaults for required variables.
   if(empty(maskOpacity))
      maskOpacity = 90;
   if(empty(popUpDelay))
      popUpDelay = 500;
   if(empty(maskBGColor))
      maskBGColor = "#333";

   lastYVal = 0;

   // Create the mask
   myMask = document.createElement( "div" );
   setWindowDimensions();

   // Set permanent mask attributes
   myMask.id = "myMask";
   myMask.style.backgroundColor = maskBGColor;
   myMask.style.position = "absolute";
   myMask.style.display = "none";
   opacity("myMask", 100, 0, 1)

   // Set permanent pop-up attributes
   popWindow = document.createElement( "div" );
   popWindow.id = "popUpWindow";
   popWindow.style.position = "absolute";
   popWindow.style.display = "none";
   popWindow.style.overflow = "auto";

   // Add onResize event listener.
   window.onresize = function() { resetPageDimensions() };

   // Set dynamic attributes
   // for new elements
   setMaskAttributes();

   // Add content to the pop-up window.
   popWindow.innerHTML = closeBtnContent + "<div class=\"loadingPopup\" >loading</div>";

   // Add elements to the DOM
   document.body.appendChild(myMask);
   document.body.appendChild(popWindow);
   
   
   // Time to find the pop-up links!
   var myLinks = document.body.getElementsByTagName("a");
   for(var a = 0; a < myLinks.length; a++)
   {
      if(myLinks[a].className.indexOf("popUp") != -1)
      {
         var gotoPage = myLinks[a].href;
         myLinks[a].href = "javascript: startPopUp('" + gotoPage + "');";
      }
   }
   
   //showPopUp(); return false
}

/****************************
 * Function to check for    *
 * uninitialized variables. *
 ****************************/
function empty(variable)
{
   if(variable == "" || variable == undefined)
      return true;
   return false;
}

/****************************
 * Function to get viewable *
 * window dimensions.       *
 ****************************/
function setWindowDimensions()
{
   if (document.documentElement)
   {
      var dombody = document.body;
      if ((document.body.clientHeight == document.body.offsetHeight) &&
          (document.body.offsetHeight == document.body.scrollHeight))
      {
         dombody = document.documentElement;
      }
      if ((document.body.clientHeight == 0) &&
          (document.documentElement.clientHeight > 0))
      {
         dombody = document.documentElement;
      }

      viewableScreenWidth = dombody.clientWidth;
      viewableScreenHeight = dombody.clientHeight;
   }
   else
   {
      viewableScreenWidth = window.screen.width;
      viewableScreenHeight = window.screen.height;
   }
   return true;
}

/****************************
 * Function to set dynamic  *
 * mask attributes.         *
 ****************************/
function setMaskAttributes()
{
   myMask.style.height =  viewableScreenHeight + "px";
   myMask.style.width = viewableScreenWidth+30 + "px";

   myMask.style.top = getCurrentTop() + "px";

   myMask.style.left = "0px";

   setPopupAttributes();
}

/****************************
 * Function to set dynamic  *
 * pop-up attributes.       *
 ****************************/
function setPopupAttributes()
{
   popWindow.style.width = (parseInt(viewableScreenWidth/startPopUpWidth)) + "px";
   popWindow.style.height = (parseInt(viewableScreenHeight/startPopUpHeight)) + "px";

   popWindow.style.top = (parseInt(getCurrentTop() +
                         (viewableScreenHeight/4))) + "px";
   //popWindow.style.top = (parseInt((viewableScreenHeight/4))) + "px";

   popWindow.style.left = (parseInt(viewableScreenWidth/3)) + "px";
}

/*******************************
 * Function to get the current *
 * scrolled position.          *
 *******************************/
function getCurrentTop()
{
   var currentTop = 0;
   if( typeof( window.pageYOffset ) == 'number' )
      currentTop = window.pageYOffset;
   else if( document.body && ( document.body.scrollLeft ||
                               document.body.scrollTop ) )
      currentTop = document.body.scrollTop;
   else if( document.documentElement &&
            ( document.documentElement.scrollLeft ||
              document.documentElement.scrollTop
            )
          )
      currentTop = document.documentElement.scrollTop;
   return currentTop;
}

/*******************************
 * Function to display the     *
 * pop-up window.              *
 *******************************/
function showPopUp()
{
   lastYVal = getCurrentTop();
   setMaskAttributes()
   opacity("myMask", 0, maskOpacity, popUpDelay);
   document.body.style.overflow = "hidden";
   window.scrollTo(0,lastYVal);
   myMask.style.top = getCurrentTop() + "px";
   //myMask.style.top = 0 + "px";

   myMask.style.display = "block";
   popWindow.style.display = "block";
   window.scrollTo(0,lastYVal);
   
   growPopUpWidth((parseInt(popWindow.style.width)), (parseInt(viewableScreenWidth/stopPopUpWidth)));
   
   return;
}

/*******************************
 * Function to hide the        *
 * pop-up window.              *
 *******************************/
function hidePopUp()
{
   //popUpIsOpen = true;

   popWindow.style.display = "none";
   opacity("myMask", maskOpacity, 0, popUpDelay);
   myMask.style.display = "none";

   document.body.style.overflow = "auto";
   window.scrollTo(0,lastYVal);

   popWindow.innerHTML = "<div class=\"loadingPopup\" ></div>";
   ungrowPopUp();
   return;
}

/************************************
 * Function to adjust for resizing. *
 ************************************/
function resetPageDimensions()
{
   if(setWindowDimensions())
      setMaskAttributes();
}

/*********************************
 * Function to fade in the mask. *
 *********************************/
function opacity(id, opacStart, opacEnd, millisec)
{
   //speed for each frame
   var speed = Math.round(millisec / 100);
   var timer = 0;

   //determine the direction for the blending, if start and end are the same nothing happens
   if(opacStart > opacEnd)
   {
      for(i = opacStart; i >= opacEnd; i--)
      {
         setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed));
         timer++;
      }
   }
   else if(opacStart < opacEnd)
   {
      for(i = opacStart; i <= opacEnd; i++)
      {
         setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed));
         timer++;
      }
   }
}

/**************************************
 * Function to help fade in the mask. *
 **************************************/
function changeOpac(opacity, id)
{
   var object = document.getElementById(id).style;
   object.opacity = (opacity / 100);
   object.MozOpacity = (opacity / 100);
   object.KhtmlOpacity = (opacity / 100);
   object.filter = "alpha(opacity=" + opacity + ")";
}

/****************************************
 * Function to initialize the "pop-up". *
 ****************************************/
function startPopUp(contentLocation)
{
   // We temporarily hide any overflow
   // while opening the pop-up window.
   popWindow.style.overflow = "hidden";
   
   // Make sure the content is shown as loading.
   popWindow.innerHTML = closeBtnContent + "<div class=\"loadingPopup\" >loading</div>";

   // Create AJAX object
   var myAjax = new Ajax(popUpURL, loadContent);
   myAjax.returnType = "full";

   // Send AJAX call.
   myAjax.send("content="+encodeURI(getFileName(contentLocation)), "GET");

   // While we wait for the return from the AJAX object,
   // we'll go ahead and open the pop-up window.
   showPopUp();
}

/****************************************
 * Function called when the AJAX object *
 * returns a value.                     *
 ****************************************/
function loadContent(response, status)
{
   // If we have a valid return, then we
   // populate the pop-up window.
   if(status == 200)
   {
      popUpContent = response;
      //while(!popUpIsOpen)
      //{
      //   continue;
      //}

      // Load content
      popWindow.innerHTML = closeBtnContent +
                            popUpContent;

      //showPopUp();
   }
   // If we got an invalid return, then
   // we tell the user that there was an error.
   else
      popWindow.innerHTML = closeBtnContent +
                               "<h2>ERROR</h2><p><em>Unable to retrieve content.</em></p>";
}


/****************************************
 * Function used to parse a file name   *
 * from a URL.                          *
 ****************************************/
function getFileName(fullURL)
{
   // Get rid of the query string.
   var parts = fullURL.split('\?');
   // Get rid of host/directory info.
   parts = parts[0].split('/');

   // Return the file name.
   return parts[(parts.length-1)];
}


/******************************************
 * Function used to increase the width of *
 * the pop-up window.                     *
 ******************************************/
function growPopUpWidth(currentWidth, stopWidth)
{
   // Figure out what the current left position is.
   currentPopUpPosition = (parseInt(popWindow.style.left));
   // Adjust the width.
   currentWidth = currentWidth + 20;
   // Adjust the left position.
   currentPopUpPosition-=10;

   // Apply the new values to the style attributes.
   popWindow.style.width = currentWidth + "px";// + "px";
   popWindow.style.left  = currentPopUpPosition + "px";

   // If we're not done growing wider, then
   // we call the function again.
   if(currentWidth < stopWidth)
   {
      timeoutString = "growPopUpWidth("+currentWidth+","+stopWidth+")";
      setTimeout(timeoutString, growthDelay);
   }
   // Otherwise, we start to grow taller.
   else
   {
      setTimeout("growPopUpHeight("
                  +(parseInt(popWindow.style.height))
                  +","
                  +(parseInt(viewableScreenHeight/stopPopUpHeight))
                  +")", growthDelay);
   }
}

/*******************************************
 * Function used to increase the height of *
 * the pop-up window.                      *
 *******************************************/
function growPopUpHeight(currentHeight, stopHeight)
{
   // Figure out what the current top position is.
   currentPopUpPosition = (parseInt(popWindow.style.top));
   // Adjust the height.
   currentHeight = currentHeight + 20;
   // Adjust the top position.
   currentPopUpPosition-=10;

   // Apply the new values to the style attributes.
   popWindow.style.height = currentHeight+ "px";// + "px";
   popWindow.style.top  = currentPopUpPosition + "px";

   // If we're not done growing taller, then
   // we call the function again.
   if(currentHeight < stopHeight)
   {
      timeoutString = "growPopUpHeight("+currentHeight+","+stopHeight+")";
      setTimeout(timeoutString, growthDelay);
   }
   // When we're all done growing, we turn
   // overflow back on.
   else
   {
      popWindow.style.overflow = "auto";
   }
}

/*******************************************
 * Function used to reset the dimensions   *
 * of the pop-up window.                   *
 *******************************************/
function ungrowPopUp()
{
   popWindow.style.width = (parseInt(viewableScreenWidth/startPopUpWidth)) + "px";
   popWindow.style.height = (parseInt(viewableScreenHeight/startPopUpHeight)) + "px";
}