//FUNCTIONSLIB.JS
//www.plscouts.org.uk
//Unauthorised Copying Prohibited

/* 
cbb function by Roger Johansson, http://www.456bereastreet.com/ (JS rounded corners)
*/
var cbb = {
	init : function() {
	// Check that the browser supports the DOM methods used
		if (!document.getElementById || !document.createElement || !document.appendChild) return false;
		var oElement, oOuter, oI1, oI2, tempId;
	// Find all elements with a class name of cbb
		var arrElements = document.getElementsByTagName('*');
		var oRegExp = new RegExp("(^|\\s)cbb(\\s|$)");
		for (var i=0; i<arrElements.length; i++) {
	// Save the original outer element for later
			oElement = arrElements[i];
			if (oRegExp.test(oElement.className)) {
	// 	Create a new element and give it the original element's class name(s) while replacing 'cbb' with 'cb'
				oOuter = document.createElement('div');
				oOuter.className = oElement.className.replace(oRegExp, '$1cb$2');
	// Give the new div the original element's id if it has one
				if (oElement.getAttribute("id")) {
					tempId = oElement.id;
					oElement.removeAttribute('id');
					oOuter.setAttribute('id', '');
					oOuter.id = tempId;
				}
	// Change the original element's class name and replace it with the new div
				oElement.className = 'i3';
				oElement.parentNode.replaceChild(oOuter, oElement);
	// Create two new div elements and insert them into the outermost div
				oI1 = document.createElement('div');
				oI1.className = 'i1';
				oOuter.appendChild(oI1);
				oI2 = document.createElement('div');
				oI2.className = 'i2';
				oI1.appendChild(oI2);
	// Insert the original element
				oI2.appendChild(oElement);
	// Insert the top and bottom divs
				cbb.insertTop(oOuter);
				cbb.insertBottom(oOuter);
			}
		}
	},
	insertTop : function(obj) {
		var oOuter, oInner;
	// Create the two div elements needed for the top of the box
		oOuter=document.createElement("div");
		oOuter.className="bt"; // The outer div needs a class name
	    oInner=document.createElement("div");
	    oOuter.appendChild(oInner);
		obj.insertBefore(oOuter,obj.firstChild);
	},
	insertBottom : function(obj) {
		var oOuter, oInner;
	// Create the two div elements needed for the bottom of the box
		oOuter=document.createElement("div");
		oOuter.className="bb"; // The outer div needs a class name
	    oInner=document.createElement("div");
	    oOuter.appendChild(oInner);
		obj.appendChild(oOuter);
	},
	// addEvent function from http://www.quirksmode.org/blog/archives/2005/10/_and_the_winner_1.html
	addEvent : function(obj, type, fn) {
		if (obj.addEventListener)
			obj.addEventListener(type, fn, false);
		else if (obj.attachEvent) {
			obj["e"+type+fn] = fn;
			obj[type+fn] = function() { obj["e"+type+fn]( window.event ); }
			obj.attachEvent("on"+type, obj[type+fn]);
		}
	}
};


/*
bgimg by unknown (attaches and resizes background image)
*/
var bgimg;
function initBg() {
  if (arguments.callee.done) return;
  arguments.callee.done = true;
  bgimg = document.getElementById('bg').getElementsByTagName('img')[0];
  if (!bgimg) return;
  bgimg.onload = resizeBg;
  //bgimg.src = 'bg.jpg';
  if (window.addEventListener) window.addEventListener('resize', resizeBg, false);
  else if (window.attachEvent) window.attachEvent('onresize', resizeBg);
  else window.onresize = resizeBg;
}
function resizeBg() {
  var w = self.innerWidth || document.documentElement.clientWidth;
  var h = self.innerHeight || document.documentElement.clientHeight;
  if (bgimg.width !== w) {
    bgimg.parentNode.style.left = '0';
    bgimg.parentNode.style.top = '0';
    bgimg.height = bgimg.parentNode.height = (w / bgimg.width) * bgimg.height;
    bgimg.width = bgimg.parentNode.width = w;
  }
  if (bgimg.height < h) {
    bgimg.width = bgimg.parentNode.width = (h / bgimg.height) * bgimg.width;
    bgimg.height = bgimg.parentNode.height = h;
    bgimg.parentNode.style.left = '-' + ((bgimg.width - w) / 2) + 'px';
  }
  else if (bgimg.height > h) {
    bgimg.parentNode.style.top = '-' + ((bgimg.height - h) / 2) + 'px';
  }
}

/*
sfHover by the Scout Association - fallback support for IE dropdown menus. 
*/
function sfHover()
{
 // Load sfHover only in IE; other browsers don't need it
   if (window.attachEvent)
{
   var sfEls = document.getElementById("nav").getElementsByTagName("li");
   for (var i=0; i<sfEls.length; i++)
   {
      sfEls[i].onmouseover=function()
      {
         this.className+=" sfhover";
      }
      sfEls[i].onmouseout=function()
      {
         this.className=this.className.replace(new RegExp(" sfhover\\b"), "");
      }
   }
   }
}

/* 
externalLinks (probably by geog.cam.ac.uk) make all links with rel=external open in new window. 
*/
function externalLinks() {
 if (!document.getElementsByTagName) return;
 var anchors = document.getElementsByTagName("a");
 for (var i=0; i<anchors.length; i++) {
   var anchor = anchors[i];
   if (anchor.getAttribute("href") &&
       anchor.getAttribute("rel") == "external")
     anchor.target = "_blank";
 }
}


//generic function to open any popup
function open_popup(address)
{
   window.open(address,address,"width=500,height=400,scrollbars=yes");
}

//generic function to open a link in a new window
function openInNew(address)
{
   window.open(address,'newWindow',"");
}

//removes advice text from textbox when user focusses on element
function removeText(element)
{
   if(document.getElementById(element).value == 'Type your message here.')
   {
      document.getElementById(element).value = '';
   }
}


/*
Light up input boxes.
*/
function inputsAL(style)
{
   if(!document.getElementsByTagName)
   {
       return;
   }
   //initalise basic vars
   var inputs = document.getElementsByTagName('input');
   var textareas = document.getElementsByTagName('textarea');
   var ia = inputs.length;
   var ta = textareas.length;
   
   //loop thru inputs
   for(var i=0; i < ia; i++)
   {
      input = inputs[i];
      
      //check for, and bypass, any inputs where effect is not required
      if(input.type == 'text' || input.type == 'password')
      {
	 //opt-out for dhtml calendar (1 per form only, as referenced via name)
	 if(input.name != 'date_cal' && input.name != 'date_start' && input.name != 'date_finish')
	 {
            addEvent(input, 'focus', inputsLU, false);
            addEvent(input, 'blur', inputsLO, false);
         }
         //always attach class to element, even if there is opt-out on lu/lo
         input.className = 'textinput';
      }
   }
   
   //loop thru textareas
   for(var i=0; i < ta; i++)
   {
      textarea = textareas[i];
      addEvent(textarea, 'focus', inputsLU, false);
      addEvent(textarea, 'blur', inputsLO, false);
   }
}

//light up
function inputsLU(e)
{
   var input = findTarget(e);
   input.className = 'inputsLU-S';
}

//light off
function inputsLO(e)
{
   var input = findTarget(e);
   if(input.type == 'text' || 'file')
   {
      input.className = 'textinput';
   }
   else
   {
      input.className = '';
   }
}



//generic function to find element that triggered a function - used for lu/lo
function findTarget(e)
{
   var target;
   
   if(window.event && window.event.srcElement)
   {
      target = window.event.srcElement;
   }
   else if(e && e.target)
   {
      target = e.target;
   }
   if(!target)
   {
      return null;
   }
   
   return target;
}

  //Library function - used to knacker the 'href' events of a link when clicked for onclick.
function knackerEvent(eventObject) {
    if (eventObject && eventObject.stopPropagation) {
        eventObject.stopPropagation();
    }
    if (window.event && window.event.cancelBubble ) {
        window.event.cancelBubble = true;
    }
    
    if (eventObject && eventObject.preventDefault) {
        eventObject.preventDefault();
    }
    if (window.event) {
        window.event.returnValue = false;
    }
}
   
   
//http://techpatterns.com/downloads/javascript_cookies.php
function Set_Cookie( name, value, expires, path, domain, secure )
{
// set time, it's in milliseconds
var today = new Date();
today.setTime( today.getTime() );

/*
if the expires variable is set, make the correct
expires time, the current script below will set
it for x number of days, to make it for hours,
delete * 24, for minutes, delete * 60 * 24
*/
if ( expires )
{
expires = expires * 1000 * 60 * 60 * 24;
}
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" : "" );
}


// this fixes an issue with the old method, ambiguous values
// with this test document.cookie.indexOf( name + "=" );
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;
	}
}




/* -------------------------------------------------------------------------- */
function addEvent(elm, evType, fn, useCapture) {
  // cross-browser event handling for IE5+, NS6 and Mozilla 
  // By Scott Andrew 
  if (elm.addEventListener) { 
    elm.addEventListener(evType, fn, useCapture); 
    return true; 
  } else if (elm.attachEvent) { 
    var r = elm.attachEvent('on' + evType, fn); 
    return r; 
  } else {
    elm['on' + evType] = fn;
  }
}

 




