var _BASE_URL = 'http://www.gobroadband.com/order/';
var _BASE_URL = 'http://www.gobroadband.com/order/';
var _QUALIFY_URL = 'http://www.gobroadband.com/order/action.php';
var _DEBUG_URL = 'http://www.gobroadband.com/order/debug.php';
var _QUALIFY_TIMEOUT = '100';

// loader image
loader = new Image(32,32);
loader.src = "imgs/loader.gif";

/**
 * Product Qualifiction class
 */
Qualifier = function(arg) {

    // default settings
    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;
    this.address_id = null;

    var phone_fields_exist = 0;
    var address_fields_exist = 0;

    // qualify address suggestion
    if (arg.address_id) {
        this.address_id = arg.address_id;
        this.provider = arg.provider;
        this.address = arg.address;
        this.apt_suite = arg.suite;
        this.city = arg.city;
        this.state = arg.state;
        this.zip = arg.zip;
    } else {

        // check for address fields
        if (this.form.address && this.form.zip && this.form.city && this.form.state) {
            address_fields_exist = 1;
        }

        // check for phone fields
        if (this.form.code && this.form.first && this.form.last) {
            phone_fields_exist = 1;
        }

        // check if address fields filled
        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;
        }

        // check if phone fields filled
        if (phone_fields_exist && (this.form.code.value.length || this.form.first.value.length || this.form.last.value.length)) {
            this.phone = true;
        }

        // check if all fields are filled
        if (!this.phone && !this.address) {
            if (phone_fields_exist) { this.phone = true; }
            if (address_fields_exist) { this.address = true; }
        }

        // run custom validation
        if (!this.validate()) return;
    }

    // run qualification
    this.qualify();
}

/**
 * Validate input data
 */
Qualifier.prototype.validate = function() {
    // remove css error classes, start validation from scratch
    for (var i = 0; i <= this.form.length; i++) {
        if (this.form[i] && this.form[i].className.indexOf('validation-failed') != -1) this.form[i].className = this.form[i].className.replace(' validation-failed', '');
    }

    var e = '';

    // phone validation
    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";
                this.form.code.className = this.form.code.className + ' validation-failed';
                this.form.first.className = this.form.first.className + ' validation-failed';
                this.form.last.className = this.form.last.className + ' validation-failed';
        }
    }

    // address validation
    if (this.address) {
        if (!this.form.address.value.length) {
            e += "Please enter Street Address\n";
            this.form.address.className = this.form.address.className + ' validation-failed';
        }
        if (!this.form.city.value.length) {
            e += "Please enter City\n";
            this.form.city.className = this.form.city.className + ' validation-failed';
        }
        if (!this.form.state.selectedIndex) {
            e += "Please select State\n";
            this.form.state.className = this.form.state.className + ' validation-failed';
        }
        if (/\D+/.test(this.form.zip.value) || this.form.zip.value.length < 5) {
            e += "Please enter a valid Zip Code\n";
            this.form.zip.className = this.form.zip.className + ' validation-failed';
        }
    }

    // email validation if entered
    if (this.form.email && this.form.email.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";
            this.form.email.className = this.form.email.className + ' validation-failed';
        }
    }

    // Service type validation
    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";
        }
    }

    // check for errors
    if(e.length) {
        alert(e);
        return false;
    }

    return true;
}

/**
 * Failed validation/service call
 */
Qualifier.prototype.failed = function() {
    return this.fail;
}

/**
 * Qualification
 */
Qualifier.prototype.qualify = function() {

    var data = {};

    // concat phone number if exists
    if (this.phone) {
        data.phone = this.form.code.value + this.form.first.value + this.form.last.value;
    }

    // assign address if exists
    if (this.address_id == null && 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;
        }
    }

    // assign email if exists
    if (this.form.email) {
        data.email = this.form.email.value;
    }

    // assign service type if exists and selected
    if (this.form.type) {
        data.type = Form.getInputs(this.form,'radio','type').find(function(radio) { return radio.checked; }).value;
    }

    // check for HDTV and New Mover values
    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;
        }
    }

    // qualify address suggestion
    if (this.address_id != null) {
        data.a_id = this.address_id;
        data.provider = this.provider;
        data.address = this.address;
        data.apt_suite = this.apt_suite;
        data.city = this.city;
        data.state = this.state;
        data.zip = this.zip;
    }

    this.params = data;
    this.formData = $(this.form).serialize(true);
    this.wrapper = $(this.prefix + 'Wrapper').innerHTML;

    // show loading image
    $(this.prefix + 'Wrapper').innerHTML =
            '<div id="' + this.prefix + 'Message">Qualification in progress... We\'re now looking for service providers in the area. It might take up to 30 seconds. Please stand by...</div>' +
            '<div id="' + this.prefix + 'Loader"><img src="' + _BASE_URL + 'imgs/loader.gif" /></div>';

    // make Ajax request
    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
    timeout = function() {
        this.error('Qualification timeout');
    }

    // set qualification request timeout
    this.timeout = setTimeout(this.onTimeout.bind(this), _QUALIFY_TIMEOUT * 1000);

    return false;
}

/**
 * Qualification error
 * @param string msg - error message
 */
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.');

    // send debug report
    new Ajax.Request(
        _DEBUG_URL, {
            parameters: 'data=' + escape(Object.toJSON(this.params)) + '&response=' + escape(this.responseText) + '&msg=' + escape(msg)
        }
    );
}

/**
 * Request timout handler
 */
Qualifier.prototype.onTimeout = function() {
    clearTimeout(this.timeout);

    this.error('Qualification timeout!');
}

/**
 * Request failure handler
 */
Qualifier.prototype.onFailure = function(t) {
    clearTimeout(this.timeout);

    this.error('Qualification failed! Error ' + t.status + ' -- ' + t.statusText);
}

/**
 * Request exception handler
 */
Qualifier.prototype.onException = function(t, e) {
    clearTimeout(this.timeout);

    this.error('Qualification ended with an exception! Error ' + e.name + ' -- ' + e.message);
}

/**
 * Request response handler
 */
Qualifier.prototype.onResponse = function(request) {
    clearTimeout(this.timeout);

    if (this.failed()) return;

    this.responseText = request.responseText;

    // check for itest value in data (data validation)
    var pattern = /\{"itest":1,.+"\}/;
    request.responseText = pattern.exec(request.responseText);

    if (request.responseText != null) {

        // eval response
        var json = eval('('+request.responseText+')');

        // if location exists, make redirect
        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!');
    }
};

/**
 * Refill request form
 */
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;
        }
    }
};

