// -*- indent-tabs-mode: nil; javascript-indent-level: 2; -*-
// 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);

function events_tabs(){
	
	tabs = document.getElementById("year-select").getElementsByTagName('a');
	var i = 0;
	var tab;
	while (tab = tabs[i++]) {
	
	
		tab.onclick = function (){
		
			// hide all events first
			var allevents = getElementsByClassName(document, 'div', "eventitem");
			var j = 0;
			while (evts = allevents[j++]) {
				evts.style.display = "none";
			}
		
			// then show the events that correspond to the year associated with the 
			// tab that been clicked on
			var className = this.id
			var events = getElementsByClassName(document, 'div', className);
			if (!events.length) {
				document.getElementById("noevents").style.display = "block";
			} else {
				document.getElementById("noevents").style.display = "none";
			};
			var evt;
			var k = 0;
			while (evt = events[k++]) {
				evt.style.display = "block";
			}

			var t;
			var c = 0;
			while (t = tabs[c++]) {
				t.className = "";
			}
			
			this.className = "selected"; 			
			
			return false;
		}
	}
}


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";
					 
						
						
					}
 			}
		}
	}		
}


// (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 linkback(){
 	if (!document.getElementById("link_back")) return false;
 	var contentarea = document.getElementById("link_back");
	var link = document.createElement("a");
	link.href = url_param("forwardurl");
	var linktext = document.createTextNode("Return to the previous page");
	link.appendChild(linktext);
	contentarea.appendChild(link);
}

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_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');
    if(document.getElementById("redirectUrl")){
    	// if we're sending an ajax request set the success url to be a simple html page which we can easily query
    	// in the parseResponse function below
    	document.getElementById("redirectUrl").value="/inc/emailsent.ajax.css";
    }
  
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) {
    sendpageform = document.getElementById("sendpage");
    displayLoading();
    request.onreadystatechange = function() {
      parseResponse(request);
    };
    request.open( "POST", sendpageform.action, true );
    request.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
    request.send(data);
    return true;
  } else {
      if(document.getElementById("redirectUrl")){
    	// if we're not sending an ajax request set the success url to be the standard html page
    	document.getElementById("redirectUrl").value="/go/page/emailsent.html";
    }
    return false;
  }
}

function parseResponse(request)
{
	if (request.readyState == 4) 
	{
		// if the response text is "success" - see /inc/emailsent.ajax.html
		if ((request.status == 200 || request.status == 304) && (request.responseText=='success')) {
			var container = document.getElementById("email-response");
			container.innerHTML = "<strong class='email-success'>The email has been sent.</strong>";
			prepareForm();
		}else{
			// the response text from the server was not 'sucess'
			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);
    }
  }
}

