var mousePos = null;
var dragObject  = null;
var txtArea = null;
var mouseOffset = null;
var txtAreaHeight = null;

function getMouseOffset(target, ev) {
	ev = ev || window.event;

	var docPos    = getPosition(target);
	var mousePos  = mouseCoords(ev);
	return {x:mousePos.x - docPos.x, y:mousePos.y - docPos.y};
}

function getPosition(e) {
	var left = 0;
	var top = 0;

	while (e.offsetParent) {
		left += e.offsetLeft;
		top += e.offsetTop;
		e = e.offsetParent;
	}

	left += e.offsetLeft;
	top  += e.offsetTop;

	return {x:left, y:top};
}


function mouseMove(ev) {
	ev = ev || window.event;
	mousePos = mouseCoords(ev);
	
	if(dragObject) {
		dragObject.style.position = 'absolute';
		dragObject.style.top = Math.max(0,(mousePos.y - mouseOffset.y)) + "px";
		dragObject.style.left = Math.max(0,(mousePos.x - mouseOffset.x)) + "px";
	}
	
	if(txtArea) {
		txtArea.style.height = Math.max(30,(txtAreaHeight + mousePos.y - mouseOffset.y)) + "px";
	}
		
	return false;
}

function mouseUp() {
	dragObject = null;
	txtArea = null;
}


function dragbar(what,ev) {
	txtArea = document.getElementById(what);
	mouseOffset = mousePos;
	txtAreaHeight = txtArea.clientHeight;
	return false;
}

document.onmousemove = mouseMove;
document.onmouseup = mouseUp;

function makeDraggable(item) {
	if (!item) return;
	item.onmousedown = function(ev) {
		dragObject  = this;
		mouseOffset = getMouseOffset(this, ev);
		return false;
	}
}

function mouseCoords(ev) {
	if(ev.pageX || ev.pageY) {
		return {x:ev.pageX, y:ev.pageY};
	}
	return {
		x:ev.clientX + document.body.scrollLeft - document.body.clientLeft,
		y:ev.clientY + document.body.scrollTop - document.body.clientTop
	};
}

/************************************************************/

var zix = 100;

function beginDrag(what,ev) {
	dragObject = document.getElementById(what);
	mouseOffset = getMouseOffset(dragObject,ev);
	dragObject.style.zIndex = zix++;
	return false;
}

function onTop(what) {
	document.getElementById(what).style.zIndex = zix++;
	return true;
}

function endDrag() {
	dragObject = null;
	return false;
}

function cancelAlert(what) {
	document.body.removeChild(document.getElementById(what));
}


function createAlert(title,body) {
	if (!document.createElement){
		alert(title+'\n'+body.replace(/<li(\s+[^>]*)*>/gi,'* ').replace(/<[^>]+>/g, ''));
		return false;
	}
	var alertDiv = document.createElement('div');
	alertID = 'alert_'+(zix++);
	alertDiv.setAttribute('id',alertID);
	alertDiv.setAttribute('class','floatAlert');
	html = bip();
	html += '<h2 onmousedown="return beginDrag(\''+alertID+'\',event)" ';
	html += 'onmouseup="return endDrag()">'+title+'<\/h2>';
	html += '<div onmousedown="return onTop(\''+alertID+'\')">';
	html += body;
	html += '<p class="alertBtns">';
	html += '<button onclick="return cancelAlert(\''+alertID+'\')">OK';
	html += '<\/button><\/p><\/div>';
	alertDiv.innerHTML = html;
	alertDiv.style.visibility='hidden';
	alertDiv.style.zIndex=zix++;
	document.body.appendChild(alertDiv);
	w = alertDiv.clientWidth;
	h = alertDiv.clientHeight;
	x0 = document.documentElement.scrollLeft || document.body.scrollTop;
	y0 = document.documentElement.scrollTop || document.body.scrollTop;
	x = Math.max(0,x0+(window.innerWidth-w)/2);
	y = Math.max(0,y0+(window.innerHeight-h)/2);
	alertDiv.style.left = x+'px';
	alertDiv.style.top = y+'px';
	
	alertDiv.style.visibility='visible';
}

function bip(){
	if (/MSIE \d+\.\d+;/.test(navigator.userAgent)) return ''; // won't work in IE
	var s = '<embed src="data:audio/wav;base64,';
	s += "UklGRrwBAABXQVZFZm10IBAAAAABAAEAQB8AAIA+AAACABAAZGF0YZgBAAD//9cBYQYLC8EMNAn";
	for (i=0; i<11; i++) s += "BAB3zruk65q7pHvP//+MMUxbFGVMW4ww";
	s += "//1HzXepr5w7rHPQAAH8LkxMzFuQStQoAALH1fe4s7C7vevb//x8Jcw9zEcQOUQgCABL4nfLu8E";
	s += "3z3fj+/78GVQuwDKUK8gUBAHL6vPax9Wr3PfsAAFwENgfvB4UGkgMAANT82vpz+oj7nv0CAPoBF";
	s += "gMtA2gCMAEAADX/9/42/6j/AQA=";
	s += '" hidden="true" autostart="true" style="position:absolute"><\/embed>';
	return s;
}

function LTrim(str) {
  for (var k=0; k<str.length && str.charAt(k) <= " "; k++);
  return str.substring(k,str.length);
}

function RTrim(str) {
  for (var j=str.length-1; j>=0 && str.charAt(j)<=" "; j--);
  return str.substring(0,j+1);
}

function Trim(str) {
  return LTrim(RTrim(str));
}

function untaintForm() {
	this.style.backgroundColor='';
	this.onfocus=this.oldfocus;
}

function taintForm(which) {
	e = document.getElementById(which);
	e.style.backgroundColor='#ff0';
	e.oldfocus=e.onfocus;
	e.blur();
	e.onfocus=untaintForm;
}

function validEnqForm(which) {
	var e = which.elements;
	var sbj=e['subject'].options[e['subject'].selectedIndex].value;
	var nam=(e['name'].value=Trim(e['name'].value));
	var phn=(e['phone'].value=Trim(e['phone'].value));
	var eml=(e['email'].value=Trim(e['email'].value));
	var msg=(e['body'].value=Trim(e['body'].value));
	var errors = new Array();
	var i=0;
	if (nam==''&&phn==''&&eml==''&&msg=='') {
		createAlert("Error","<p>You're trying to submit an empty form. Please fill it in first.</p>");
		return false;
	}
	if(sbj=='0'){
		errors[i++]="Please choose a subject line from the drop-down menu";
		taintForm('subject');
	}
	if(nam.length<3){
		errors[i++]="Please provide your full name";
		taintForm('name');
	}
	if(nam.length>200){
		errors[i++]="Please make your name a bit shorter";
		taintForm('name');
	}
	if(phn=='' && eml==''){
		errors[i++]="You have to provide either a phone number or an email address. You can't leave both empty.";
		taintForm('phone');
		taintForm('email');
	}
	if(phn.length > 80 || phn.length>0 && !(/\d{5}|\d{3}[\s\-]{1,3}\d{3}|\d\d[\s\-]{1,3}\d\d[\s\-]{1,3}\d\d/.test(phn))){
		errors[i++]="Please provide a valid phone number, or leave that part empty";
		taintForm('phone');
	}
	if(eml.length>0 && !(/^(\S{1,64}\.)*\S{1,64}@([\w\-]{1,64}\.){1,4}[a-z]{2,10}$/i.test(eml))){
		errors[i++]="The email address you provided is invalid.";
		taintForm('email');
	}
	if(msg.length<2){
		errors[i++]="You don't seem to have typed in your message yet.";
		taintForm('body');
	}
	if(msg.split(/https?:\/\//i).length>2){
		errors[i++]="I'm sorry, but to cut down on spam submissions, I've had to limit the number of URLs per message to 2. Please reduce the number of URLs in your message and try again.";
		taintForm('body');
	}
	if (errors.length==0) return true;
	var html='<ul>\n';
	for (var j=0;j<i;j++) html+='<li>'+errors[j]+'</li>\n';
	html+='</ul>';
	pl = (i==1) ? '' : 's';
	html='<p>Please fix the following problem'+pl+' and try submitting the form again:</p>'+html;
	createAlert('Form Not Submitted',html);
	return false;
}

function nogo() {
	return false;
}


sbtn = 0;
sbtntxt = '';
sbtnw='';

mustcheck=true;

function checkEnqForm(which) {
	if (!mustcheck) return true;
	else if (validEnqForm(which)) {
		return true;
	}
	else {
		if (savebtn) resetBtn(savebtn);
		if (spinnerimg) spinnerimg.src="/img/spin0.png";
		return false;
	}
}

function resetBtn(btn) {
	btn.onmousedown=null;
	btn.style.width=btn.savewidth;
	btn.innerHTML=btn.savetxt;
	btn.style.color='#000';
	document.getElementById(btn.savespinner).src="/img/spin0.png";
}

savebtn=0;
spinnerimg=0;

function debounce(btn,busytxt,spinnerid) {
	if (btn.innerHTML==busytxt) return false;
	w=btn.offsetWidth;
	
	btn.savewidth=btn.style.width;
	btn.savetxt=btn.innerHTML;
	btn.savespinner=spinnerid;
	
	btn.style.width=w+'px';
	btn.innerHTML=busytxt;
	btn.onmousedown=nogo;
	btn.style.color='#678';
	savebtn=btn;
	document.onunload='resetBtn(savebtn)';
	spinnerimg=document.getElementById(spinnerid);
	spinnerimg.src="/img/spin.gif";
	btn.blur();
	return true;
}

function disableForm(which) {
	e=document.getElementById(which).elements;
	for(i=0;i<e.length;i++)e[i].disabled='disabled';
	return true;
}


function noEnter(e) {
  var keynum;
  if (window.event) return (e.keyCode!=13);
  else if (e.which) return (e.which!=13);
  return true;
}

function noWhiteSpace(e) {
	var keynum=65; // default to 'A'
	var char;
	if (window.event) keynum = e.keyCode;
	else if(e.which) keynum = e.which;
	char=String.fromCharCode(keynum);
	return (!(/\s/.test(char)));
}
