/*
	Team Walking Javascript Functions
	Created by Matt R 3rd July 2007
	for Kariba Creative Media
*/

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

// This script will emulate the css :hover effect on the menu elements in IE

// The variables
var cssid = "primary-nav"; // CSS ID for the menuwrapper
var menuadd = "h";  // Character to be added to the specific classes upon hovering. So for example, if this is set to "h", class "menuparent" will become "menuparenth" when hovered over.
var menuh = "menuh"; // Classname for hovering over all other menu items

if (window.attachEvent) window.attachEvent("onload", cssHover);

function cssHover() {
	var sfEls = document.getElementById(cssid).getElementsByTagName("LI");
	for (var i=0; i<sfEls.length; i++) {

		sfEls[i].onmouseover=function() {
			if (this.className != "") {
				this.className = this.className + menuadd;
			}
			else {	
				this.className = menuh;
			}
		}

		sfEls[i].onmouseout=function() {
			if (this.className == menuh) {
				this.className = "";
			}
			else {
				this.className = this.className.replace(new RegExp(menuadd + "$"), "");
			}
		}
	}
}

function createoverlayloader()
{
	var objBody = document.getElementsByTagName("body").item(0);
	
	var objOverlay = document.createElement("div");
	objOverlay.setAttribute('id','overlay');
	objOverlay.style.display = 'none';
	//objOverlay.onclick = function() { myLightbox.end(); return false; }
	objBody.appendChild(objOverlay);
	
	$('overlay').innerHTML = '<div id="horizon"><div id="loadercontent"><img src="assets/images/loader.gif" /><br><h2>Loading...</h2></div></div>';
	
	// stretch overlay to fill page and fade in
	var arrayPageSize = getPageSize();
	Element.setHeight('overlay', arrayPageSize[1]);
	new Effect.Appear('overlay', { duration: 1, from: 0.0, to: 0.8 });
	window.setTimeout("new Effect.Fade('overlay', { duration: 1, from: 0.8, to: 0.0 });", 5000);
}

function destroyoverlayloader()
{
	new Effect.Fade('overlay', { duration: 1, from: 0.8, to: 0.0 });
}

/* Tertiary Menu Functions */
addLoadEvent(function() {
	
	/* Phone me back Function */
	
	if ($('tm_phone'))
	{
		$('tm_phone').onclick = function() 
		{
			var name = prompt('Please enter your name.', '');
			
			// Detect if IE7 (because it doesn't allow the silly prompt scripting thingy
			IE7 = ((document.all)&&(navigator.appVersion.indexOf("MSIE 7.")!=-1)) ? true : false;
			
			if (IE7 && !name)
			{
				alert('IE7 User - You need to allow scripted windows on this page in order to continue. Please do so and try again.');
				return
			}
			
			if (!name || name == "")
			{
				alert('Please enter a name to continue.');
				return;
			}
			else
			{
				var telephone = prompt('Please enter your telephone number and one of our team will call you back.', '');	
				
				if (telephone == "")
				{
					alert('Please enter a telephone number to continue.');
					return;
				}

				var url = 'ajax.php?method=callback&name=' + name + '&telephone=' + telephone;
		
				new Ajax.Request(url, {
					method: 'get',
					onLoading: function() {
						createoverlayloader();
					},
					onComplete: function(request) {
						if (request.responseText)
						{
							alert(request.responseText);
						}
						else
						{
							$('loadercontent').innerHTML = '<h2>Your request has been received. A member of staff will be in touch shortly.</h2>';
							//alert('Your request has been received. A member of staff will be in touch shortly.');
							
							//destroyoverlayloader();
						}
					}
				});
			}
			
		}
	}
	
	/* Forward to a friend Function */
	
	if ($('tm_forward'))
	{
		$('tm_forward').onclick = function() {
			
			var your_name = prompt('Please enter your name.');
			
			// Detect if IE7 (because it doesn't allow the silly prompt scripting thingy
			IE7 = ((document.all)&&(navigator.appVersion.indexOf("MSIE 7.")!=-1)) ? true : false;
			
			if (IE7 && !your_name)
			{
				alert('IE7 User - You need to allow scripted windows on this page in order to continue. Please do so and try again.');
				return
			}
			
			if (!your_name || your_name == "")
			{
				alert('You need to enter a name to continue.');
				return;
			}
			
			var their_email = prompt('Please enter the email address of the person you would like to forward this page to.');
			
			if (their_email == "" || emailCheck(their_email) == false)
			{
				alert('You need to enter a valid email address to continue.');
				return;
			}
			
			var forward_url = window.location.href;
			
			var url = 'ajax.php?method=forward&name=' + your_name + '&emailaddress=' + their_email + '&forwardurl=' + forward_url;
	
			new Ajax.Request(url, {
				method: 'get',
				onLoading: function() {
					createoverlayloader();
				},
				onComplete: function(request) {
					if (request.responseText)
					{
						alert(request.responseText);
					}
					else
					{
						$('loadercontent').innerHTML = '<h2>Your request has been received and the page has been forwarded.</h2>';
						//alert('Your request has been received. A member of staff will be in touch shortly.');
						
						//destroyoverlayloader();
					}
				}
			});
		}
	}
	
	/* Print Function */
	if ($('tm_print'))
	{
		$('tm_print').onclick = function() {
			var confirmed = confirm('Would you like to Print this page?');
			if (confirmed)
			{
				window.print();	
			}
		}
	}
	/* Bookmark Function */
	if ($('tm_bookmark'))
	{
		$('tm_bookmark').onclick = function() {
			var confirmed = confirm('Would you like to add this page to your Favourites?');
			if (confirmed)
			{
				var title = "Gauntlet Health and Safety";
				var url = "http://www.gauntlethealthandsafety.co.uk/";
				
				if (window.sidebar)  // Mozilla Firefox Bookmark
				{
					window.sidebar.addPanel(title, url,"");
				}
				else if( window.external ) { // IE Favorite
					window.external.AddFavorite(url, title); 
				}
				else if(window.opera && window.print) { // Opera Hotlist
					return true; 
				}				
			}
		}
	}
	
	/* Newsletter Request */
	
	if ($('tm_newsletter'))
	{
		$('tm_newsletter').onclick = function() {
			
			var your_name = prompt('Please enter your name.');
			
			// Detect if IE7 (because it doesn't allow the silly prompt scripting thingy
			IE7 = ((document.all)&&(navigator.appVersion.indexOf("MSIE 7.")!=-1)) ? true : false;
			
			if (IE7 && !your_name)
			{
				alert('IE7 User - You need to allow scripted windows on this page in order to continue. Please do so and try again.');
				return
			}
			
			if (!your_name || your_name == "")
			{
				alert('You need to enter a name to continue.');
				return;
			}
			
			var your_email = prompt('Please enter your email address.');
			
			if (your_email == "" || emailCheck(your_email) == false)
			{
				alert('You need to enter a valid email address to continue.');
				return;
			}
			
			var url = 'ajax.php?method=newsletter&name=' + your_name + '&emailaddress=' + your_email;
	
			new Ajax.Request(url, {
				method: 'get',
				onLoading: function() {
					createoverlayloader();
				},
				onComplete: function(request) {
					if (request.responseText)
					{
						alert(request.responseText);
					}
					else
					{
						$('loadercontent').innerHTML = '<h2>Your request has been received, and your email address has been added.</h2>';
					}
				}
			});
		}
	}
});
			

// Contact Form Javascript

function emailCheck (emailStr) {
	var emailPat=/^(.+)@(.+)$/
	var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]"
	var validChars="\[^\\s" + specialChars + "\]"
	var quotedUser="(\"[^\"]*\")"
	var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/
	var atom=validChars + '+'
	var word="(" + atom + "|" + quotedUser + ")"
	var userPat=new RegExp("^" + word + "(\\." + word + ")*$")
	var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$")
	var matchArray=emailStr.match(emailPat)
	if (matchArray==null) {
		alert("Email address seems incorrect (check @ and .'s)")
		return false
	}
	var user=matchArray[1]
	var domain=matchArray[2]

	if (user.match(userPat)==null) {
		alert("The username doesn't seem to be valid.")
		return false
	}
	var IPArray=domain.match(ipDomainPat)
	if (IPArray!=null) {
		// this is an IP address
		  for (var i=1;i<=4;i++) {
			if (IPArray[i]>255) {
				alert("Destination IP address is invalid!")
			return false
			}
		}
		return true
	}
	
	var domainArray=domain.match(domainPat)
	if (domainArray==null) {
		alert("The domain name doesn't seem to be valid.")
		return false
	}
	
	var atomPat=new RegExp(atom,"g")
	var domArr=domain.match(atomPat)
	var len=domArr.length
	if (domArr[domArr.length-1].length<2 || 
		domArr[domArr.length-1].length>3) {
	   alert("The address must end in a three-letter domain, or two letter country.")
	   return false
	}
	if (len<2) {
	   var errStr="This address is missing a hostname!"
	   alert(errStr)
	   return false
	}
	return true;
}

function submit_contactform()
{
	// Setup Defaults
	var AjaxForm = 1;
	var myform = document.contact_form;
	var ErrorColour = '#FF0000';
	
	// Reset all Background Colours
	
	myform.name.style.backgroundColor = '';
	myform.telephone.style.backgroundColor = '';
	myform.emailaddress.style.backgroundColor = '';
	
	// Check all fields
	
	var checked = 1;
		
	if (checked == 1 && myform.name.value == "")
	{
		myform.name.style.backgroundColor = ErrorColour;
		myform.name.focus();
		alert('You must enter a name.');
		checked = 0;
	}
	if (checked == 1 && myform.name.value.length < 3)
	{
		myform.name.style.backgroundColor = ErrorColour;
		myform.name.focus();
		alert('You must enter a name that is longer than 3 characters.')
		checked = 0;
	}
	if (checked == 1 && myform.emailaddress.value == "")
	{
		myform.emailaddress.style.backgroundColor = ErrorColour;
		myform.emailaddress.focus();
		alert('You must enter an email address.');
		checked = 0;
	}
	
	var emailaddress = myform.emailaddress.value;
	
	if (checked == 1 && emailCheck(emailaddress) != true)
	{
		myform.emailaddress.style.backgroundColor = ErrorColour;
		myform.emailaddress.focus();
		alert('You must enter a valid email address .');
		checked = 0;
	}
	if (checked == 1 && myform.telephone.value == "")
	{
		//alert('You must enter an email address.')
		var confirm_tel = confirm('Are you sure you want to submit the form without a telephone number included?');
		if (!confirm_tel)
		{
			myform.telephone.style.backgroundColor = ErrorColour;
			myform.telephone.focus();
			checked = 0;
		}
	}
	if (checked == 1 && myform.code.value == "")
	{
		myform.code.style.backgroundColor = ErrorColour;
		myform.code.focus();
		alert('You must enter the security code to continue.');
		checked = 0;
	}
	
	// If all fields checked, submit form via Ajax
	if (checked == 1)
	{
		if (AjaxForm == 1)
		{
			// Declare Variables
			var name = myform.name.value.escapeHTML();
			var emailaddress = myform.emailaddress.value.escapeHTML();
			var telephone = myform.telephone.value.escapeHTML();
			var message = myform.message.value.escapeHTML();
			
			var url = 'ajax.php?method=contact&name=' + name + '&emailaddress=' + emailaddress + '&telephone=' + telephone + '&message=' + message;
	
			new Ajax.Request(url, {
				method: 'get',
				onLoading: function() {
					$('contact_form_return').remove();
					createoverlayloader();
				},
				onComplete: function(request) {
					document.getElementById('contact_form').innerHTML = request.responseText;
					destroyoverlayloader();
				}
			});
		}
		else
		{
			document.myform.submit();
		}
	}
	
}

function replace(string,text,by) {
// Replaces text with by in string
    var strLength = string.length, txtLength = text.length;
    if ((strLength == 0) || (txtLength == 0)) return string;

    var i = string.indexOf(text);
    if ((!i) && (text != string.substring(0,txtLength))) return string;
    if (i == -1) return string;

    var newstr = string.substring(0,i) + by;

    if (i+txtLength < strLength)
        newstr += replace(string.substring(i+txtLength,strLength),text,by);

    return newstr;
}
// Automatically add classnames to Sidebar pictures for "the Matt Effect"


