window.addEvent('domready', function() {
	new FormCheck('clientForm');
	
	new FormCheck('newsForm', {
		submitByAjax : true,
		onAjaxRequest : ajaxRequest,
		onAjaxSuccess : ajaxResponse,
		onAjaxFailure : function() { alert("ajax failure"); }
	});
});

function ajaxRequest() {
	timeout = true;
	var yoffset = window.getScroll().y;
	var y = window.getHeight()/2;
	var x = window.getWidth()/2;
	y += yoffset;
	y -= 150;
	x -= 100;
var y2 = y +50;
var x2 = x + 50;
	var ajaxDiv = new Element('div', { id: 'ajaxDiv', style: 'width:200px; height:200px; position:absolute; background-color:#574e86; opacity:0.7; top:'+y+'px; left:'+x+'px;'});
	var gif = new Element('img', { id: 'gif', src: 'images/ajax-loader(2).gif',width: '100px', height: '100px', style: 'opacity:1; margin:50px;'});
	gif.injectInside(ajaxDiv);
	ajaxDiv.injectInside(document.body);

}

function ajaxResponse(responseText) {
	clearFields();
//	if(timeout == true) {
//		timeout = false;
//	alert(responseText);
//window.setTimeout('ajaxResponse(\''+responseText+'\')', 3000);
	
//	}
	//else {
	removeMsg('ajaxDiv');

	var xml = (new DOMParser()).parseFromString(responseText, "text/xml");

	if(!xml.getElementsByTagName("message")[0]){
		var errors = xml.getElementsByTagName("error")[0];

		var html = "Errors found";
		var errArray = Array();
		for(var i = 0;i < errors.length;i++){
			errArray[i] = errors[i].firstChild.nodeValue;
		}
		for(var i = 0;i < errArray.length;i++){
			html += "\n"+errArray[i]+"\n";
		}
		showMessage(html);
	}
	else if(!xml.getElementsByTagName("error")[0]){
		
		var html = xml.getElementsByTagName("message")[0].firstChild.nodeValue;
		showMessage(html);
	}
//}
}

function showMessage(html) {
	var yoffset = window.getScroll().y;
	var y = window.getHeight()/2;
	var x = window.getWidth()/2;
	y += yoffset;
	y -= 150;
	x -= 100;
	
	var msgDiv = new Element('div', { id: 'msgDiv', style: 'text-align: center; width:200px; height:200px; position:absolute; background-color:#574e86; opacity:0.7; top:'+y+'px; left:'+x+'px;'});
	var h1 = new Element('h1', { style: 'color:white; font-size:16px; font-family:Georgia; width:180px; margin:80px auto 0;'});
	h1.innerHTML = html;
	h1.injectInside(msgDiv);
	var id = "msgDiv";
	msgDiv.injectInside(document.body);
	setTimeout('removeMsg(\''+id+'\')', 1500);
}

function removeMsg(id) {
	document.body.removeChild($(id));
}

function clearFields() {
	if($('signup_form')) {
		var inputs = $('signup_form').getElementsByTagName("input");
		for(var i = 0;i < inputs.length;i++){
			inputs[i].value = "";
		}
		var text = $('signup_form').getElementsByTagName('textarea');
		text[0].value = "";
	}
	
	if($('questionForm')) {
		var inputs = $('questionForm').getElementsByTagName("input");
		for(var i = 0;i < inputs.length;i++) {
			inputs[i].value = "";
		}
		var text = $('questionForm').getElementsByTagName('textarea');
		text[0].value = "";
		
	}
}
