/**
 * IndexController
 */
function IndexController() {
    var self = this;
    this.dialNumber = null;
    this.callNumber = null;
    this.makeCallForm = null;
    this.prefsStack = null;
    this.settingsTabs = null;
    this.settingsStack = null;
    this.callForm = null;
    this.makeCallInSpanish = null;
    this.preferencesForm = null;
    this.services = new Services();
    this.suggestedAddressPopup = null;
    this.useSuggestedAddressButton = null;
    this.prefsFeedback = null;
    this.errorPrompt = 'Please correct any items highlighted in red. <br/>Mouse over red items for info.';
    this.errorCount = 0;
    this.warningDisplay = null;
    jQuery(document).ready(function() {
        self.onLoad();
    })
}
IndexController.prototype = new BaseController();
/**
 * Initialize page behaviors and instance vars here.
 */
IndexController.prototype.onLoad = function() {
    var self = this;
    this.dialNumber = jQuery("#dialNumber");
    this.dialNumber.focus();
    this.dialNumber.bind("input paste keydown",
                         function() {
        var elem = jQuery(this);
        if (elem.val() == elem[0].defaultValue) {
            elem.val('');
        }
    }).blur(function() {
        var elem = jQuery(this);
        if (elem.val() == '') {
            elem.val(elem[0].defaultValue);
        }
    });

    this.callNumber = jQuery("#callNumber");
    this.makeCallInSpanish = jQuery("#inSpanish");
    this.makeCallForm = jQuery("#makeCallForm")
    this.callForm = jQuery("#callPrefsForm")
    this.prefsStack = new AccordionViewStack("#prefsSettings");
    this.settingsTabs = new TabMenu('#prefSubNav');
    this.settingsTabs.addListener(TabMenu.TAB_CLICK, function (e, d) {
        self.onSettingsTabClick(d);
    });
    this.settingsStack = new ViewStack('#settingsStack');
    this.settingsStack.showIndex(0);
    /**
     * Make action responders return false to prevent default action.
     */
    this.makeCallForm.submit(function() {
        return self.makeCall();
    });
    this.preferencesForm = jQuery("#preferencesForm");
    this.warningDisplay = jQuery("#warningDisplay");
    this.preferencesForm.find('.email').focus(function() {
        self.warningDisplay.show();
    });
    this.prefsFeedback = jQuery("#preferencesFeedback");

    jQuery("#preferences .cancelButton").click(function() {
        jQuery("#prefsLabel").click();
        self.callForm[0].reset();
    });
    jQuery("#preferences .saveButton").click(function() {
        self.savePreferencesFromCallForm();
        jQuery("#prefsLabel").click();
    });
    jQuery("#settings .cancelButton").click(function() {
        jQuery("#settingsLabel").click();
        self.clearErrorPrompt();
        self.preferencesForm[0].reset();
    });
    jQuery("#settings .saveButton").click(function() {
        self.validatePreferencesForm();
    });

    this.suggestedAddressPopup = jQuery("#suggestedAddressPopup");

    jQuery("#tryAddressAgainButton").click(function() {
        self.suggestedAddressPopup.hide();
        jQuery("#addressFeedback").html('')
    });

    this.useSuggestedAddressButton = jQuery("#useThisAddressButton");

    this.useSuggestedAddressButton.click(function() {
        self.useSuggestedAddress(jQuery(this).data('addressVO'))
    });
    if (openSettings) {
        jQuery("#settingsLabel").click();
        if (openSub) {
            jQuery("#" + openSub + "SettingsButton").click();
        }
    }
};

IndexController.prototype.validateIMHandle = function () {
    var self = this;
    var handle = this.preferencesForm.find('.imHandle');
    handle.removeClass('validationError').attr('title', '');
    if (!handle.val().empty() && handle.val() != handle[0].defaultValue) {
        this.services.async = false;
        this.services.validateIMHandle({
            handle:handle.val()
        }, function(data) {
            if (data > 0) {
                self.errorCount++;
                handle.addClass('validationError');
                handle.attr('title', 'The IM handle your entered is already in use.')
            }
        });
    }
};

IndexController.prototype.useSuggestedAddress = function(addressVo) {
    this.preferencesForm.find('.firstName').val(addressVo.firstName);
    this.preferencesForm.find('.lastName').val(addressVo.lastName);
    this.preferencesForm.find('.street').val(addressVo.street);
    this.preferencesForm.find('.apt').val(addressVo.street2);
    this.preferencesForm.find('.city').val(addressVo.city);
    this.preferencesForm.find('.state').val(addressVo.state);
    this.preferencesForm.find('.zip').val(addressVo.zip);
    this.suggestedAddressPopup.hide();
    jQuery("#addressFeedback").html('Using suggested address. Please correct any errors and save.');
};

IndexController.prototype.savePreferencesFromCallForm = function() {
    if (this.callForm.find("#saveCallFormSettings:checked").length > 0) {
        this.preferencesForm.find(".gender[value='" + this.callForm.find(".gender:checked").val() + "']").attr('checked', 'checked');
        this.preferencesForm.find(".language'[value='" + this.callForm.find(".language':checked").val() + "']").attr('checked', 'checked');
        this.preferencesForm.find(".coversation'[value='" + this.callForm.find(".coversation':checked").val() + "']").attr('checked', 'checked');
        this.preferencesForm.find('.vco').val(this.callForm.find(".vco").val());
        this.validatePreferencesForm();
    }

};
IndexController.prototype.validatePreferencesForm = function() {
    this.errorCount = 0;
    this.clearErrorPrompt();
    this.prefsFeedback.html('Saving preferences. Please wait this could take a moment...');
    this.preferencesForm.find(".validationError").attr('title', '').removeClass("validationError");
    var firstName = this.preferencesForm.find('.firstName');
    if (firstName.val().empty()) {
        firstName.addClass('validationError');
        firstName.attr("title", 'First name cannot be blank.');
        this.errorCount++;
    }
    var lastName = this.preferencesForm.find('.lastName');
    if (lastName.val().empty()) {
        lastName.addClass('validationError');
        lastName.attr("title", 'Last name cannot be blank.');
        this.errorCount++;
    }

    this.suggestedAddressPopup.hide();
    var street = this.preferencesForm.find('.street');
    var apt = this.preferencesForm.find('.apt');
    var city = this.preferencesForm.find('.city');
    var state = this.preferencesForm.find('.state');
    var orignalState = this.preferencesForm.find('.orginalState');
    var zip = this.preferencesForm.find('.zip');
    if (street.val().empty() || city.val().empty() || state.val().empty() || zip.val().empty()) {
        if (street.val().empty()) {
            street.addClass('validationError');
            street.attr('title', 'Please enter a valid steet.');
        }
        if (city.val().empty()) {
            city.addClass('validationError');
            city.attr('title', 'Please enter a valid city.')
        }
        if (state.val().empty()) {
            state.addClass('validationError');
            state.attr('title', 'Please enter a valid state.')
        }
        if (zip.val().empty()) {
            zip.addClass('validationError');
            zip.attr('title', 'Please enter a valid zip.')
        }
        this.errorCount++
    } else {
        if (street.val() != street[0].defaultValue || apt.val() != apt[0].defaultValue || city.val() != city[0].defaultValue || state.val() != orignalState.val() || zip.val() != zip[0].defaultValue) {
            var feedback = jQuery("#addressFeedback");
            feedback.html('Validating address. Please wait...');
            this.services.async = false;
            var response = this.services.validateAddress({
                                                             firstName:firstName.val(),
                                                             lastName:lastName.val(),
                street:street.val(),
                apt:apt.val(),
                city:city.val(),
                state:state.val(),
                zip:zip.val()
                                                         }).responseText;

            var responseObject = eval("(" + response + ")");
            var addressVO = responseObject.data;
            if (!responseObject.success) {
                this.errorCount++;
                jQuery(".address").addClass("validationError").attr('title', 'The address you\'ve entered does not appear to be valid. Please try again. For assistance please contact customer care.');
                if (addressVO) {
                    this.suggestedAddressPopup.show();
                    this.suggestedAddressPopup.find('#suggestedAddress').html("<div>" + addressVO.firstName + " " + addressVO.lastName + "</div><div>" + addressVO.street + "</div>" + "<div>" + addressVO.street2 + "</div>" + "<div>" + addressVO.city + ", " + addressVO.state + "</div>" + "<div>" + addressVO.zip + "</div>");
                    this.useSuggestedAddressButton.data('addressVO', addressVO);
                } else {
                    feedback.html('The address you\'ve entered does not appear to be valid. Please try again. For assistance please contact customer care.');
                }
            } else {
                feedback.html('Address validated.');
                jQuery(".address").removeClass("validationError").attr('title', '')
            }

        }
    }
    this.emailMatch();
    this.checkEmail();
    this.validateIMHandle();
    var password = this.preferencesForm.find('.password');
    var passwordVer = this.preferencesForm.find('.passwordVer');
    if (!password.val().empty()) {
        var pwl = password.val().length;
        if (pwl < 4 || pwl > 8) {
            this.errorCount++;
            password.addClass('validationError');
            password.attr('title', 'The password you entered is invalid. Please use only alphanumeric characters (letters or numbers - no symbols or spaces), and be sure that the length is between 4 and 8 characters.')
        } else {
            if (password.val() != passwordVer.val()) {
                this.errorCount++;
                passwordVer.addClass('validationError');
                passwordVer.attr('title', 'The passwords you entered to not match. Please make sure they match.')
            }
        }

    }
    if (this.errorCount == 0) {
        this.savePreferences();
    } else {
        this.showErrorPrompt();
    }
};

IndexController.prototype.clearErrorPrompt = function() {
    this.prefsFeedback.removeClass("error");
    this.prefsFeedback.html('');
    this.warningDisplay.hide();
};
IndexController.prototype.showErrorPrompt = function() {
    this.prefsFeedback.addClass("error");
    this.prefsFeedback.html(this.errorPrompt)
};

IndexController.prototype.emailMatch = function() {
    var email = this.preferencesForm.find('.email');
    var emailVer = this.preferencesForm.find('.emailVer');
    if (email.val() != emailVer.val()) {
        this.errorCount++;
        emailVer.addClass('validationError');
        emailVer.attr('title', 'Email addresses do not match.')
    }
};
IndexController.prototype.checkEmail = function() {
    var thisClass = this;
    var email = this.preferencesForm.find('.email');
    email.removeClass("validationError").attr('title', '');
    if (!email.val().empty()) {
        if (!Validator.emailRegEx.test(email.val())) {
            this.errorCount++;
            email.attr('title', 'The email address you entered does not appear to be valid. Please check the email you entered, and try again. For assistance contact customer care.');
            email.addClass("validationError");
            this.showErrorPrompt();
        } else {
            this.services.async = false;
            this.services.emailExists({
                email:email.val()
            }, function(data) {
                if (data > 0) {
                    thisClass.errorCount++;
                    email.attr('title', 'The email you entered is already associated with an existing IP-Relay account. If you already have a IP-Relay account please do not create another one. Click <a href="javascript:loginController.showForgotPassword()">here</a> and we will email you your password (or email you with instructions on how to reset your password). For assistance contact customer care.');
                    email.addClass("validationError");
                }
            })
        }
    }
};

IndexController.prototype.savePreferences = function() {
    var thisClass = this;
    jQuery.ajax({
        url:'/services/savePreferences.php',
        type:'POST',
        dataType:'json',
        service:'savePreferences',
        data:this.preferencesForm.serialize(),
        success:function(data) {
            thisClass.onPreferencesSaved(data);
        }
    })
};
IndexController.prototype.onPreferencesSaved = function(data) {
    var thisClass = this;
    if (data.result == true) {
        this.clearErrorPrompt();
        this.prefsFeedback.html('Preferences saved.');
        setTimeout('jQuery("#settingsLabel").click()', 1500)
    } else {
        jQuery.each(data.errors, function(key, val) {
            thisClass.preferencesForm.find("." + key).addClass("validationError").attr('title', val);
            thisClass.showErrorPrompt();
        })
    }

};
IndexController.prototype.onSettingsTabClick = function(e) {
    this.settingsStack.showIndex(e.tabIndex);
};
IndexController.prototype.makeCall = function () {
    if (this.dialNumber.val() != this.dialNumber[0].defaultValue) {
        this.callNumber.val(this.dialNumber.val());
    }
    if (jQuery("#inSpanish:checked").val()) {
        jQuery("#spanish").attr('checked', true);
    }
    this.callForm.submit();
    return  false;
};
var indexController = new IndexController;
