/**
 * Contains JQuery based JS to be loaded into all pages
 * which use main layout. 
 * 
 * @author Tom Brown <tombrown86@googlemail.com>
 */

var loadedLayers = new Array();

/**
* This calls grayOutAndDisplay with the layer specified. It also sets the close
* operation on an elem with class name "close_popup".
* If loadAjaxOnce, then the layerId is stored so the ajax call is only made once.
* If an ajax URL is specified and the ajax content hasn't already been loaded,
* then the content of elem with class "popup_content" in the layer is loaded from the url.
*
* The layer with layerId is expected to have divs with class names 'popup_content'
* and 'close_popup'.
*
* @param string - layerId - id of element in which to load ajax content
* @param string - ajaxUrl - URL which to send ajax GET request
* @param boolean - loadAjaxOnce - true if content is only loaded once
* @param function - onLoadFunction - called when ajax content is loaded
* @param function - onCloseFunction - called when ajax content layer is closed 
*/
function grayOutAndDisplayLayer(layerId, ajaxUrl, loadAjaxOnce, onLoadFunction, onCloseFunction)
{
	// If loadAjaxOnce, only load ajax content if 
	// loadedLayers dosn't contain layerId
	if(!loadAjaxOnce || !array_contains(loadedLayers, layerId))
	{
		loadedLayers[loadedLayers.length] = layerId;
		if(ajaxUrl != null) $("#"+layerId+" .popup_content").load(ajaxUrl, {'isAjaxReq' : true}, onLoadFunction);
	}
	grayOutAndDisplay(true, layerId);
	$("#"+layerId+" .close_popup").click(function(){
		grayOutAndDisplay(false, layerId);
		if(onCloseFunction != undefined)
		{
			onCloseFunction();
		}
	});
}


/**
* This function grays out the entier page apart from any element with id visibleElements
* or with an id in the array visibleElements.
*
* Code has been taken from http://www.hunlock.com/blogs/Snippets:_Howto_Grey-Out_The_Screen
* and has been modified to display visibleElements and hideAllOverlays.
*/
function grayOutAndDisplay(vis, visibleElements, hideAllOverlays, options) {
  // Pass true to gray out screen, false to ungray
  // options are optional.  This is a JSON object with the following (optional) properties
  // opacity:0-100         // Lower number = less grayout higher = more of a blackout 
  // zindex: #             // HTML elements with a higher zindex appear on top of the gray out
  // bgcolor: (#xxxxxx)    // Standard RGB Hex color code
  // grayOut(true, {'zindex':'50', 'bgcolor':'#0000FF', 'opacity':'70'});
  // Because options is JSON opacity/zindex/bgcolor are all optional and can appear
  // in any order.  Pass only the properties you need to set.
  var options = options || {}; 
  var zindex = options.zindex || 50;
  var opacity = options.opacity || 70;
  var opaque = (opacity / 100);
  var bgcolor = options.bgcolor || '#000000';
  var dark=document.getElementById('darkenScreenObject');
  if (!dark) {
    // The dark layer doesn't exist, it's never been created.  So we'll
    // create it here and apply some basic styles.
    // If you are getting errors in IE see: http://support.microsoft.com/default.aspx/kb/927917
    var tbody = document.getElementsByTagName("body")[0];
    var tnode = document.createElement('div');           // Create the layer.
        tnode.style.position='absolute';                 // Position absolutely
        tnode.style.top='0px';                           // In the top
        tnode.style.left='0px';                          // Left corner of the page
        tnode.style.overflow='hidden';                   // Try to avoid making scroll bars            
        tnode.style.display='none';                      // Start out Hidden
        tnode.id='darkenScreenObject';                   // Name it so we can find it later
    tbody.appendChild(tnode);                            // Add it to the web page
    dark=document.getElementById('darkenScreenObject');  // Get the object.
  }
  if (vis) {
    // Calculate the page width and height 
    if( document.body && ( document.body.scrollWidth || document.body.scrollHeight ) ) {
        var pageWidth = document.body.scrollWidth+'px';
        var pageHeight = document.body.scrollHeight+'px';
    } else if( document.body.offsetWidth ) {
      var pageWidth = document.body.offsetWidth+'px';
      var pageHeight = document.body.offsetHeight+'px';
    } else {
       var pageWidth='100%';
       var pageHeight='100%';
    }   
    //set the shader to cover the entire page and make it visible.
    dark.style.opacity=opaque;                      
    dark.style.MozOpacity=opaque;                   
    dark.style.filter='alpha(opacity='+opacity+')'; 
    dark.style.zIndex=zindex;        
    dark.style.backgroundColor=bgcolor;  
    dark.style.width= pageWidth;
    dark.style.height= pageHeight;
    dark.style.display='block';				 
  } else {
     dark.style.display='none';
  }

  if(hideAllOverlays != undefined && hideAllOverlays)
  {
  	$(".overlay_layer").css({"display":"none"});
  }

  // Now display (or hide) visibleElements, and set appropriate zindex's
  if(!isArray(visibleElements))
  {
  	visibleElements = [visibleElements];
  }
  for(elem in visibleElements)
  {
  	if(vis)
  	{
  		// Calculate appropriate Y position from layer width
  		var elemWidth = $("#"+visibleElements[elem]).width();
  		var containerWidth = $("#"+"container").width();
  		var yPositionOffset = (containerWidth-elemWidth)/2;
		var moveX = findPosX(document.getElementById("container")) + yPositionOffset;
		// Find top of current scroll position (or use container if can't get property)
		if (document.documentElement && document.documentElement.scrollTop)
			var top = document.documentElement.scrollTop;
		else if (document.body && document.body.scrollTop)
			var top = document.body.scrollTop
		else
			top = findPosY(document.getElementById("container"));
		var moveY = top + 60;
		$("#" + visibleElements[elem]).css({'top' : moveY + "px", 'left' : moveX + "px", 'display': 'block', 'z-index': ++zindex});
	}
	else
	{
		$("#" + visibleElements[elem]).css({'display' : 'none'});
	}
  }
}


/*
* Returns true of obj is an array
*/
function isArray(obj)
{
   if (obj.constructor.toString().indexOf("Array") == -1)
      return false;
   else
      return true;
}


function findPosX(obj)
{
  var curleft = 0;
  if(obj.offsetParent)
      while(1) 
      {
        curleft += obj.offsetLeft;
        if(!obj.offsetParent)
          break;
        obj = obj.offsetParent;
      }
  else if(obj.x)
      curleft += obj.x;
  return curleft;
}

function findPosY(obj)
{
  var curtop = 0;
  if(obj.offsetParent)
      while(1)
      {
        curtop += obj.offsetTop;
        if(!obj.offsetParent)
          break;
        obj = obj.offsetParent;
      }
  else if(obj.y)
      curtop += obj.y;
  return curtop;
}

/**
* Returns true if array contains value
*/
function array_contains(array, value)
{
	for(key in array)
	{
		if(array[key] == value)
			return true
	}
	return false;
}