var _BASE_URL = 'http://www.comcastinfo.com/order/';
var _BASE_URL = 'http://www.comcastinfo.com/order/';
var _QUALIFY_URL = 'http://www.comcastinfo.com/order/action.php';
var _DEBUG_URL = 'http://www.comcastinfo.com/order/debug.php';
var _QUALIFY_TIMEOUT = '60';
var _QUALIFY_LOADER_TEXT = 'Qualification in progress... We\'re now looking for best deals in your area. It might take up to 30 seconds. Please stand by...';

loader = new Image(32,32);
loader.src = "imgs/loader.gif";

Qualifier = function(arg) {
	this.phone = false;
	this.address = false;
	this.form = arg.form;
	this.wrapper = null;
	this.params = {};
	this.prefix = arg.prefix;
	this.fail = false;
	this.responseText = '';
	this.timeout = null;
	this.formData = null;

	var phone_fields_exist = 0;
	var address_fields_exist = 0;

	if (this.form.address && this.form.zip && this.form.city && this.form.state) {
		address_fields_exist = 1;
	}

	if (this.form.code && this.form.first && this.form.last) {
		phone_fields_exist = 1;
	}

	if (address_fields_exist && (this.form.address.value.length || this.form.zip.value.length || this.form.city.value.length || this.form.state.selectedIndex)) {
		this.address = true;
	}

	if (phone_fields_exist && (this.form.code.value.length || this.form.first.value.length || this.form.last.value.length)) {
		this.phone = true;
	}

	if (!this.phone && !this.address) {
		if (phone_fields_exist) { this.phone = true; }
		if (address_fields_exist) { this.address = true; }
	}

	if (!this.filter()) return;
	if (!this.validate()) return;

	this.qualify();
}

Qualifier.prototype.filter = function() {
	if(this.address && this.form.address.value.match(/\s{2,}/g)) {
		this.form.address.value = this.form.address.value.replace(/\s{2,}/g, " ");
	}
	
	return true;
}

Qualifier.prototype.validate = function() {

	var e = '';

	if (this.phone) {
		var num = /^([0-9])+$/;

		if (!num.test(this.form.code.value) || this.form.code.value.length<3 ||
			!num.test(this.form.first.value) || this.form.first.value.length<3 ||
			!num.test(this.form.last.value) || this.form.last.value.length<4 || this.form.code.value.charAt(0) == '0') {
				e += "Please enter your Service telephone number\n";
		}
	}

	if (this.address) {
	
		if (!this.form.address.value.length) e += "Please enter Street Address\n";
		if (/\D+/.test(this.form.zip.value) || this.form.zip.value.length < 5) e += "Please enter a valid Zip Code\n";
		if (!this.form.city.value.length) e += "Please enter City\n";
		if (!this.form.state.selectedIndex) e += "Please select State\n";
	}

	if (this.form.email && this.form.email.value.length) {
		var pattern = /^([a-zA-Z0-9_'+*$%\^&!\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9:]{2,4})+$/;

		if (!pattern.test(this.form.email.value)) {
			e += "Please enter valid Email\n";
		}
	}

	if (this.form.type) {
		var value;
		Form.getInputs(this.form, 'radio').each( function(input) { if (input.checked) { value = input.value }; });

		if (value != 'home' && value != 'business') {
			e += "Please select service Type\n";
		}
	}

	if(e.length) {
		alert(e);
		return false;
	}

	return true;
}

Qualifier.prototype.failed = function() {
	return this.fail;
}

Qualifier.prototype.qualify = function() {

	var data = {};

	if (this.phone) {
		data.phone = this.form.code.value + this.form.first.value + this.form.last.value;
	}

	if (this.address) {
		data.address = this.form.address.value;
		data.zip = this.form.zip.value;
		data.state = this.form.state.value;
		data.city = this.form.city.value;
		data.apt_suite = this.form.apt_suite.value;

		if (!this.phone) {
			data.nophonenumber = 1;
		}
	}

	if (this.form.email) {
		data.email = this.form.email.value;
	}

	if (this.form.type) {
		var value;
		Form.getInputs(this.form, 'radio').each( function(input) { if (input.checked) { value = input.value }; });

		data.type = value;
	}

	if (this.form.type) {
		data.type = Form.getInputs(this.form,'radio','type').find(function(radio) { return radio.checked; }).value;
	}

    if (this.form.promo_code) {
    	data.promo_code = this.form.promo_code.value;
    }

	if (this.form.has_hdtv && this.form.is_new_mover) {
		if($('has_hdtv_yes').checked) {
			data.has_hdtv = 1;
		} else {
			data.has_hdtv = 0;
		}
		if ($('is_new_mover_yes').checked) {
			data.is_new_mover = 1;
		} else {
			data.is_new_mover = 0;
		}

	}

	this.params = data;
	this.formData = $(this.form).serialize(true);
	this.wrapper = $(this.prefix + 'Wrapper').innerHTML;

	_QUALIFY_LOADER_TEXT = typeof(_QUALIFY_LOADER_TEXT) != 'undefined' ? _QUALIFY_LOADER_TEXT : 'Qualification in progress... We\'re now looking for best deals in your area. It might take up to 30 seconds. Please stand by...';

	$(this.prefix + 'Wrapper').innerHTML =
			'<div id="' + this.prefix + 'Message">' + _QUALIFY_LOADER_TEXT + '</div>' +
			'<div id="' + this.prefix + 'Loader"><img src="' + _BASE_URL + 'imgs/loader.gif" /></div>';

	new Ajax.Request(
		_QUALIFY_URL, {
			parameters: 'data=' + escape(Object.toJSON(this.params)),
			onComplete: this.onResponse.bind(this),
			onException: this.onException.bind(this),
			onFailure: this.onFailure.bind(this)
		}
	);

	timeout = function() {
		this.error('Qualification timeout');
	}

	this.timeout = setTimeout(this.onTimeout.bind(this), _QUALIFY_TIMEOUT * 1000);

	return false;
}

Qualifier.prototype.error = function(msg) {
	clearTimeout(this.timeout);

	if (this.failed()) return;

	this.fail = true;

	$(this.prefix + 'Wrapper').innerHTML = this.wrapper;

	this.refillForm();

	alert('We are sorry! We might be having some technical issues. Please come back later or try again.');

	new Ajax.Request(
		_DEBUG_URL, {
			parameters: 'data=' + escape(Object.toJSON(this.params)) + '&response=' + escape(this.responseText) + '&msg=' + escape(msg)
		}
	);
}

Qualifier.prototype.onTimeout = function() {
	clearTimeout(this.timeout);

	this.error('Qualification timeout!');
}

Qualifier.prototype.onFailure = function(t) {
	clearTimeout(this.timeout);

	this.error('Qualification failed! Error ' + t.status + ' -- ' + t.statusText);
}

Qualifier.prototype.onException = function(t, e) {
	clearTimeout(this.timeout);

	this.error('Qualification ended with an exception! Error ' + e.name + ' -- ' + e.message);
}

Qualifier.prototype.onResponse = function(request) {
	clearTimeout(this.timeout);

	if (this.failed()) return;

	var pattern = /\{"itest":1,.+"\}/;

	this.responseText = request.responseText;

	request.responseText = pattern.exec(request.responseText);

	if (request.responseText != null) {

		var json = eval('('+request.responseText+')');

		if (json.location) {
			if (typeof(_PARTNER_URL_PATTERN) != 'undefined' && _PARTNER_URL_PATTERN != null) {
				if (document.referrer != '' && _PARTNER_URL_PATTERN.test(document.referrer)) {
					top.location.replace(json.location);
				} else {
					top.location.href = json.location;
				}
			} else {
				top.location.href = json.location;
			}
			return;
		}

		if (json.error) {
			this.error('An internal error was returned!');
		}

	} else {
		this.error('Unable to eval the response!');
	}
};

Qualifier.prototype.refillForm = function() {

	var form_element = $(this.prefix);
	var form_data = this.formData;
	var element_list = $(form_element).getElements();
	for (var i = 0; i < element_list.length; i++) {
		var field_element = $(element_list[i]);
		field_element.value = form_data[field_element.name];
		if (form_data[field_element.name] && typeof(field_element.checked) != 'undefined') {
			field_element.checked = true;
		}
	}
};

