// -------------------------------------------------
// Accompanies WGS site
// -------------------------------------------------

// Text Changer settings

var LARGE  = 105;          // % font size
var MEDIUM = 90;
var SMALL  = 76;           // the default - must be same as BODY font-size in CSS file
var HILITE = '#F4C0A8';    // currently-selected text sizer background colour
var BG     = '#FFFFFF';    // regular background colour
var DAYS   = 365;          // days to retain cookie which remembers user choice of text size

// Array of pages (identified by title) which require imagemap-driven popup divs
var arRequirePopups = ['Children','Moving & remortgaging', 'Financial Dispute','Separation']

// -------------------------------------------------

// obtain arrays of all links & divs
var arAnchors = document.getElementsByTagName('a');
var arDivs = document.getElementsByTagName('div');

addEvent(window,"load",init);

function init(){

	// functions to run on page load

    // build homepage menu
// 	if (document.title == 'Warner Goodman Homepage'){
// 	   setupMainMenuHandlers();
// 	   setupMainMenuStyles();
// 	   document.onclick = hidePoppedDivs
// 	}

    // prepare imagemap popup windows for those pages which use them
	for (i = 0; i < arRequirePopups.length; i++){
	   if (document.title == arRequirePopups[i]) {
	      setupImagemapPoppers();
	      document.onclick = hidePoppedDivs;
		  break;
	   }
	}

    // Set font sizes, if stored or chosen
    checkTextSize();
	setupTextSizer();

    // prevent dummy test page link errors where href contains 'xxx'
    // blockDummyPages(arAnchors, 'xxx');
}

function setupMainMenuStyles(){

   // display main navigation on home page

   for (var i = 0; i < arDivs.length; i++){

	   var obj = arDivs[i];
	   var objStyle = obj.style;
      
	   // set CSS background image for submenu popups
	   if (obj.id == 'smnucommercial'){
	      var bgImage = 'url(images/wgcommsmall.gif)';
		  var imgPaddingTop = '80px';
	   }
	   else {
	      var bgImage = 'url(images/wgslogosmall.gif)';
		  var imgPaddingTop = '50px';
	   }

	   // show main navigation div
	   if (obj.id == 'homenav'){
		   objStyle.display = 'block';
	   }

	   // hide subnav popup boxes
	   if (obj.className == 'homesubmenu'){ 
		   objStyle.display = 'none';
		   objStyle.styleFloat = 'none'; // IE floats
		   objStyle.cssFloat = 'none';   // non-IE floats
		   objStyle.position = 'absolute';
		   objStyle.backgroundImage = bgImage;
		   objStyle.paddingTop = imgPaddingTop;
	   }

	   // hide description text in subnav boxes
	   if (obj.className == 'homesubmenuhdr'){
		   objStyle.display = 'none';
	   }
   }
}

function setupMainMenuHandlers(){

   // assign click event handlers for homepage menu

   // click on a menu div to pop a submenu box
   for (var i = 0; i < arDivs.length; i++){
	  if ((arDivs[i].className == 'homeU')||(arDivs[i].className == 'homeL')){
		  arDivs[i].onclick = showSubmenu;
      }
   }

	// prevent default href links from working
   for (var i = 0; i < arAnchors.length; i++){
	  if ((arAnchors[i].className == 'homeUlink') || (arAnchors[i].className == 'homeLlink')){
		  arAnchors[i].onclick = function(){return false;};
      }
   }
}


function showSubmenu(e) {

   // Pops a homepage submenu box

   // prevent document.onclick also firing and thus closing all the menus
   stopProp(e);

   callerID = this.id;
   caller = document.getElementById(this.id);

   // obtain the WGS dept name from caller's ID
   deptID = callerID.substr(5);
    			 
   if (callerID.indexOf('homeU') > -1){
       popHomeMenuDiv('smnu' + deptID, caller, 5, 5);
   }

   if (callerID.indexOf('homeL') > -1){
       popHomeMenuDiv('smnu' + deptID, caller, 5, -50);
   }

   return false;
}

function popHomeMenuDiv(IDtoShow, caller, offLeft, offTop){ 
	
   // Shows a hidden menu div in a position relative to the calling object

   arPos = findPos(caller);
   x = arPos[0];
   y = arPos[1];

   // hide all the others, if popped
   hidePoppedDivs()

   // then show this one
   myObj = document.getElementById(IDtoShow);
   myObj.style.left = (x + offLeft) + "px";
   myObj.style.top = (y + offTop) + "px";
   myObj.style.display = "block";
}

function setupImagemapPoppers(){

   // assign click event handlers for emulated popup boxes
   // for each imagemap <area> element on the page

   // get position of image over which the map is applied
   arImgPos = findPos(document.getElementById('mapimage'))

   // x,y offset to pop box just under the parent <area> element
   areaOffset = [0, 25];

   var arAreas = document.getElementsByTagName('area');
   for (var i = 0; i < arAreas.length; i++){
	  if (arAreas[i].className == 'pop'){
		  arAreas[i].onclick = popImagemapDiv;
      }
   }
}

function popImagemapDiv(e){ 
	
   // Shows a hidden div by clicking on an imagemap area to emulate a popup.
   // Requires:
   //   (1) parent image to have an ID of 'mapimage'
   //   (3) each <area> to have class of 'pop' and an explicit id
   //   (2) for each <area> id 'foo', the matching popup div id must be: 'foo_pop'

   // prevent document.onclick firing and shutting all the popups
   stopProp(e);

   // get <area> left & top coordinates
   var oArea = document.getElementById(this.id);
   var arCoords = oArea.coords.split(',')
   var left = parseInt(arCoords[0]);
   var top = parseInt(arCoords[1]);

   // hide all the other popped divs, if already popped
   hidePoppedDivs();

   // then show the popup div which matches the <area>
   myObj = document.getElementById(this.id + '_pop');
   myObj.style.left = (arImgPos[0] + areaOffset[0] + left)+ "px";
   myObj.style.top =  (arImgPos[1] + areaOffset[1] + top )+ "px";
   myObj.style.display = "block";

   // cancel the href move to an other page
   return false;
}

function hidePoppedDivs(){  

   // Hides all manually popped divs for homepage menu & other page popups

    for (var i = 0; i < arDivs.length; i++){
	   if ( (arDivs[i].className == 'homesubmenu') || (arDivs[i].className == 'pop')){
		  arDivs[i].style.display = "none";
	   }
    }
}


function findPos(obj){

    // From quirksmode. Returns an array containing x & y for an object

	var curleft = curtop = 0;

    if (obj.offsetParent){
		while (obj.offsetParent){
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
			obj = obj.offsetParent;
		}
	}
   return [curleft, curtop];
}


function blockDummyPages(arLinks, dummyURL){

   // block link navigation to dummy pages where href value contains dummyURL

	var msg = "Sorry, the page does not yet exist.";

    for (var i = 0; i < arLinks.length; i++){
       if (arLinks[i].href.indexOf(dummyURL) > -1){
          arLinks[i].onclick = function(){alert(msg); return false;};
	   }
	}
}

function stopProp(e){

   // Quirksmode xplat event propagation stopper to block event handlers
   // on parent objects up the DOM from firing

   if (!e) {
	   var e = window.event;
   }
   if (e.stopPropagation) {
	   e.stopPropagation();
   }
   e.cancelBubble = true;
}

// -------------------------------------------------

// Text Changer device functions
// (Size values are used as percentage font size for BODY element)

function setupTextSizer(){

   // display Text Sizer
    document.getElementById('sizerholder').style.display = 'inline';

	// sets up onclick event handlers for text sizer
	addEvent(document.getElementById("tsSmall"), 'click', setTextSize);
	addEvent(document.getElementById("tsMedium"), 'click', setTextSize);
	addEvent(document.getElementById("tsLarge"), 'click',  setTextSize);
}

function checkTextSize(){

   // retrieves any cookie-stored text size preference
   // and sets accordingly

   var cookieval = readCookie("WGSTextSize");
   if (cookieval != null){
	   setTextSize(cookieval);
   }
}
                          
function setTextSize(cookieval) {

   // Sets font size in percent for BODY and highlights the clicked link
   // either from stored cookie value or user click event

   var sizeval = false;

   if ((cookieval == "tsSmall")  || 
	   (cookieval == "tsMedium") || 
	   (cookieval == "tsLarge")){
       var sizeval = cookieval;
   }
   if (this.id){
       var sizeval = this.id;
	   // Remove ugly dotted "has focus" box around the link
	   // and highlight the clicked link
	   this.blur();
	   highlight(this.id);
   }

   if (sizeval){
      switch (sizeval){
         case "tsSmall" :
	        intFontSize = SMALL;
	        break;
         case "tsMedium" : 
	        intFontSize = MEDIUM;
	        break;
         case "tsLarge" : 
	        intFontSize = LARGE;
	        break;
         default: 
	        intFontSize = SMALL;
      }
      document.body.style.fontSize = intFontSize + "%"
      createCookie("WGSTextSize", sizeval , DAYS);
   }
}

function highlight(myID){

    // sets HILITE colour to current text size link
    // and sets the other two elements to the BG colour

    s = document.getElementById("tsSmall");
    m = document.getElementById("tsMedium");
    l = document.getElementById("tsLarge");

    s.style.backgroundColor = BG;
	m.style.backgroundColor = BG;
	l.style.backgroundColor = BG;
    
	if (myID == "tsLarge"){
       l.style.backgroundColor = HILITE;
	}
	else if (myID == "tsMedium"){
       m.style.backgroundColor = HILITE;
	}
	else { 
       s.style.backgroundColor = HILITE; // default
	}
}


function createCookie(name, value, days) {

   if (days){
      var date = new Date();
      date.setTime(date.getTime()+(days*24*60*60*1000));
      var expires = "; expires=" + date.toGMTString();
   }
   else {
	   expires = "";
   }

   document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(name) {

   var nameEQ = name + "=";
   var ca = document.cookie.split(';');
   for (var i = 0; i < ca.length; i++){
      var c = ca[i];
      while (c.charAt(0) == ' ') {
		  c = c.substring(1, c.length);
	  }
      if (c.indexOf(nameEQ) == 0){
		  return c.substring(nameEQ.length, c.length);
	  }
   }

   return null;
}

// -------------------------------------------------

// Event handler utility functions by Dean Edwards, 2005
// with input from Tino Zijdel, Matthias Miller, Diego Perini
// http://dean.edwards.name/weblog/2005/10/add-event/

function addEvent(element, type, handler) {
	if (element.addEventListener) {
		element.addEventListener(type, handler, false);
	} 
	else {
		// assign each event handler a unique ID
		if (!handler.$$guid){
			handler.$$guid = addEvent.guid++;
		}

		// create a hash table of event types for the element
		if (!element.events){ 
			element.events = {};
		}

		// create a hash table of event handlers for each element/event pair
		var handlers = element.events[type];
		if (!handlers){
			handlers = element.events[type] = {};
			// store the existing event handler (if there is one)
			if (element["on" + type]) {
				handlers[0] = element["on" + type];
			}
		}
		// store the event handler in the hash table
		handlers[handler.$$guid] = handler;
		// assign a global event handler to do all the work
		element["on" + type] = handleEvent;
	}
};

// a counter used to create unique IDs
addEvent.guid = 1;

function removeEvent(element, type, handler) {

	if (element.removeEventListener) {
		element.removeEventListener(type, handler, false);
	} 
	else {
		// delete the event handler from the hash table
		if (element.events && element.events[type]) {
			delete element.events[type][handler.$$guid];
		}
	}
};

function handleEvent(event) {

	var returnValue = true;
	// grab the event object (IE uses a global event object)
	event = event || fixEvent(((this.ownerDocument || this.document || this).parentWindow || window).event);
	// get a reference to the hash table of event handlers
	var handlers = this.events[event.type];
	// execute each event handler
	for (var i in handlers) {
		this.$$handleEvent = handlers[i];
		if (this.$$handleEvent(event) === false) {
			returnValue = false;
		}
	}
	return returnValue;
};

function fixEvent(event) {

	// add W3C standard event methods
	event.preventDefault = fixEvent.preventDefault;
	event.stopPropagation = fixEvent.stopPropagation;
	return event;
};

fixEvent.preventDefault = function() {
	this.returnValue = false;
};

fixEvent.stopPropagation = function() {
	this.cancelBubble = true;
};

// -------------------------------------------------

