var url = "";
var urn = "";
var VI = '/verification/image.php';
window.onload = function() {

	var f = document.getElementsByTagName('form')[1];
	
	f.onsubmit = function() {
				
		urn = "";
		url = "";
	
		var invalids = Array();
		if (trim(this.name.value) == "") {
			invalids.push('name');		
		}
		//place field is optional
		this.email.value = this.email.value.toLowerCase();
		if (!trim(this.email.value).match(/^[a-z0-9_\+-]+(\.[a-z0-9_\+-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*\.([a-z]{2,4})$/)) {
			invalids.push('valid email');
		}
		if (trim(this.message.value) == "") {
			invalids.push('message');
		}
	
		if (invalids.length > 0) {
			alert("Please enter " + stringOf(invalids) + ".");
			return false;	
		}
				
		//construct the uri
		url = this.action;
		urn = "name=" + encodeURIComponent(trim(this.name.value)) + "&place=" + encodeURIComponent(trim(this.place.value)) + "&email=" + encodeURIComponent(trim(this.email.value)) + "&message=" +  encodeURIComponent(trim(this.message.value));

		//show verification image
		show_verification_image();
		
		return false;
	}
}

function trim(s) {
		return s.replace(/^\s+|\s+$/g,"");
}

function stringOf(arr) {
	var out = "";
	for(var i in arr) {
		out += i == arr.length-1 ? arr.length == 1 ? arr[i] : " and " + arr[i] : i == 0 ? arr[i] : ", " + arr[i];
	}
	return out;
}

function show_verification_image() {
	if (urn == "" || url == "") return;
	var layer = document.createElement('div');
	layer.className = "layer";
	layer.id = "layer";
	document.body.appendChild(layer);
	var div = document.createElement('div');
	div.id = 'verification_image'
	document.body.appendChild(div);
	
	var div1 = document.createElement('div');
	div1.innerHTML = 'Enter the text below<img src="'+VI+'?random=' + Math.random() + '" height="50" width="120" alt="" />';
	div.appendChild(div1);
	
	var div2 = document.createElement('div');
	var code = document.createElement('input');
	code.type = 'text';
	code.id = "input_code";
	div2.appendChild(code);
	div.appendChild(div2);
	
	var div3 = document.createElement('div');
	var submit = document.createElement('input');
	submit.type = "submit";
	submit.value = "Submit";
	var reset = document.createElement('input');
	reset.type = "reset";
	reset.value = "Cancel";
	div3.appendChild(submit);
	div3.appendChild(reset);
	div.appendChild(div3);
	
	code.focus();//very important..else the focus remains on the form
	
	code.onkeydown = function(e) {
		var keycode;
		if (window.event) keycode = window.event.keyCode;
		else if (e) keycode = e.which;
		if (keycode==13) {
			submit.onclick();
			return false;
		}
	}
	submit.onclick = function() {
		if (trim(code.value) == "") {
			alert("Please fill in the text given in the box");
			code.focus();
			return false;
		}
		
		//disable
		code.disabled = true;
		submit.disabled = true;
		reset.disabled = true;
		
		
		//link URI via ajax post
		urn = urn + "&code=" + encodeURIComponent(code.value);
		post();
		return false;
	}
	
	reset.onclick = function() {
		document.body.removeChild(layer);
		document.body.removeChild(div);
	}
}

function post() {

	var http = xmlHttp();
    if (!http)
    alert('Your browser does not support Ajax.');

    //onreadystatechange
    http.onreadystatechange = function () {
    	stateChanged(http);
    };

    //send http request
    urn += '&random=' + Math.random();
    http.open("post", url, true);
    http.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=utf-8");
    http.setRequestHeader("Content-length", urn.length);
    http.setRequestHeader("Connection", "close");
    http.send(urn);
}

function stateChanged(http) {

	if (http.readyState==4 || http.readyState=="complete") {

			//if successfull
		if (http.status == 200) {
					
			//response XML document
			var response = http.responseXML;
						
			if (!response) {
				alert('Invalid response XML');
				showLoading(false);
				reloadImage();
			}
			response = response.getElementsByTagName('response')[0];			
			if (parseInt(response.getAttribute('success')) == 1) {
				alert(response.getAttribute("message"));
				document.getElementsByTagName('form')[0].reset();
			}
			else {
				var message = response.getAttribute("message");
				alert(message);
				showLoading(false);
				if (message.match('code')) {
					reloadImage();
					return;			
				}
			}
			showLoading(false);
			document.body.removeChild(document.getElementById('verification_image'));
			document.body.removeChild(document.getElementById('layer'));
		}
		else {
			alert('Error in connection');
			showLoading(false);
		}
	}
	else showLoading(true);
}

function xmlHttp() {
    var http;
    try	{
    	http = new XMLHttpRequest();
    }
    catch (e) {
    	try {
    		http = new ActiveXObject("Msxml2.XMLHTTP");
    	}
    	catch (e1) {
    		http = new ActiveXObject("Microsoft.XMLHTTP");
    	}
    }
    return http;
}

function showLoading(flag) {
	if (flag) {
		if (document.getElementById('loading_popup')) return;
		var loading = document.createElement('div');
		loading.innerHTML = "Working...";
		loading.id= "loading_popup";
		document.body.appendChild(loading);
	}
	else {
		if (document.getElementById('loading_popup')) {
			document.body.removeChild(document.getElementById('loading_popup'));
		}
	}
}

function reloadImage() {
	if (document.getElementById('verification_image')) {
		document.getElementById('verification_image').getElementsByTagName('img')[0].src = VI + "?random=" + Math.random();
		var inputs = document.getElementById('verification_image').getElementsByTagName('input');
		for (var i = 0; i < inputs.length; i++) {
			inputs[i].disabled = false;
		}		
	}
	if (document.getElementById('input_code')) {
		document.getElementById('input_code').value = "";
		document.getElementById('input_code').focus();
	}
}
