/* Dollar function, Ajax JSON request handler, Response message handler, Event handler, Form checker, Cookie handler */
function $(i){return document.getElementById(i)};
function JsonRequest(mn,cb){this.cb=typeof mn==='function'?mn:cb;this.ecb=function(r){alert(r['message']?r['message']:'Error id:'+r['error'])};this.threads=[];this.threadsBusy=[]};JsonRequest.prototype.setErrorCallback=function(c){this.ecb=c};JsonRequest.prototype.makeRequest=function(url,p,rType){var that=this,i;if(!p)p=null;url+=(url.indexOf('?')>-1?'&':'?')+'json=1';if(!(i=this.getThread())==null)return false;r=this.threads[i];if(p){r.open('POST',url,true);r.setRequestHeader("Content-Type","application/x-www-form-urlencoded");r.setRequestHeader("Content-length",p.length);r.setRequestHeader("Connection","close")}else r.open('GET',url,true);if(typeof rType==='function')r.onreadystatechange=function(){if(that.threads[i].readyState==4){that.clearThread(i);rType(that.evalR(that.threads[i].responseText))}};else if(this.callback)r.onreadystatechange=function(){if(that.threads[i].readyState==4){that.clearThread(i);that.callback(that.evalR(that.threads[i].responseText),rType)}};else r.onreadystatechange=function(){if(that.threads[i].readyState==4)that.clearThread(i)};r.send(p);return true};JsonRequest.prototype.clearThread=function(i){var that=this;setTimeout(function(){that.threadsBusy[i]=false},2000)};JsonRequest.prototype.callback=function(r,t){if(r['error'])this.ecb(r);else this.cb(r,t)};JsonRequest.prototype.getThread=function(){for(i=0;i<this.threads.length;i++){if(!this.threadsBusy[i])break}if(!this.threads[i]){this.threads[i]=this.makeObj()}this.threadsBusy[i]=true;return this.threads[i]?i:null};JsonRequest.prototype.makeObj=function(){if(window.XMLHttpRequest)r=new XMLHttpRequest();else if(window.ActiveXObject){try{r=new ActiveXObject("Msxml2.XMLHTTP")}catch(e){try{r=new ActiveXObject("Microsoft.XMLHTTP")}catch(e){}}}return r?r:false};JsonRequest.prototype.evalR=function(j){return j!='()'?eval('('+j+')'):{}};
function MessageBox(){this.fadeInc=0.1;this.fadeInt=60;this.mbox=null;this.timer=[];this.messages=[]};MessageBox.prototype.showMessage=function(message,type,timeout){if(!type)type='pos';if(!this.mbox)this.createDiv();var i=this.messages.length,that=this;this.messages[i]=document.createElement('div');this.messages[i].style.display='none';this.messages[i].className=type;this.messages[i].innerHTML=message;this.messages[i].onmouseover=function(){that.hideMessage(i)};this.mbox.appendChild(this.messages[i]);this.fade(i,1);setTimeout(function(){that.hideMessage(i)},(timeout?timeout:5)*1000)};MessageBox.prototype.hideMessage=function(i){this.fade(i,0)};MessageBox.prototype.fade=function(i,dir){if(!this.messages[i])return;var op,that=this;if(!(op=parseFloat(this.messages[i].getAttribute('op'))))op=dir?0:1;if(op<0)op=0;if(op>1)op=1;this.messages[i].style.opacity=op;this.messages[i].style.filter='Alpha(opacity='+(op*100)+')';if(op)this.messages[i].style.display='block';else this.messages[i].style.display='none';if(dir&&op<1||!dir&&op>0){this.messages[i].setAttribute('op',op+that.fadeInc*(dir?1:-1));if(this.timer[i]!=null)clearTimeout(this.timer[i]);this.timer[i]=setTimeout(function(){that.fade(i,dir)},this.fadeInt)}else if(!dir&&op<=0){this.mbox.removeChild(this.messages[i]);this.messages[i]=null}};MessageBox.prototype.createDiv=function(p){var that=this;this.mbox=document.createElement('div');this.mbox.className='responseContainer';(p?p:document.body).appendChild(this.mbox)};// addEvent manager from twinhelix.com
var addEvent=function(o,t,f,l){var d='addEventListener',n='on'+t,rO=o,rT=t,rF=f,rL=l;if(o[d]&&!l)return o[d](t,f,false);if(!o._evts)o._evts={};if(!o._evts[t]){o._evts[t]=o[n]?{b:o[n]}:{};o[n]=new Function('e','var r=true,o=this,a=o._evts["'+t+'"],i;for(i in a){o._f=a[i];r=o._f(e||window.event)!=false&&r;o._f=null}'+(t=='beforeunload'?'if(r)':'')+'return r');if(t!='unload')addEvent(window,'unload',function(){removeEvent(rO,rT,rF,rL)})}if(!f._i)f._i=addEvent._i++;o._evts[t][f._i]=f};addEvent._i=1;var removeEvent=function(o,t,f,l){var d='removeEventListener';if(o[d]&&!l)return o[d](t,f,false);if(o._evts&&o._evts[t]&&f._i)delete o._evts[t][f._i]};
function FormCheck(mbox){this.mbox=mbox};FormCheck.prototype.check=function(f,prompt,pwdLength){var r=true;if(pwdLength===null)pwdLength=[4,10];var u,t,msg='',pwd,eColor='#FFA';for(i=0;i<f.elements.length;i++){el=f.elements[i];check=el.getAttribute('check');t=-1;if(!check)continue;else if(el.tagName=='SELECT'&&!el.options[el.selectedIndex].value){t=u?'':'Please fill in all fields';u=true}else if(el.getAttribute('type')=='checkbox'&&!el.checked){t=u?'':'Please fill in all fields';u=true}else if(check=='email'&&!this.isEmail(el.value))t='Email address is not valid';else if(parseInt(check)==check&&el.value.length<check||check.charAt(0)=='/'&&check.charAt(check.length-1)=='/'&&!el.value.match(new RegExp(check.substr(1,check.length-2)))){t=u?'':'Please fill in all fields';u=true}else if(check=='pwd'&&!pwd&&(el.value.length<pwdLength[0]||el.value.length>pwdLength[1]))t='Password must be between '+pwdLength[0]+' and '+pwdLength[1]+' characters';else if(check=='pwd'&&!pwd)pwd=el.value;else if(check=='pwd'){if(el.value!=pwd){t='Password fields do not match'}pwd=''}if(t!=-1){msg+=t?t+'\n':'';el.style.background=eColor;r=false}else el.style.background='none'}if(msg&&prompt)r=confirm('FORM ERROR:\n'+msg+'\n\nClick OK to submit anyway,or cancel to return to the form.');else if(msg){if(this.mbox)this.mbox.showMessage(('FORM ERROR:\n'+msg).replace(/\n/g,'<br>'),'neg');else alert('FORM ERROR:\n'+msg)}return r};FormCheck.prototype.isEmail=function(m){var filter=/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;if(filter.test(m))return true;return false};FormCheck.prototype.isNum=function(a){return typeof a=='number'&&isFinite(a)};
function CookieMonster(){};CookieMonster.prototype.get=function(nameOfCookie){if(document.cookie.length>0){var regexp=new RegExp(nameOfCookie+'(\\[.*?\\])?=[^;]*','g'),matches=document.cookie.match(regexp),returnValue={},temp,nameParts;if(matches){for(var i=0;i<matches.length;i++){matches[i]=matches[i].split('=');nameParts=matches[i][0].split(/\]?\[/);temp=returnValue;for(var j=0,jl=nameParts.length;j<jl;j++){nameParts[j]=unescape(nameParts[j])||0;if(j==jl-1){nameParts[j]=nameParts[j].replace(/\]$/,'');temp[nameParts[j]]=unescape(matches[i][1])}else{if(!temp[nameParts[j]]||typeof temp[nameParts[j]]!=='object')temp[nameParts[j]]={};temp=temp[nameParts[j]]}}}}return returnValue[nameOfCookie]}return null};CookieMonster.prototype.set=function(nameOfCookie,value,expireDays){var ExpireDate=new Date(),plus='++'.substring(0,1),that=this;ExpireDate.setTime(ExpireDate.getTime()+(expireDays*24*3600*1000));if(value instanceof Array){for(var i=0;i<value.length;i++)this.set(nameOfCookie+'['+i+']',value[i],expireDays)}else if(typeof value=='object'){for(var i in value)this.set(nameOfCookie+'['+escape(i)+']',value[i],expireDays)}else{document.cookie=nameOfCookie+"="+escape(value)+((expireDays==null)?"":";expires="+ExpireDate.toGMTString())+";path=/"}};CookieMonster.prototype.del=function(nameOfCookie){if(document.cookie.length>0){var regexp=new RegExp(nameOfCookie+'(\\[.*?\\])?=[^;]*','g'),matches=document.cookie.match(regexp),name;if(matches){for(var i=0;i<matches.length;i++){name=matches[i].split('=')[0];document.cookie=name+"=;expires=Thu,01-Jan-70 00:00:01 GMT;path=/"}}}};












function KillSpam(form){
	if (typeof form === 'string') 
		form = $(form);

	// get styles for returned messages etc
	this.getCSS('/ibdg_sendmail/client_side_includes/style.css');
	
	
	
	// set up textarea and textbox analysis
	this.textInputs = [];
	var textareas = form.getElementsByTagName('textarea'),
			inputs = form.getElementsByTagName('input');
	for (var i = 0; i < textareas.length; i++)
		this.textInputs.push(textareas[i]);
	for (var i = 0; i < inputs.length; i++){
		if (inputs[i].type == 'text')
			this.textInputs.push(inputs[i]);
	}
	
	for (var i = 0; i < this.textInputs.length; i++){
		this.textInputs[i].ksInfo = {'clicks' : 0, 'keypresses' : 0, 'time' : 0};
		
		// record length of time in focus
		addEvent(this.textInputs[i], 'focus', function(){
			var startDate = new Date(),
			onblur = function(){
				var endDate = new Date();
				this.ksInfo.time = (this.ksInfo.time || 0) + endDate.getTime() - startDate.getTime();
				removeEvent(this, 'blur', onblur);
			};
			
			addEvent(this, 'blur', onblur);
		});
		
		// record number of clicks and keypresses
		addEvent(this.textInputs[i], 'click', function(){
			this.ksInfo.clicks = (this.ksInfo.clicks || 0) + 1;
		});
		addEvent(this.textInputs[i], 'keypress', function(){
			this.ksInfo.keypresses = (this.ksInfo.keypresses || 0) + 1;
		});
	}
	
	
	var that = this;
	
	// add onsubmit event to form
	if (!form.onsubmit)
		form.onsubmit = function(){
			return that.onSubmit(this);
		};
	
	
	// show response if one stored in cookie
	var r = this.cookies.get('response');
	if (r){
		//console.log(r);
		this.mbox.showMessage(r.message, r.type);
		this.cookies.del('response');
	}
};

KillSpam.prototype.json = new JsonRequest();
KillSpam.prototype.mbox = new MessageBox();
KillSpam.prototype.cookies = new CookieMonster();
KillSpam.prototype.formCheck = new FormCheck(KillSpam.prototype.mbox);

/* Attempts to parse the form, add any extra info gathered about the user's behaviour, and send the request via AJAX
 * Returns false on success (to kill form submission)
 * Attached to the form's onsubmit handler in init() so long as there is no existing onsubmit event handler - if
 * so will need to be manually attached
 * Also, form can only be submitted once every 3 seconds (stops double clicks and and repeated clicking from sending multiple messages)
 */
KillSpam.prototype.onSubmit = function(form){
	var that = this;
	
	if (this.isSubmitting || !this.formCheck.check(form))
		return false; 
	
	this.isSubmitting = true;
	setTimeout(function(){
		that.isSubmitting = false;
	}, 3000);
	
	// parse form and add extra data
	var post = this.parseForm(form) + '&' + this.encodeToUrl({'ibdgData' : {'behaviour' : this.getUserData()}});
	
	
	// send via ajax
	this.json.makeRequest('/ibdg_sendmail/send', post, function(data){
		
		if (data.redirect){
			that.cookies.set('response', data.response);
			window.location = data.redirect;// + (data.response ? (data.redirect.match(/\?/) ? '&' : '?') + that.encodeToUrl({'response' : data.response}) : '');
		}
		else {
			if (data.response) {
				that.mbox.showMessage(data.response.message, data.response.type);
				
				if (data.response.type == 'pos') {
					that.clearForm(form);
				}
			}
		}
	});
	
	return false;
};

KillSpam.prototype.getUserData = function(){
	var data = {'textInputs' : []};
	for (var i = 0; i < this.textInputs.length; i++){
		this.textInputs[i].ksInfo.contentLength = this.textInputs[i].value.length;
		data.textInputs.push(this.textInputs[i].ksInfo);
	}
	
	return data;
};


// returns a url string for get/post from a form
KillSpam.prototype.parseForm = function(form){
	var str = '', name, inputs = [
		form.getElementsByTagName('input'),
		form.getElementsByTagName('select'),
		form.getElementsByTagName('textarea')
	];

	// Loop through each list of tags, constructing our string.
	for (var i = 0; i < inputs.length; i++){
		for (var j = 0; j < inputs[i].length; j++){
			if (inputs[i][j] && (name = inputs[i][j].getAttribute('name'))){
				var plus = '++'.substring(0,1); // CodeTrim fix.
				str += escape(name).replace(plus, '%2B') +
				'=' + escape(inputs[i][j].value).replace(plus, '%2B') + '&';
			}
		}
	}

	return str.substring(0, str.length - 1);
};


// returns a url string for get/post from a form
KillSpam.prototype.clearForm = function(form){
	var selects = form.getElementsByTagName('select'),
			textareas = form.getElementsByTagName('textarea'),
			inputs = form.getElementsByTagName('input');

	for (var i = 0; i < selects.length; i++){
		selects[i].selectedIndex = 0;
	}
	for (var i = 0; i < inputs.length; i++){
		if (inputs[i].type == 'text') {
			inputs[i].value = '';
		}
	}
	for (var i = 0; i < textareas.length; i++){
		textareas[i].innerHTML = textareas[i].value = '';
	}
};

// returns a url string for get/post from an object/array
KillSpam.prototype.encodeToUrl = function(obj, parent){
	var str = [],
			plus = '++'.substring(0,1),
			that = this;
			
	if (!parent)
		parent = '';
	
	var process = function(i, val){
		var p = parent ? parent + '[' + escape(i).replace(plus, '%2B') + ']' : i;
		if (typeof val === 'object')
			str.push(that.encodeToUrl(val, p));
		else {
			str.push(p + '=' + escape(val).replace(plus, '%2B'));
		}
	};
	
	
	if (obj instanceof Array){
		for (var i = 0; i < obj.length; i++)
			process(i, obj[i]);
	}
	else {
		for (var i in obj)
			process(i, obj[i]);
	}
	
	return str.join('&');
};

KillSpam.prototype.getCSS = function(path){
	if (document.getElementById('dynamic-css-' + path))
		return 1;
	var head = document.getElementsByTagName("head")[0],
			css = document.createElement('link');
	css.rel = 'text/css';
	css.rel = 'stylesheet';
	css.href = path;
	css.id = 'dynamic-css-' + path;
	head.appendChild(css)
};




// INITIALISATION


var ks = [];

// initialise each form on the page
addEvent(window, 'load', function(){
	if (!ks.length){
		// only auto-initialise if it hasn't already been done manually by the user
		var forms = document.getElementsByTagName('form');
		// look for forms with class 'ibdg_sendmail'
		for (var i = 0; i < forms.length; i++){
			if (forms[i].className.match(/(?:^|\s)ibdg_sendmail(?:$|\s)/))
				ks.push(new KillSpam(forms[i]));
		}
		// if none found, apply to all forms
		if (!ks.length){
			for (var i = 0; i < forms.length; i++){
				ks.push(new KillSpam(forms[i]));
			}
		}
	}
});