var ck_name = /^[A-Za-z\'\-\s.]{1,50}$/;

var validators = new Array();
var httprequest = createXMLHTTPObject();

var requestTimeout = 1000;

var formIndex = undefined;

function byPassPhoneValidation() {
	if(phoneValidator.isValidated == false) {
		//httprequest.abort();
		//phoneValidator.isValidated = true;
		validator.validatorCompleteEvent();
	}
}

function update_and_validate() {
	formIndex = {
		'form' : document.Form1,
		'day' : document.Form1.day,
		'month' : document.Form1.month,
		'year' : document.Form1.year,
		'first_name' : document.Form1.fname,
		'last_name' : document.Form1.lname,
		'phone_1_area' : document.Form1.area_code,
		'phone_1_xxx' : document.Form1.xxx,
		'phone_1_xxxx' : document.Form1.xxxx,
		'phone_2_area' : document.Form1.area_code2,
		'phone_2_xxx' : document.Form1.xxx2,
		'phone_2_xxxx' : document.Form1.xxxx2,
		'email' : document.Form1.email,
		'from_zip' : document.Form1.zip_from,
		'to_zip' : document.Form1.zip_to,
		'rooms' : document.Form1.aptsize,
		'session_id' : document.Form1.session_id
	};
	validator.empty();
	validator.addValidator(dateValidator);
	validator.addValidator(nameValidator);
	validator.addValidator(emailValidator);
	validator.addValidator(phoneValidator);
	validator.addValidator(zipValidator);
	validator.addValidator(movesizeValidator);
	validator.run();
	return false;
}

var validator = new function() {
	this.errors = new Array();
	this.validators = new Array();
	
	this.addValidator = function(validator) {
		this.validators.push(validator);
	}
	this.allValidated = function() {
		for(i in this.validators) {
			if(this.validators[i].isValidated == false) {
				return false;
			}
		}
		return true;
	}
	this.clean = function() {
		this.errors = new Array();
		for(i in this.validators) {
			this.validators[i].isValidated = false;
			this.validators[i].isValid = false;
		}
	}
	this.empty = function() {
		this.validators = new Array();
	}
	this.isValid = function() {
		for(i in this.validators) {
			if(this.validators[i].isValid == false) {
				return false;
			}
		}
		return true;
	}
	this.run = function() {
		this.clean();
		for(i in this.validators) {
			this.validators[i].validate();
			this.validatorCompleteEvent();
		}
	}
	this.validatorCompleteEvent = function() {
		if(this.allValidated()) {
			if(this.isValid()) {
				formIndex["form"].submit();
			} else {
				var message = "";
				for(i in this.errors) {
					message = message + this.errors[i] + "\n";
				}
				alert(message);
			}
		}
	}
}

// Prototype validator, with common parameters that all validator functions must have
var prototypeValidator = function() {
	this.isValidated = false;
	this.isValid = false;
}

var dateValidator = new prototypeValidator;
dateValidator.validate = function() {
	var mon = undefined;
	var day = undefined;
	if((mon = formIndex["month"].selectedIndex) != '') {
		mon = formIndex["month"].value;
	}
	if((day = formIndex["day"].selectedIndex) != '') {
		day = formIndex["day"].value;
	}
	var year = formIndex["year"].value;
	
	var date = new Date();
	date.setFullYear(year, mon, day);
	
	var date_in_six_months = new Date();
	date_in_six_months.setDate(date_in_six_months.getDate()+180);
	
	if(mon == "" || day == "" || year == "") {
		validator.errors.push("Please select a date.");
	} else if(date < new Date()) {
		validator.errors.push("Date entered has already passed");
	} else if(date_in_six_months < date) {
		validator.errors.push("We only accept dates that are within 6 months");
	} else {
		this.isValid = true;
	}
	this.isValidated = true;
}

var nameValidator = new prototypeValidator;
nameValidator.validate = function() {
	var first_name = formIndex["first_name"];
	var last_name = formIndex["last_name"];

	c = 0;
	if(first_name.value == "" || first_name.value == "First") {
		validator.errors.push("Please provide your first name");
		//first_name.focus();
		c=c+1;
	}else if(!ck_name.test(first_name.value)) {
		validator.errors.push("Your First name should have only letters");
		c=c+1;
	}

	cc = 0;
	if(last_name.value == "" || last_name.value == "Last") {
		validator.errors.push("Please provide your last name");
		//last_name.focus();
		cc=cc+1;
	}else if(!ck_name.test(last_name.value)) {
		validator.errors.push("Your Last name should have only letters");
		cc=cc+1;
	}

	if(c == 0 && cc == 0){
		this.isValid = true;
	}
	this.isValidated = true;
}

var emailValidator = new prototypeValidator;
emailValidator.validate = function() {
	var email = formIndex["email"];
	var email_value = new String(email.value);
	if(email_value == "") {
		validator.errors.push("Your email address is a required field. Please fill it in.");
		email.focus();
	} else if(email_value.indexOf("@")==-1 || email_value.indexOf(".")==-1) {
		validator.errors.push("Please enter valid email address.");
	} else {
		this.isValid = true;
	}
	this.isValidated = true;
}

var phoneValidator = new prototypeValidator;
phoneValidator.validate = function() {
	var phone_1_area_code = formIndex["phone_1_area"];
	var phone_1_xxx = formIndex["phone_1_xxx"];
	var phone_1_xxxx = formIndex["phone_1_xxxx"];
	var phone_2_area_code = formIndex["phone_2_area"];
	var phone_2_xxx = formIndex["phone_2_xxx"];
	var phone_2_xxxx = formIndex["phone_2_xxxx"];
	var number_to_validate = "";
	var valid_number = null;
	if(
		phone_2_area_code.value + phone_2_xxx.value + phone_2_xxxx.value != '' &&
		(!(/\d{3}/.test(phone_2_area_code.value))
		|| !(/\d{3}/.test(phone_2_xxx.value))
		|| !(/\d{4}/.test(phone_2_xxxx.value)))
	) {
		validator.errors.push("Invalid secondary phone number format.");
	} else {
		number_to_validate = phone_2_area_code.value + phone_2_xxx.value + phone_2_xxxx.value;
	}
	if(
		!(/\d{3}/.test(phone_1_area_code.value))
		|| !(/\d{3}/.test(phone_1_xxx.value))
		|| !(/\d{4}/.test(phone_1_xxxx.value))
	) {
		validator.errors.push("Invalid phone number format.");
	} else {
		number_to_validate = phone_1_area_code.value + phone_1_xxx.value + phone_1_xxxx.value;
	}
	if(number_to_validate != "") {
		var post_string_values = {
			"name" : formIndex["first_name"].value + " " + formIndex["last_name"].value,
			"email" : formIndex["email"].value,
			"phone_number" : phone_1_area_code.value + phone_1_xxx.value + phone_1_xxxx.value,
			"phone_number2" : phone_2_area_code.value + phone_2_xxx.value + phone_2_xxxx.value,
			"from_zip" : formIndex["from_zip"].value,
			"to_zip" : formIndex["to_zip"].value,
			"move_date" : getYear() + "-" + getMonth() + "-" + getDay(),
			"rooms" : formIndex["rooms"].value,
			"sid" : formIndex["session_id"].value
		};
		var post_string = createHttpQuery(post_string_values);
		var ajax_url = "http://www.zmoving.com/tasks/p_validator.php";
		httprequest.open("POST",ajax_url,true);
		httprequest.onreadystatechange = function() {
			if(httprequest.readyState == 4) {
				response = eval("(" + httprequest.responseText + ")");
				if(response.isValid == 'true') {
					phoneValidator.isValid = true;
				} else {
					validator.errors.push("Please enter an actual phone number");
				}
				phoneValidator.isValidated = true;
				validator.validatorCompleteEvent();
			}
		}
		httprequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		httprequest.send(post_string);
		window.setTimeout("byPassPhoneValidation()", requestTimeout);
	} else {
		phoneValidator.isValidated = true;
	}
}

var zipValidator = new prototypeValidator;
zipValidator.validate = function() {
	var origin_zip = formIndex["from_zip"]
	var destination_zip = formIndex["to_zip"];
	if(
		!(/\d{5}/.test(origin_zip.value))
		|| !(/\d{5}/.test(destination_zip.value))
	) {
		validator.errors.push("Please enter correct ZIP code");
	} else {
		this.isValid = true;
	}
	this.isValidated = true;
}

var movesizeValidator = new prototypeValidator;
movesizeValidator.validate = function() {
	var movesize = formIndex["rooms"];
	if(movesize.value == "") {
		validator.errors.push("Please select move size");
		movesize.focus();
	} else {
		this.isValid = true;
	}
	this.isValidated = true;
}

function getDay() {
	if(formIndex["day"].selectedIndex == '') {
		return formIndex["day"].selectedIndex;
	} else {
		return formIndex["day"].value;
	}
}

function getMonth() {
	if(formIndex["month"].selectedIndex == '') {
		return formIndex["month"].selectedIndex;
	} else {
		return formIndex["month"].value;
	}
}

function getYear() {
	return formIndex["year"].value;
}

function createHttpQuery(array) {
    var query = "";
    for(var parameter in array) {
        if(array[parameter].length > 0) {
            query += "&" + encodeURIComponent(parameter) + "=" + encodeURIComponent(array[parameter]);
        }
    }
    query = query.substr(1);
    return query;
}