//var age = 1;

function ajaxCall(action, values, resultHandler) {
	var httpRequest = false;

	if(window.XMLHttpRequest){
		httpRequest = new XMLHttpRequest();
		if(httpRequest.overrideMimeType){
			httpRequest.overrideMimeType('text/xml');
		}
	} else {
		return false;
	}

	if (!httpRequest) {
		alertMsg('e', 'Cannot create an XMLHTTP instance.');
		return false;
	}
	
	var sendUrl = 'ajax.php?action=' + action;
	var valuesCount = values.length;
	var i;
	// if there are no values passed in, then we ignore this section of code
	if((valuesCount % 2) == 0){
		for(i = 0; i < valuesCount; i++){
			if((i % 2) == 0){
				sendUrl += '&' + values[i];
			} else {
				sendUrl += '=' + values[i];
			}
		}
	} else {
		alertMsg('s',	'There was an error with the number of arguments sent in the value ' +
				'array for the ajaxCall method. Please try again at a later time.');
		return false;
	}
	
	httpRequest.onreadystatechange = function() { ajaxResult(httpRequest, resultHandler) };
	httpRequest.open("GET", sendUrl, true);
	httpRequest.send(null);
}

function ajaxResult(httpRequest, resultHandler){
	if (httpRequest.readyState == 4){
		if (httpRequest.status == 200){
			var continueResult = true;
			switch(httpRequest.responseText){
				case '-99':
					alertMsg('e', 'You must be logged in to perform that action.');
					resetPage();
					break;
			}
			if(continueResult){
				setTimeout(resultHandler + "('" + httpRequest.responseText + "')", 1);
			}
		} else {
			alertMsg('e', httpRequest.status);
		}
	}
}

function alertMsg(type, msg){
	alert(msg);
}

function calculateAge(){
	var age = getObj('humanYears').value;
	var dogAge;
	if(age == 1){
		dogAge = 16;
	}
	if(age == 2){
		dogAge = 24;
	}
	if(age == 3){
		dogAge = 30;
	}
	if(age >= 4){
		dogAge = (30 + (5 * (age - 3)));
	}
	getObj('result').innerHTML = 'My dog\'s age is <strong>' + dogAge + '</strong> years old in human years.';
}

function closeAllWindows(){
	var i;
	var windows = Array('about', 'feedback');
	for(i = 0; i < windows.length; i++){
		getObj(windows[i]).style.display = 'none';
		getObj(windows[i] + 'Header').style.display = 'none';
	}
	getObj('windowClose').style.display = 'none';
}

function clearError(obj){
	if(obj.className.indexOf('Error') >= 0){
		var len = obj.className.length - 5;
		obj.className = obj.className.substr(0, len);
	}
}


function feedbackTest(obj){
	var result = 0;
	if(validate(obj) == 'true'){
		clearError(obj);
	} else {
		result++;
		markError(obj);
	}
	return result;
}

function getObj(id){
	return document.getElementById(id);
}

function markError(obj){
	if(obj.className.indexOf('Error') < 0){
		obj.className = obj.className + 'Error';
	}
}

function nl2br(str) { 
    return str.replace(/([^>])\n/g, '$1<br />');
}

function openWindow(windowName){
	closeAllWindows();
	getObj(windowName).style.display = 'block';
	getObj(windowName + 'Header').style.display = 'block';
	getObj('windowClose').style.display = 'block';
}

function sendFeedback(){
	// setup variables
	var msg = getObj('fieldFeedbackMsg');
	var name = getObj('fieldFeedbackName');
	var email = getObj('fieldFeedbackEmail');
	
	// validate
	var errorCount = feedbackTest(msg) + feedbackTest(name) + feedbackTest(email);
	if(errorCount == 0){
		var values = new Array('name', name.value, 'email', email.value, 'message', nl2br(msg.value));
		ajaxCall('sendFeedback', values, 'sendFeedbackHandler');
	}
}

function sendFeedbackHandler(response){
	if(response == 'sent'){
		getObj('feedback').innerHTML = 'Your message has been sent!<br /><br />Thank you very much for taking the time to tell me what you think.';
	} else {
		alertMsg('There was an unknown problem sending the message. Please try again.');
	}
}

function updateAge(){
	age = getObj('humanYears').value;
}

function validate(obj){
	// return the string "true" if the obj validates
	var result = 'true';
	
	if(obj.value.length == 0){
		result = 'The input field is empty.';
	} else {
		var objId = obj.id.toLowerCase();
		if(objId.indexOf('name') >= 0){
			// at this point we are validating a name field
			var regex=/^[A-Za-z]+[A-Za-z\-]*$/;
			if(!regex.test(obj.value)){
				result = 'Your name isn\'t valid. Your name must start with a letter and only contain letters and hyphens (-).';
			}
		}
		if(objId.indexOf('email') >= 0){
			// at this point we are validating an email field
			var at = obj.value.indexOf('@');
			if(at > 0){
				if(obj.value.indexOf('.', at) <= at){
					result = 'Email address is invalid.';
				}
			} else {
				result = 'Email address is invalid.';
			}
		}
		if(objId.indexOf('message') >= 0){
			// at this point we are validating a message field
			if(obj.value.length > 10){
				if(obj.value == 'Your message'){
					result = 'Please enter in your message.';
				}
			} else {
				result = 'Your message is too short.';
			}
		}
	}
	return result;
}

