// NSW Department of Environment and Climate Change
// Education for sustainability (EFS) DotNetNuke skin - Javascript functions
// See CSS for history, contact details

/*  External site dialog/frame values */

/*  constants  */
var ATTACHOPTION_OFF    = 0;
var ATTACHOPTION_DIALOG = 1;
var ATTACHOPTION_FRAME  = 2;

/*  current selection for automatic behaviour of external links  */
var attachExternalSiteWarning = ATTACHOPTION_OFF;  
var addExternalLinkImage = true;
var addImageShadow = true;

/*  need to change this to the actual page with the frame module on it */
var FRAME_URL = 'http://demo.inventua.com/oeilt/default.aspx?tabid=904';  
/*var FRAME_URL = 'http://www.livingthing.net.au/go/default.aspx?tabid=123';  */


/*  Resize widget values  */
var resizeIncrements = 0;
var baseSize = 100;

//---------------------------------------------------------------------------------------------
//   Widget (resize) button code
//---------------------------------------------------------------------------------------------
function resizeUp() 
{
  var ctlWrapper = document.getElementById('cim_page-wrapper');

	if (!ctlWrapper.style.fontSize)
	{
	  resizeIncrements=1;
	}
	else 
	{
	resizeIncrements++;
	}
	resizecheckLimit();
	var num_newsize = baseSize * ((0.1 * resizeIncrements)+1);
	ctlWrapper.style.fontSize = num_newsize + '%';
	
	Set_Cookie( 'oeilt_fontsize', ctlWrapper.style.fontSize, 7, '/', '', '' ) 
	
	if (addImageShadow)
	  setShadowPosition();
}

function resizecheckLimit()
{
  if (resizeIncrements < -7) resizeIncrements = -7;
  if (resizeIncrements > 7) resizeIncrements = 7;
}

function resizeZero() 
{
	resizeIncrements=0;
	document.getElementById('cim_page-wrapper').style.fontSize = baseSize + '%';
	
	Set_Cookie( 'oeilt_fontsize', document.getElementById('cim_page-wrapper').style.fontSize, 7, '/', '', '' ) 
	
	if (addImageShadow)
	  setShadowPosition();
}

function resizeDown() 
{
  var ctlWrapper = document.getElementById('cim_page-wrapper');
  
	if (!ctlWrapper.style.fontSize)
	{
		resizeIncrements=-1;
	}
	else 
	{
	  resizeIncrements--;	
	}
	resizecheckLimit();
	var num_newsize = baseSize * ((0.1 * resizeIncrements)+1);
	ctlWrapper.style.fontSize = num_newsize + '%';
	
	Set_Cookie( 'oeilt_fontsize', ctlWrapper.style.fontSize, 7, '/', '', '' ) 
	
	if (addImageShadow)
	  setShadowPosition();
} 

function Set_Cookie( name, value, expires, path, domain, secure ) 
{
  // set time, it's in milliseconds
  var today = new Date();
  today.setTime( today.getTime() );

  if ( expires )
  {
    expires = expires * 1000 * 60 * 60;  // expires is in days
  }
  var expires_date = new Date( today.getTime() + (expires) );

  document.cookie = name + "=" +escape( value ) +
    ( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) + 
    ( ( path ) ? ";path=" + path : "" ) + 
    ( ( domain ) ? ";domain=" + domain : "" ) +
    ( ( secure ) ? ";secure" : "" );
}

function Get_Cookie( check_name ) 
{
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f
	
	for ( i = 0; i < a_all_cookies.length; i++ )
	{
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );
		
		
		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');
	
		// if the extracted name matches passed check_name
		if ( cookie_name == check_name )
		{
			b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if ( a_temp_cookie.length > 1 )
			{
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found )
	{
		return null;
	}
}				

//---------------------------------------------------------------------------------------------


//---------------------------------------------------------------------------------------------
//   OnLoad general, Image shadowing & external link icon code
//---------------------------------------------------------------------------------------------

function setupFormatPage()
{
  window.setTimeout('formatPage()', 200);
}
  
function addLoadEvent(func) 
{
	var oldonload = window.onload;
	if (typeof window.onload != 'function') 
	{
		window.onload = func;
	} 
	else 
	{
		window.onload = function() 
		{
			if (oldonload) 
			{
				oldonload();
			}
			func();
		}
	}
}

// Photo gradient border code - just put class="photo-shadow" and this code will run
var shadowedImages = new Array(0);
var shadowColours = new Array ('#cfcfcf','#dadada', '#e3e3e3', '#ebebeb','#f1f1f1', '#f6f6f6', '#fafafa', '#fcfcfc');
addLoadEvent (setupFormatPage);

function formatPage()
{
  var intControlIndex=0;
  var drawShadowFunc = drawShadow;
  var detectExternalLinksFunc = detectExternalLinks;
  var enableButtonsFunc = enableButtons;
  var objContentElement = document.getElementById('ContentArea');
  //var objContentParentElement = objContentElement.parentElement;
    
  if ( Get_Cookie( 'oeilt_fontsize' ) )
  {
    document.getElementById('cim_page-wrapper').style.fontSize = Get_Cookie( 'oeilt_fontsize' );
  }

  // Draw the external link icons
  if (addExternalLinkImage)
  {
    var objElementArray2 = document.getElementsByTagName ? objContentElement.getElementsByTagName('a') : document.all['ContentArea'].tags('a');
    for (intControlIndex = 0; intControlIndex < objElementArray2.length; intControlIndex++) 
    {
 	    detectExternalLinksFunc(objElementArray2[intControlIndex]); 	
    }
  }
  
  if (addImageShadow)
  {
    // Draw the shadow graphics
    var objElementArray1 = document.getElementsByTagName ? objContentElement.getElementsByTagName('img') : document.all['ContentArea'].tags('img');
    for (intControlIndex = 0; intControlIndex < objElementArray1.length; intControlIndex++) 
    {
 	    if (objElementArray1[intControlIndex].className.indexOf('photo-shadow') >= 0) 
 	    {
 	      if (objElementArray1[intControlIndex].style.display != 'none')
  		    drawShadowFunc(objElementArray1[intControlIndex]);
 	    } 	  
    }  
  }
  
  // Enable the widget controls
  if (document.getElementById('top_widget-line'))
  {
    var objElementArray3 = document.getElementsByTagName ? document.getElementById('top_widget-line').getElementsByTagName('a') : document.all['top_widget-line'].tags('a');
    for (intControlIndex = 0; intControlIndex < objElementArray3.length; intControlIndex++) 
    {
 	    enableButtonsFunc(objElementArray3[intControlIndex]);
    }  
  }
  
  // Widget controls - special case for the home page
  if (document.getElementById('HomeTopWidgetLine'))
  {
    var objElementArray5 = document.getElementsByTagName ? document.getElementById('HomeTopWidgetLine').getElementsByTagName('a') : document.all['HomeTopWidgetLine'].tags('a');
    for (intControlIndex = 0; intControlIndex < objElementArray5.length; intControlIndex++) 
    {
 	    enableButtonsFunc(objElementArray5[intControlIndex]);
    }  
  }
  
  var objElementArray4 = document.getElementsByTagName ? document.getElementById('bottom_widget-line').getElementsByTagName('a') : document.all['bottom_widget-line'].tags('a');
  for (intControlIndex = 0; intControlIndex < objElementArray4.length; intControlIndex++) 
  {
 	  enableButtonsFunc(objElementArray4[intControlIndex]);
  }  
  
  if (addImageShadow)
  {
    setShadowPosition();   
    window.onresize=function() {setShadowPosition();}   
  }
}

function enableButtons(linkElement)
{
  if (linkElement.className.indexOf('widget_button') >= 0)
    linkElement.style.display='inline'; 
}

function detectExternalLinks(linkElement)
{
  var linkUrl = linkElement.href.toLowerCase();
  var linkClassName = linkElement.className;
  var linkScheme;
  var isExternalLink=false;
  
  if (linkElement.href && linkElement.href.split('//').length>0)
    linkScheme=linkElement.href.split('//')[0].toLowerCase();
  else
    return;
      
  if (linkScheme == 'mailto:')
  {
    if (linkElement.className.indexOf('mail-link') < 0 && linkElement.className.indexOf('noautoclass') < 0)
    {
      if ((linkClassName) && linkClassName != '')
        linkElement.className = linkElement.className + ' mail-link';
      else
        linkElement.className = linkElement.className + 'mail-link';
        
      isExternalLink=true;
    }
  }
  if (linkScheme == 'http:' && linkUrl.indexOf('livingthing') < 0  && linkUrl.indexOf('oeilt') < 0)
  {    
    if (linkClassName.indexOf('external-link') < 0 && linkClassName.indexOf('noautoclass') < 0)
    {
      if (!(linkElement.childNodes) || linkElement.childNodes.length == 0 || !(linkElement.childNodes[0].tagName) || linkElement.childNodes[0].tagName.toLowerCase() != 'img')
      {
        if ((linkClassName) && linkClassName != '')
          linkElement.className = linkElement.className + ' external-link';
        else  
          linkElement.className = linkElement.className + 'external-link';
      }
      isExternalLink=true;
    }
    
    if (isExternalLink)
    {
      // attach link tracker/external target event handler
      if (attachExternalSiteWarning==ATTACHOPTION_DIALOG)
        attachExternalLinkDialog(linkElement)
      else if (attachExternalSiteWarning==ATTACHOPTION_FRAME)
        attachFrameCode(linkElement)
      else
      {
        linkElement.onclick = function () 
        {
          // The navigateExternal function is generated in the ExternalLinkTracker skin object
          navigateExternal(this); 
          return false;
        }    
      }
    }
  }  
}

function GetModuleId(element)
{
  // attempts to detect the module ID of the passed-in DHTML element by moving up the DHTML tree
  // until it finds one with an id of 'dnn_ctrNNNN'.  The NNNN part is the module id.  If no match is found,
  // return -1
  var parent = element.parentNode;
  var splitVal;
  
  while (parent && parent.id)
  {
    if (parent.id.indexOf('dnn_ctr') >= 0)
    {
      splitVal = parent.id.substring(7);
      if (splitVal.indexOf('_') >= 0)      
        return splitVal.substring(0, splitVal.indexOf('_'));
    }
    parent = parent.parentNode;
  }  
  return -1;
}

// Used by external link tracker
function URLEncode (clearString) 
{
  var output = '';
  var x = 0;
  clearString = clearString.toString();
  var regex = /(^[a-zA-Z0-9_.]*)/;
  while (x < clearString.length) 
  {
    var match = regex.exec(clearString.substr(x));
    if (match != null && match.length > 1 && match[1] != '') 
    {
    	output += match[1];
      x += match[1].length;
    } 
    else 
    {
      if (clearString[x] == ' ')
        output += '+';
      else 
      {
        var charCode = clearString.charCodeAt(x);
        var hexVal = charCode.toString(16);
        output += '%' + ( hexVal.length < 2 ? '0' : '' ) + hexVal.toUpperCase();
      }
      x++;
    }
  }
  return output;
}

function navigateParentTarget(node)
{
  window.open(node.getAttribute('href'), node.getAttribute('target'));
}

function drawShadow(photoImage)
{  
  var parentTag = photoImage.parentNode.tagName.toLowerCase();
  
  for (intLineIndex=shadowColours.length-1; intLineIndex >= 0; intLineIndex--)
  {
    var newSd = document.createElement("div")
    newSd.className = "photo-shadow-outer"
    // Each shadow DIV has an id of "shadowL_intIndex" (L=index of target element, X=index of shadow (depth) 
    newSd.id='shadow' + shadowedImages.length + '_' + intLineIndex; 
    newSd.style.borderColor = shadowColours[intLineIndex]; 
    newSd.style.borderStyle = 'solid';
    newSd.style.borderWidth = '1px';
    
    // In FF, if the IMG is inside an A element, the photo shadows block mouse clicks, this is to compensate
    if (parentTag == 'a')
    {
      newSd.setAttribute('href', photoImage.parentNode.href);
      newSd.setAttribute('target', photoImage.parentNode.target);
      newSd.onclick= function () {navigateParentTarget(this); return false;}
    }
    
    photoImage.offsetParent.appendChild(newSd);
  }
  
  shadowedImages[shadowedImages.length]=photoImage;  
}

function setShadowPosition()
{
  if (shadowedImages.length>0)  
  {
    for (var intShadowIndex=0; intShadowIndex<shadowedImages.length; intShadowIndex++)
    {
	    for (var intIndex=0; intIndex<shadowColours.length; intIndex++)
	    {
		    var shadowdiv = document.getElementById('shadow' + intShadowIndex + '_' + intIndex);
  		    		  
		    shadowdiv.style.left = shadowedImages[intShadowIndex].offsetLeft - intIndex-1 + 'px';
		    shadowdiv.style.top = shadowedImages[intShadowIndex].offsetTop - intIndex-1 + 'px';
		    //shadowdiv.style.left = findLeftPos(shadowedImages[intShadowIndex])- intIndex-1 + 'px';
		    //shadowdiv.style.top = findTopPos(shadowedImages[intShadowIndex]) - intIndex-1 + 'px';
		    if (navigator.appVersion.indexOf("MSIE") < 0)  /* not IE */
		    {
		      shadowdiv.style.width = shadowedImages[intShadowIndex].offsetWidth + (intIndex * 2) + 'px';
		      shadowdiv.style.height = shadowedImages[intShadowIndex].offsetHeight + (intIndex * 2) + 'px';
		    }
		    else  /*  IE  */
		    {
		      shadowdiv.style.width = shadowedImages[intShadowIndex].offsetWidth + (intIndex * 2)+2 + 'px';
		      shadowdiv.style.height = shadowedImages[intShadowIndex].offsetHeight + (intIndex * 2)+2 + 'px';
  		  }
	    }
    }
  }
}

// Used in skins to set focus to search terms textbox for accesskey=4 
function focusSearch()
{
  document.getElementById('dnn_dnnSEARCH_txtSearch').focus();  
}

//---------------------------------------------------------------------------------------------
//   DHTML Dialog code
//---------------------------------------------------------------------------------------------
var dialogTargetHref;
var dialogUseTracker;
function showDialog(targetHref, caption, message, height, width, usetracker, oklabel, cancellabel)
{
  //  Display a "popup" message using DHTML methods centered on the page
  //  Show the message and an OK/Cancel button.  When OK is clicked, navigate to targetHref
  //
  //  Sample:
  //    showDialog('http://www.google.com', document.getElementById('cim_page-wrapper'), 'Visit Google', 'Do you want to visit us?', 400, 600, false);
   
  var pagewidth;
  var pageHeight;
  var scrollTop;
  
  dialogClose();
  dialogTargetHref = targetHref;
  dialogUseTracker=usetracker;
  
  if (typeof(window.innerWidth) == 'number') 
  {
    // Not IE, most browsers support this
    pagewidth = window.innerWidth;    
    pageheight = window.innerHeight;    
  }
  else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) 
  {
    // IE 6+ in standards compliant mode
    pagewidth = document.documentElement.clientWidth;    
    pageheight = document.documentElement.clientHeight;    
  }
  else if (document.body && (document.body.clientWidth || document.body.clientHeight)) 
  {
    //IE 4 or lower
    pagewidth = document.body.clientWidth;
    pageheight = document.body.clientHeight;
  }
  
  if (self.pageYOffset) // all except Explorer
  { 
    scrollTop = self.pageYOffset;
  }
  else if (document.documentElement && document.documentElement.scrollTop) // Explorer 6 Strict
  { 
    scrollTop = document.documentElement.scrollTop;
  }
  else if (document.body) // all other Explorers
  {
    scrollTop = document.body.scrollTop;
  }
     
  var ctlDialog = document.createElement("div");
  ctlDialog.className = 'warningDialog';
  ctlDialog.id='warningDialog'; 
  ctlDialog.style.width = width;
  ctlDialog.style.height = height;
  ctlDialog.style.left = (pagewidth - width)/2 + 'px';
  ctlDialog.style.top = ((pageheight - height)/2 + scrollTop) + 'px';
  
  var ctlCaption = document.createElement("div");
  ctlCaption.className = 'caption';
  ctlCaption.style.width = '100%';
  ctlCaption.innerHTML = caption;
  ctlDialog.appendChild(ctlCaption);
  
  var ctlMessage = document.createElement("div");
  ctlMessage.className = 'message';
  ctlMessage.style.width = '100%';
  ctlMessage.innerHTML = message;
  ctlDialog.appendChild(ctlMessage);
  
  var ctlButtonPanel = document.createElement("div");
  ctlButtonPanel.className = 'buttonPanel';
  ctlButtonPanel.style.width = '100%';
  
  var ctlOkButton = document.createElement("input");
  ctlOkButton.name = 'OKButton';
  ctlOkButton.type='button';
  
  if (oklabel)
    ctlOkButton.value=oklabel;
  else
    ctlOkButton.value='OK';
    
  ctlOkButton.className = 'button commandbutton';
  ctlOkButton.onclick= function () {dialogNavigate();}
  ctlButtonPanel.appendChild(ctlOkButton);
  
  var ctlCancelButton = document.createElement("input");
  ctlCancelButton.name = 'CancelButton';
  ctlCancelButton.type='button';
  ctlCancelButton.className = 'button commandbutton';
  
  if (cancellabel)
    ctlCancelButton.value=cancellabel;
  else
    ctlCancelButton.value='Cancel';
  ctlCancelButton.onclick= function () {dialogClose();}
  ctlButtonPanel.appendChild(ctlCancelButton); 
  
  ctlDialog.appendChild(ctlButtonPanel);
  
  document.getElementById('Form').appendChild(ctlDialog);   
  //document.body.appendChild(ctlDialog);   
}

function dialogClose()
{
  dialogTargetHref = '';
  if (document.getElementById('warningDialog'))
    document.getElementById('warningDialog').parentNode.removeChild(document.getElementById('warningDialog'));    
}

function dialogNavigate()
{
  if (dialogUseTracker)
    navigateExternal(this);       
  else
    window.location = dialogTargetHref;
}

function attachExternalLinkDialog(linkElement)
{
  linkElement.onclick = function () 
  {
    showDialog
    (
      linkElement.href, 
      'External Site Link', 'The link you have selected [' + linkElement.href + '] navigates to a site outsite our control.  Do you want to visit the site?', 
      400, 
      600, 
      true
    );
      
    return false;
  }     
}

function attachFrameCode(linkElement)
{
  if (FRAME_URL.indexOf('?') == -1)
    linkElement.href = FRAME_URL + '?target=' + linkElement.href;
  else
    linkElement.href = FRAME_URL + '&target=' + linkElement.href;
}