var success = false;

function $(element) {
  if (arguments.length > 1) {
    for (var i = 0, elements = [], length = arguments.length; i < length; i++)
      elements.push($(arguments[i]));
    return elements;
  }
  if (typeof element == 'string')
    element = document.getElementById(element);
  return element;
}

function validateFields() {
	var whiteSpace = /^[\s]+$/;

	if ( $('posText').value == '' || whiteSpace.test($('posText').value) ) {
		alert("Well, you need to write something there too...");
	}
	else if ( $('posEmail').value == '' ) {
		alert("Sorry. You can't CC the mail to yourself without really typing anything.");
		$('cForm').reset();
		$('posName').focus();
	}
	else {
		sendPosEmail();
	}
}

function loadDefault() {
	var x = new Xerces();
	if(x.Read('name')) {
		$('posName').value = x.Read('name');
	}
	if(x.Read('email')) {
		$('posEmail').value = x.Read('email');
	}
}

function sendPosEmail () {
	$('loadBar').style.display = 'block';
	$('emailSuccess').style.display = 'none';

	var x = new Xerces();
	x.Create('name', $('posName').value, 365);
	x.Create('email', $('posEmail').value, 365);

	new Ajax.Request('ajax.php?z='+Math.random(),
		{
			method: 'post',
			parameters: { q: 'contactus', posName: $('posName').value, posEmail: $('posEmail').value, posRegard: $('posRegard').value, posText: $('posText').value },
			onSuccess: function(reply) {
				if(trim(reply.responseText) == 'true') {
					success = true;
					$('loadBar').style.display = 'none';
					$('emailSuccess').style.display = 'block';
				} else {
					$('loadBar').style.display = 'none';
					$('emailSuccess').innerHTML = "<strong style='color: #FF0000;'>Error 1 : The message could not be sent. You can either try again later, or drop a mail to sudhanshuraheja@gmail.com.</strong>";
					$('emailSuccess').style.display = 'block';
				}
				$('posName').value = '';
				$('posEmail').value = '';
				$('posRegard').value = '';
				$('posText').value = '';
			},
			onFailure: function() {
				$('loadBar').style.display = 'none';
				$('emailSuccess').innerHTML = "<strong style='color: #FF0000;'>Error 2 : The message could not be sent. You can either try again later, or drop a mail to sudhanshuraheja@gmail.com.</strong>";
				$('emailSuccess').style.display = 'block';
				$('posName').value = '';
				$('posEmail').value = '';
				$('posRegard').value = '';
				$('posText').value = '';
			}
		}
	);
}

function hideContactTimer() {
	$('loadBar').style.display = 'none';
	$('emailSuccess').innerHTML = "<strong style='color:#FF0000;'>Error 3 : The message could not be sent. You can either try again later, or drop a mail to sudhanshuraheja@gmail.com.</strong>";
	$('emailSuccess').style.display = 'block';
}

function trim(str) {
	return str.replace(/^\s+|\s+$/g, '');
}

