// addLoadEvent function as seen at http://simon.incutio.com/archive/2004/05/26/addLoadEvent
// allows you to stack functions and apply them to the onload event and also means you 
// can abstract onload functions from the html
// I've added an argument 'arg' for onload functions with an argument
// Could probably be better implemented with 'arguments[]'

function addLoadEvent(func,arg) {
	
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      if (oldonload) {
        oldonload();
      }
      func(arg);
    }
  }
}


addLoadEvent(prepareForm);


// (c) Bright Interactive 2007, Eric Clack, eric@bright-interactive.com


function url_param(p) {
	// Retrieve an url param specified by p=value
	var re = new RegExp( p + "=([^&]+)" );
	var matches = document.location.href.match(re);
	if (matches) {
		return unescape(matches[1]);
	}
	else {
		return '';
	}
}


function query_string() {
	// Retrieve the domain name from the current page
	var re = new RegExp( "\\?(.*)" );
	var matches = document.location.href.match(re);
	if (matches) {
		return matches[1];
	}
	else {
		return '';
	}
}


function domain_name() {
	// Retrieve the domain name from the current page
	var re = new RegExp( "(http|https)://([^/]+)/" );
	var matches = document.location.href.match(re);
	if (matches) {
		return matches[2];
	}
	else {
		return '';
	}
}


function protocol() {
	// Retrieve the domain name from the current page
	var re = new RegExp( "(http|https)://" );
	var matches = document.location.href.match(re);
	if (matches) {
		return matches[1];
	}
	else {
		return '';
	}
}

 
/*
	Copyright Robert Nyman, http://www.robertnyman.com
	Free to use if this text is included
*/
// ---
function $(strId){
	return document.getElementById(strId);
}
// ---
function getElementsByClassName(oElm, strTagName, strClassName){
	var arrElements = (strTagName == "*" && oElm.all)? oElm.all : oElm.getElementsByTagName(strTagName);
	var arrReturnElements = new Array();
	strClassName = strClassName.replace(/\-/g, "\\-");
	var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$)");
	var oElement;
	for(var i=0; i<arrElements.length; i++){
		oElement = arrElements[i];		
		if(oRegExp.test(oElement.className)){
			arrReturnElements.push(oElement);
		}	
	}
	return (arrReturnElements)
}
// ---
function addClassName(oElm, strClassName){
	var strCurrentClass = oElm.className;
	if(!new RegExp(strClassName, "i").test(strCurrentClass)){
		oElm.className = strCurrentClass + ((strCurrentClass.length > 0)? " " : "") + strClassName;
	}
}
// ---
function removeClassName(oElm, strClassName){
	var oClassToRemove = new RegExp((strClassName + "\s?"), "i");
	oElm.className = oElm.className.replace(oClassToRemove, "").replace(/^\s?|\s?$/g, "");
}
// ---

function getPageUrl(){
 	if (!document.getElementById("pageurl")) return false;
	var field = document.getElementById("pageurl");
	field.value = document.location.href.replace(/\&/g,'&amp;');
}

function getHTTPObject() {
  var xhr = false;
  if (window.XMLHttpRequest) {
    xhr = new XMLHttpRequest();
  } else if (window.ActiveXObject) {
    try {
      xhr = new ActiveXObject("Msxml2.XMLHTTP");
    } catch(e) {
      try {
        xhr = new ActiveXObject("Microsoft.XMLHTTP");
      } catch(e) {
        xhr = false;
      }
    }
  }
  return xhr;
}

function highlight_year() {

	// Highlight the right subnav item by comparing the URL with
	// the href of each <a> elt in the <div id="subnav">, or by
	// using the hint if supplied as arguments[0]. The hint
	// specifies a part of the URL, useful for actions with
	// lots of paramters
	
	var this_page = document.location.href;
	
	// Remove anchor if there is one -- anything following #, including #
	this_page = this_page.replace( /\#.*/, '' );
	
	var hint = "";
	if (arguments[0]) {
		hint = arguments[0];
	}
	
	
	// Try both subnav and subnavIndent for our item to highlight
	
	var divs = [ "year-select" ];
	for (var d = 0; d < divs.length; d++) {
	
		if (document.getElementById(divs[d])) {
			var subnav_elts = document.getElementById(divs[d]);
			var aTags = subnav_elts.getElementsByTagName("A");
 			var i = 0;
			for (i = 0; i < aTags.length; i++) {
				// Is this a link?
				var elt = aTags[i]
 					if (elt.href == this_page || (hint && elt.href.indexOf(hint) != -1) ) {
						elt.className = elt.className + " selected";
					 
						
						
					}
 			}
		}
	}
		

}
function highlight_subnav() {
	// Highlight the right subnav item by comparing the URL with
	// the href of each <a> elt in the <div id="subnav">, or by
	// using the hint if supplied as arguments[0]. The hint
	// specifies a part of the URL, useful for actions with
	// lots of paramters
	
	var this_page = document.location.href;
	
	// Remove anchor if there is one -- anything following #, including #
	this_page = this_page.replace( /\#.*/, '' );
	
	var hint = "";
	if (arguments[0]) {
		hint = arguments[0];
	}
	
	
	// Try both subnav and subnavIndent for our item to highlight
	
	var divs = [ "secondary_content" ];
	for (var d = 0; d < divs.length; d++) {
	
		if (document.getElementById(divs[d])) {
			var subnav_elts = document.getElementById(divs[d]);
			var aTags = subnav_elts.getElementsByTagName("A");
 			var i = 0;
			for (i = 0; i < aTags.length; i++) {
				// Is this a link?
				var elt = aTags[i]
 					if (elt.href == this_page || (hint && elt.href.indexOf(hint) != -1) ) {
						elt.className = elt.className + " currentsection";
					 
						
						
					}
 			}
		}
	}
		

}



function prepareForm() {
  if(!document.getElementById) {
    return;
  }
  if(!document.getElementById("sendpage")) {
    return;
  }
  
  var image = document.getElementById("sendpagebtn");
  image.setAttribute("src","/img/buttons/sendpage.jpg");
  removeClassName(image,'sending-email');
document.getElementById("sendpage").onsubmit = function() {
  	if(!validate(this)) return false;
    var data = "";
    for (var i=0; i<this.elements.length; i++) {
      data+= this.elements[i].name;
      data+= "=";
      data+= escape(this.elements[i].value);
      data+= "&";
    }
    return !sendData(data);
  };
}

function sendData(data) {
  var request = getHTTPObject();
  if (request) {
    displayLoading(document.getElementById("sendpage"));
    request.onreadystatechange = function() {
      parseResponse(request);
    };
    request.open( "POST", "/do/bright/form/mailform", true );
    request.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
    request.send(data);
    return true;
  } else {
    return false;
  }
}

function parseResponse(request)
{
  if (request.readyState == 4) 
  {
  
   		// the line request.responseText.substr(172,5) refers to a html comment placed immediately next to the head tag
  		// looks like <!--error * do not remove *---> this is checked and treated as an error even though the page is found and an "OK" status is sent
		if ((request.status == 200 || request.status == 304) && (request.responseText.substr(172,5) != "error")) {
			var container = document.getElementById("email-response");
			container.innerHTML = "<strong class='email-success'>The email has been sent.</strong>";
 		  	prepareForm();
		}else{
			// the response code from the server was not positive so show a generic error
			var container = document.getElementById("email-response");
			container.innerHTML = "<strong class='email-error'>Sorry, the email has not been sent. Please try again later.</strong>";
			resetLoading();
 		}
	}
}

function getHTTPObject() {
  var xhr = false;
  if (window.XMLHttpRequest) {
    xhr = new XMLHttpRequest();
  } else if (window.ActiveXObject) {
    try {
      xhr = new ActiveXObject("Msxml2.XMLHTTP");
    } catch(e) {
      try {
        xhr = new ActiveXObject("Microsoft.XMLHTTP");
      } catch(e) {
        xhr = false;
      }
    }
  }
  return xhr;
}

function displayLoading(element) {
	var image = document.getElementById("sendpagebtn");
	image.setAttribute("src","/img/buttons/sending.gif");
	addClassName(image,'sending-email');
}

function resetLoading(element) {
	var image = document.getElementById("sendpagebtn");
	image.setAttribute("src","/img/buttons/sendpage.jpg");
	removeClassName(image,'sending-email');
}

function fadeUp(element,red,green,blue) {
  if (element.fade) {
    clearTimeout(element.fade);
  }
  element.style.backgroundColor = "rgb("+red+","+green+","+blue+")";
  if (red == 255 && green == 255 && blue == 255) {
    return;
  }
  var newred = red + Math.ceil((255 - red)/10);
  var newgreen = green + Math.ceil((255 - green)/10);
  var newblue = blue + Math.ceil((255 - blue)/10);
  var repeat = function() {
    fadeUp(element,newred,newgreen,newblue)
  };
  element.fade = setTimeout(repeat,100);
}

function fadeUpErrors(element) {
  var messages = element.getElementsByTagName("strong");
  for (var i=0; i<messages.length; i++) {
    if (messages[i].className == "error") {
      fadeUp(messages[i],255,153,153);
    }
  }
}

