/******************************************************************* 
* Send Email
***********************************************************************/

var xmlHttp; var viewing = 0;

function sendEmail(){
	
	//Prevent sending of email if form is disabled
	if(document.getElementById('form-name').disabled){return false;}
	
	//Delete existing notes
	if(document.getElementById('sending') != null){document.getElementById('submission').removeChild(document.getElementById('sending'));}

	var submission = document.getElementById('submission');	
	
	if(document.getElementById('form-name').value == 'Name'){
		submission.innerHTML = '<div id="sending">Invalid name</div>'+submission.innerHTML
	}
	else if(document.getElementById('form-email').value == 'Email' || !isValidEmail(document.getElementById('form-email').value)){
		submission.innerHTML = '<div id="sending">Invalid email address</div>'+submission.innerHTML
	}
	else if(document.getElementById('form-message').value == 'Message'){
		submission.innerHTML = '<div id="sending">Please enter you message</div>'+submission.innerHTML
	}
	else{
		
		//Check we can use AJAX
		xmlHttp = GetXmlHttpObject();
		if (xmlHttp == null){document.getElementById('sending').innerHTML = 'Your browser does not support AJAX<br>Please contact:<br><a href="mailto: tla@townshendla.com">tla@townshendla.com</a>'; return false;}
		
		var form_name = document.getElementById('form-name').value;
		var form_email = document.getElementById('form-email').value;
		var form_message = document.getElementById('form-message').value;
		
		document.getElementById('form-name').disabled = true;
		document.getElementById('form-email').disabled = true;
		document.getElementById('form-message').disabled = true;
		submission.innerHTML = '<div id="sending" class="underline">Sending Email<br><br><img src="../images/loading.gif"></div>'+submission.innerHTML;
		
		var params = "request=contact&formName=" + form_name + "&formEmail=" + form_email + "&formMessage=" + form_message;
		
		var url = '../database.php?request=contact&rand='+Math.random();
		xmlHttp.onreadystatechange = function() {callbackSendEmail();}
		xmlHttp.open("POST",url,true);
		xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		xmlHttp.setRequestHeader("Content-length", params.length);
		xmlHttp.setRequestHeader("Connection", "close");
		xmlHttp.send(params);
	}
}

function callbackSendEmail(){
	if(xmlHttp.readyState == 4){
    if(xmlHttp.responseText == 'emailSent'){
      setTimeout('sentEmail()', 1000);
		}
		else{
      alert (xmlHttp.responseText);
    }
	}
}

function sentEmail(){
	document.getElementById('sending').innerHTML = 'Email Sent';
	setTimeout('sentEmailClean()', 2000);
}

function sentEmailClean(){
	if(document.getElementById('sending') != null){document.getElementById('submission').removeChild(document.getElementById('sending'));}
	
	document.getElementById('form-name').disabled = false;
	document.getElementById('form-email').disabled = false;
	document.getElementById('form-message').disabled = false;
	
	resetEmail();
}

function resetEmail(){
	
	//Prevent form reset if form is disabled
	if(document.getElementById('form-name').disabled){return false;}
	
	document.getElementById('form-name').value='Name';
	document.getElementById('form-email').value='Email';
	document.getElementById('form-message').value='Message';
	
	//Delete existing notes
	if(document.getElementById('sending') != null){document.getElementById('submission').removeChild(document.getElementById('sending'));}
}

//Basic validation of email address
function isValidEmail(str) {
   return (str.indexOf(".") > 2) && (str.indexOf("@") > 0);
}

//AJAX Core
function GetXmlHttpObject(){
  var xmlHttp = null;
  try{/*Firefox, Opera 8.0+, Safari*/xmlHttp=new XMLHttpRequest();}
  catch (e){/*Internet Explorer*/
    try{xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");}
    catch (e){xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");}
  }
  return xmlHttp;
}

/******************************************************************* 
* Form functions
***********************************************************************/

function inputFocus(object, inputtext){
	if(object.value == inputtext){
		object.value = "";
	}
}

function inputBlur(object, inputtext){
	if(object.value == ""){
		object.value = inputtext;
	}
}

/******************************************************************* 
* Map Thumbnails
***********************************************************************/

function showMapThumb(projectID, location, title, folder){
	
	viewing = projectID;
	
	document.getElementById("map-"+projectID).src = location+'images/map-point-over.png';
	
	//Check if AJAX is allowed, if not then do nothing
	xmlHttp = GetXmlHttpObject();
  if (xmlHttp == null){return false;}
	
	var url = location + 'database.php?request=thumbs&id='+projectID+'&rand='+Math.random();
  xmlHttp.onreadystatechange = function() {callbackShowMapThumb(projectID, location, title, folder);}
  xmlHttp.open("GET",url,true);
  xmlHttp.send(null);
  
  //Create loading stuff
  var objBody = document.getElementsByTagName("body").item(0);
  var objOverlay = document.createElement("div");
  objOverlay.setAttribute('id','map-point-box');
  objOverlay.setAttribute('class','map-point-box-nopicts');
	objOverlay.setAttribute('className','map-point-box-nopicts');
	objOverlay.style.top = (calculateOffsetTop(document.getElementById("map-point-"+projectID)) - 35) + "px";
  objOverlay.style.left = (calculateOffsetLeft(document.getElementById("map-point-"+projectID)) - 81) + "px";
  objBody.insertBefore(objOverlay, objBody.firstChild);
  objOverlay.innerHTML = '<img src="'+location+'images/loading-2.gif" style="margin-top: 6px;">';
  
  //Test fade in
  //changeOpacity('map-point-box', 0);
  //Fade.opacity['map-point-box'] = 0;
  //Fade.fadeIn('map-point-box');
  
  return false;
}

function callbackShowMapThumb(projectID, location, title, folder){
	if(xmlHttp.readyState == 4 && viewing == projectID){
		
		var objOverlay = document.getElementById('map-point-box');
		
		overlay = ''+title+'<br>';
		
		if(xmlHttp.responseText !== ''){
			objOverlay.setAttribute('class','map-point-box');
			objOverlay.setAttribute('className','map-point-box');
			objOverlay.style.top = (calculateOffsetTop(document.getElementById("map-point-"+projectID)) - 129) + "px";
			
			images = xmlHttp.responseText.split("|");
			thumbnail = images[0];
			overlay += '<img src="'+location+'images/projects/'+folder+'/'+thumbnail+'">';
		}
		else{
			objOverlay.setAttribute('class','map-point-box-nopicts');
			objOverlay.setAttribute('className','map-point-box-nopicts');
			objOverlay.style.top = (calculateOffsetTop(document.getElementById("map-point-"+projectID)) - 35) + "px";
		}
		
		objOverlay.innerHTML = overlay;
	}
}

function hideMapThumb(location, projectID){
	if(document.getElementById('map-point-box') != null){document.body.removeChild(document.getElementById('map-point-box'));}
	document.getElementById("map-"+projectID).src = location+'images/map-point.png';
	viewing = 0;
}

//Calculate the offsets recursively
function calculateOffsetTop(r){
  return calculateAttribute(r,'offsetTop');
}

function calculateOffsetLeft(r){
  return calculateAttribute(r,'offsetLeft');
}

function calculateAttribute(r,attribute){
  var amount = 0;
  while(r){
    amount += r[attribute]; 
    r = r.offsetParent;
  }
  return amount;
}

/******************************************************************* 
* Project Thumbnails
***********************************************************************/

var currentThumb = null;

function showProjectThumb(id, thumb){
	
	//Check if this is the current image
	if(id != fadeOldImage){
    
    //Update the current thumbnail
    currentThumb = id;
	
    var objBody = document.getElementsByTagName("body").item(0);
    var objOverlay = document.createElement("div");
    objOverlay.setAttribute('id','projects-thumb');
    objOverlay.setAttribute('class','projects-thumb');
    objOverlay.setAttribute('className','projects-thumb');
    objOverlay.style.top = (calculateOffsetTop(document.getElementById("thumbnail-"+id)) - 112) + "px";
    objOverlay.style.left = (calculateOffsetLeft(document.getElementById("thumbnail-"+id)) - 71) + "px";
    objBody.insertBefore(objOverlay, objBody.firstChild);
    objOverlay.innerHTML = '<img src="' + thumb + '">';
  }
  
  //Test fade in
  //changeOpacity('projects-thumb', 0);
  //Fade.opacity['projects-thumb'] = 0;
  //Fade.fadeIn('projects-thumb');
}

function cleanProjectThumb(id){
	if(document.getElementById('projects-thumb') != null){
    if(!id || id == currentThumb){
      document.getElementById('projects-thumb').parentNode.removeChild(document.getElementById('projects-thumb'));
    }
	}
}

var fadeDirection = null;
var fadeOpacity = 100;
var fadeRun = false;
var fadeOldImage = 1;
var fadeNewImage = 0;

function fadeProjectImage(newImage){
  
  //Check that we have not clicked the same button.
  if(newImage != fadeNewImage){
    
    //Clear thumbnail
    cleanProjectThumb(newImage);
    
    //Pause slideshow
    slideCountdown = 11;
    
    fadeDirection = "fadeOut";
    fadeNewImage = newImage;
    if(!fadeRun){fadeProjectImageRun();}
  }
}

function fadeProjectImageRun(){

  if(fadeDirection == "fadeOut"){
    
    fadeOpacity = fadeOpacity - 5;
    
    if(fadeOpacity <= 0){
      
      fadeOpacity = 0;
      fadeDirection = "fadeIn";
      
      changeOpacity('image-holder', fadeOpacity);
      
      document.images['project-image'].src = arr_images[fadeNewImage];
      
      //Update thumbnail box
      document.getElementById("thumbnail-" + fadeOldImage).setAttribute("class", "links");
      document.getElementById("thumbnail-" + fadeOldImage).className = "links";
      document.getElementById("thumbnail-" + fadeNewImage).setAttribute("class", "links-selected");
      document.getElementById("thumbnail-" + fadeNewImage).className = "links-selected";
      
      //Update old image as new image
      fadeOldImage = fadeNewImage;
      
    }
    else{
      changeOpacity('image-holder', fadeOpacity);
    }

    fadeRun = true;
  }
  
  if(fadeDirection == "fadeIn"){
    
    fadeOpacity = fadeOpacity + 5;
    
    if(fadeOpacity >= 100){
      fadeOpacity = 100;
      fadeDirection = null;
      changeOpacity('image-holder', fadeOpacity);
    }
    else{
      changeOpacity('image-holder', fadeOpacity);
      fadeRun = true;
    }    
  }
  
  if(fadeRun){setTimeout("fadeProjectImageRun()", 20);}
}

/******************************************************************* 
* Slideshow names
***********************************************************************/

var slideCountdown = 6;

function slideshow(){
  
  //Check that there are enough images for the slideshow then run
  if(arr_images.length > 2){
    
    slideCountdown = slideCountdown - 1
    
    if(slideCountdown <= 0){
      if(arr_images.length == fadeOldImage + 1){
        fadeProjectImage(1);
      }
      else{
        fadeProjectImage(fadeOldImage + 1);
      }
      slideCountdown = 6;
    }
    setTimeout("slideshow()", 1000);
  }
}

/******************************************************************* 
* Profile names
***********************************************************************/

function loadName(id){

  //Check if AJAX is allowed, if not then do nothing
	xmlHttp = GetXmlHttpObject();
  if (xmlHttp == null){return false;}
	
	var url = '../database.php?request=names&id='+id+'&rand='+Math.random();
  xmlHttp.onreadystatechange = function() {callbackLoadName(id);}
  xmlHttp.open("GET",url,true);
  xmlHttp.send(null);
}

function callbackLoadName(id){
	if(xmlHttp.readyState == 4){
    if(xmlHttp.responseText !== ''){
      document.getElementById('profile-left').innerHTML = xmlHttp.responseText;
    }
	}
}

/******************************************************************* 
* Image fader
* Change this to an object for images so dont have to individual define before:
* http://www.javascript-fx.com/fade_rollovers/general_help/help.html
* or http://brainerror.net/scripts/javascript/blendtrans/
***********************************************************************/

//Change the opacity for different browsers
function changeOpacity(obj, opacity){
	var object = document.getElementById(obj); 
	object.style.opacity = (opacity / 100);
	object.style.MozOpacity = (opacity / 100);
	object.style.KhtmlOpacity = (opacity / 100);
	object.style.filter = "alpha(opacity=" + opacity + ")";
}

//Create object
if(!window.Fade){Fade = new Object();}

//Arrays to hold the states
Fade.states = new Array();
Fade.opacity = new Array();
Fade.running = false;

Fade.fadeIn = function(obj){
  
  //Check if we have defined opacity
  if(Fade.opacity[obj] == null){Fade.opacity[obj] = 0;}
  
  Fade.states[obj] = "fadeIn";
  
  Fade.startrun();
}

Fade.fadeOut = function(obj){
  
  //Check if we have defined opacity
  if(Fade.opacity[obj] == null){Fade.opacity[obj] = 100;}

  Fade.states[obj] = "fadeOut";
  
  Fade.startrun();
}

Fade.startrun = function(){
	if(!Fade.running){Fade.run();}
}

Fade.run = function(){
  Fade.running = false;

  for(obj in Fade.states){
  
    if(Fade.states[obj] == "fadeIn"){
      Fade.opacity[obj] = Fade.opacity[obj] + 5;
      
      if(Fade.opacity[obj] >= 100){
        Fade.states[obj] = "off";
        Fade.opacity[obj] = 100;
      }
      else{
        Fade.running = true;
      }
      
      //Check that the object exists then change opacity
      if(document.getElementById(obj) != null){
        changeOpacity(obj, Fade.opacity[obj]);
      }
    }
    
    if(Fade.states[obj] == "fadeOut"){
      Fade.opacity[obj] = Fade.opacity[obj] - 5;
      
      if(Fade.opacity[obj] <= 0){
        Fade.states[obj] = "off";
        Fade.opacity[obj] = 0;
      }
      else{
        Fade.running = true;
      }
      
      //Check that the object exists then change opacity
      if(document.getElementById(obj) != null){
        changeOpacity(obj, Fade.opacity[obj]);
      }
    }
  }
  
  if(Fade.running){setTimeout("Fade.run()", 20);}
}

/******************************************************************* 
* Scroll text
***********************************************************************/

var scrollTop = 0;
var nextEvent = '';

function loadScroll(textheight){
  
  scrollHeight = document.getElementById("text").offsetHeight;
  
  if(scrollHeight > textheight){
    document.getElementById("scrollbar").innerHTML = '<a href="javascript:void(0)" onmouseover="scrolldiv(1, ' + textheight + ')" onmouseout="stopscroll()">&uarr;</a><br><a href="javascript:void(0)" onmouseover="scrolldiv(-1, ' + textheight + ')" onmouseout="stopscroll()">&darr;</a>';
  }

}

function scrolldiv(amount, textheight){
  scrollHeight = document.getElementById("text").offsetHeight;
  
  if(scrollTop + amount <= 0 && scrollTop + scrollHeight + amount >= textheight){
    scrollTop += amount;
    document.getElementById("text").style.top = scrollTop + "px";
    nextEvent = setTimeout('scrolldiv('+amount+', '+textheight+')', 15);
  }
}

//Stop the scrolling!
function stopscroll(){
  if(nextEvent){clearTimeout(nextEvent);}
}