MyAccountPage = Tmatex.UIContainer.subClass({
    init: function(container, pageParameters) {
        this._super.apply(this, [container]);
        var THIS = this;
        var url = "myaccount";
        var myAccountPage = "myAccount.html";
        this.loginPanel = jQuery("#loginPanel");

        var loginPasswdListener = function(event) {
            var valid = THIS.loginPanel.form.loginInput.val().trim().length > 0 && THIS.loginPanel.form.passwdInput.val().trim().length > 0;
            THIS.loginPanel.loginButton.setEnabled(valid);
            if (valid && event.keyCode === 13/*enter*/)
                THIS.loginPanel.loginButton.doClick();
        };

        this.loginPanel.form = new Tmatex.Form(this.loginPanel.find(".form"), Tmatex.DataTypes);
        this.loginPanel.form.loginInput = this.loginPanel.find(".login input").keyup(loginPasswdListener);
        Tmatex.unpimpInput(this.loginPanel.form.loginInput);
        this.loginPanel.form.passwdInput = this.loginPanel.find(".passwd input").keyup(loginPasswdListener);

        this.loginPanel.loginButton = new Tmatex.Button(this.loginPanel.find("button.login"), {
            onClick: function(button) {
                var dataFields = THIS.loginPanel.form.validate();
                if (dataFields.login === null)
                    THIS.loginPanel.form.setError(THIS.loginPanel.form.loginInput, Tmatex.Message.missingData);
                if (dataFields.passwd === null)
                    THIS.loginPanel.form.setError(THIS.loginPanel.form.passwdInput, Tmatex.Message.missingData);

                if (dataFields.login !== null && dataFields.passwd !== null) {
                    THIS.ajax(url, {
                        type: "POST",
                        data: {auth: true, login: dataFields.login, passwd: dataFields.passwd},
                        success: function() {
                            window.location = myAccountPage;
                        },
                        error: THIS.loginPanel.form.serverErrorsHandler
                    });
                }
            }
        }).setEnabled(false);

        this.loginPanel.resetButton = new Tmatex.Button(this.loginPanel.find("button.reset"), {
            onClick: function() {
                THIS.loginPanel.find("input").val("");
                THIS.loginPanel.form.resetErrors();
                THIS.loginPanel.find(".reminder").hide();
                THIS.loginPanel.loginButton.setEnabled(false);
                THIS.loginPanel.remindButton.setEnabled(false);
            }
        });

        this.loginPanel.forgotPasswdLink = this.loginPanel.find(".loginResetButtons th").click(function() {
            var remindButtonVisible = THIS.loginPanel.remindButton.isVisible();
            THIS.loginPanel.find(".reminder").toggle(!remindButtonVisible);
        });

        var emailPhoneListener = function() {
            var emailValid = Tmatex.DataTypes.email.validate(THIS.loginPanel.form.emailInput.val()) == undefined;
            var phoneValid = Tmatex.DataTypes.phone.validate(THIS.loginPanel.form.phoneInput.val()) == undefined;
            THIS.loginPanel.remindButton.setEnabled(emailValid || phoneValid);
        };
        this.loginPanel.form.emailInput = this.loginPanel.find(".email input").bind({
            focus: function(event) {
                Tmatex.fixBuggyInputPlaceHolder(event.target);
            },
            keyup: emailPhoneListener
        });
        Tmatex.unpimpInput(this.loginPanel.form.emailInput);

        this.loginPanel.form.phoneInput = this.loginPanel.find(".phone input").bind({
            focus: function(event) {
                Tmatex.fixBuggyInputPlaceHolder(event.target);
            },
            keyup: emailPhoneListener
        });
        Tmatex.unpimpInput(this.loginPanel.form.phoneInput);

        if (Browser.isPlaceHolderSupported()) {
            this.loginPanel.form.emailInput.attr("placeholder", "john@example.com");
            this.loginPanel.form.phoneInput.attr("placeholder", "123-456-7890");
        }

        this.loginPanel.remindButton = new Tmatex.Button(this.loginPanel.find("button.remind"), {
            onClick: function(button) {
                var dataFields = THIS.loginPanel.form.validate();
                if (dataFields) {
                    var parms;
                    if (dataFields.email)
                        parms = {email: dataFields.email};
                    else if (dataFields.phone)
                        parms = {phone: dataFields.phone};
                    if (parms) {
                        THIS.ajax("mobile", {
                            type: "POST",
                            data: jQuery.extend({remind: true}, parms),
                            success: function(data, alertMessage) {
                                alert(alertMessage);
                                THIS.loginPanel.resetButton.doClick();
                            },
                            error: THIS.loginPanel.form.serverErrorsHandler
                        });
                    } else
                        alert("Please specify valid email address or phone number you have on file.");
                }
            }
        }).setEnabled(false);

        // Welcome
        this.welcomePanel = this.markup.find(".welcome em");
        this.markup.find(".welcome a").click(function() {
            THIS.ajax(url, {
                type: "POST",
                data: {logout: true},
                success: function() {
                    window.location = myAccountPage;
                }
            });
        });

        this.cancelSubscriptionLink = this.markup.find(".summary .cancel").click(function() {
            var cancelSubBlockVisible = THIS.cancelSubscriptionBlock.is(":visible");
            THIS.cancelSubscriptionBlock.toggle(!cancelSubBlockVisible);
            THIS.cancelSubscriptionBlock.textArea.val("");
            if (!cancelSubBlockVisible)
                THIS.cancelSubscriptionBlock.textArea.focus();

//            if (confirm(Autoniq.Message.maCancelConfirm))
//                THIS.ajax(url, {
//                    type: "POST",
//                    data: {cancel: true},
//                    success: function() {
//                        window.location = myAccountPage;
//                    }
//                });
        });

        this.cancelSubscriptionBlock = this.markup.find(".summary .cancelReason").hide();
        this.cancelSubscriptionBlock.textArea = this.cancelSubscriptionBlock.find("textarea");
        this.cancelSubscriptionBlock.cancelButton = this.cancelSubscriptionBlock.find("button").click(function() {
            if (confirm(Autoniq.Message.maCancelConfirm)) {
                var reason = THIS.cancelSubscriptionBlock.textArea.val().trim();
                THIS.ajax(url, {
                    type: "POST",
                    data: {cancel: true, reason: reason.length > 0 ? reason : undefined},
                    success: function() {
                        window.location = myAccountPage;
                    }
                });
            }
        });

        this.reactivateSubscriptionText = this.markup.find(".summary .reactivate").hide();

        // Payment Info Panel
        this.paymentPanel = this.markup.find(".paymentInfo");
        this.paymentPanel.form = new Tmatex.Form(this.paymentPanel.find(".form"), Tmatex.DataTypes);
        this.paymentPanel.form.superPopulate = this.paymentPanel.form.populate;
        this.paymentPanel.form.populate = function(dataArray) {
            THIS.paymentPanel.form.superPopulate.apply(this, [jQuery.extend(THIS.accountActive ? dataArray : {}, {
                ccStateDomain: Autoniq.CCStateUSA,
                ccProviderDomain: Autoniq.CCProviderDomain,
                ccExpiresMonthDomain: Autoniq.CCExpiresMonthDomain,
                ccExpiresYearDomain: Autoniq.CCExpiresYearDomain
            })]);
        };

        this.paymentPanel.toggleEditModeLink = this.paymentPanel.find(".updateLink").click(function() {
            THIS.togglePaymentPanelEditMode(!THIS.isPaymentPanelEditMode());
        });

        this.paymentPanel.saveButton = new Tmatex.Button(this.paymentPanel.find("button.save"), {
            onClick: function(button) {
                var dataFields = THIS.paymentPanel.form.validate();
                if (dataFields) {
                    THIS.ajax(url, {
                        type: "POST",
                        data: jQuery.extend({cc: true}, dataFields),
                        success: function(data, infoMessage) {
                            THIS.paymentPanel.form.applyChanges(THIS.userSettings, dataFields);
                            if (infoMessage)
                                alert(infoMessage);
                            //THIS.togglePaymentPanelEditMode(false);
                            window.location = myAccountPage;//refresh entire page in case account was reactivated
                        },
                        error: THIS.paymentPanel.form.serverErrorsHandler
                    });
                }
            }
        });

        this.paymentPanel.cancelButton = this.paymentPanel.find("button.cancel").click(function() {
            THIS.togglePaymentPanelEditMode(false);
        });

        this.paymentPanel.receiptSelector = new Tmatex.DropDown(this.paymentPanel.find(".paymentReceipts select"));

        this.paymentPanel.downloadButton = new Tmatex.Button(this.paymentPanel.find(".paymentReceipts button"), {
            onClick: function(button) {
                var dataPeriod = THIS.paymentPanel.receiptSelector.markup.val();
                if (dataPeriod) {
                    THIS.ajax(url, {
                        type: "DOWNLOAD",
                        data: {receipt: dataPeriod}
                    });
                } else
                    alert("No payment history available yet.")
            }
        });

        // VHR Panel
        function saveClickHandler(vhrProvider, form, checkAgreed) {
            var dataFields = form.validate();
            if (dataFields && (checkAgreed == undefined || checkAgreed)) {
                THIS.ajax(url, {
                    type: "POST",
                    data: jQuery.extend({vhrProvider: vhrProvider}, dataFields),
                    success: function() {
                        form.applyChanges(THIS.userSettings, dataFields);
                        alert("Saved");
                    },
                    error: form.serverErrorsHandler
                });
            }
        }

        this.vhrPanel = this.markup.find(".vhr");
        this.vhrPanel.carfaxForm = new Tmatex.Form(this.vhrPanel.find(".carfaxBlock .form"), Tmatex.DataTypes);
        this.vhrPanel.carfaxAgree = this.vhrPanel.find(".carfaxAgree:first").click(function() {
            var checked = Tmatex.CheckBox.isChecked(THIS.vhrPanel.carfaxAgree);
            if (!checked) {
                THIS.vhrPanel.carfaxForm.resetErrors();
                THIS.vhrPanel.find(".carfaxBlock input").val("");
                Tmatex.CheckBox.setChecked(THIS.vhrPanel.find(".carfaxBlock .checkbox"), false);
                saveClickHandler("cf", THIS.vhrPanel.carfaxForm);
            }
            THIS.vhrPanel.find(".carfaxBlock input, .carfaxBlock .autoPurchase").toggleEnable(checked);
            THIS.vhrPanel.carfaxSaveButton.setEnabled(checked);
        });

        this.vhrPanel.carfaxSaveButton = new Tmatex.Button(this.vhrPanel.find(".carfaxBlock button.save"), {
            onClick: function() {
                saveClickHandler("cf", THIS.vhrPanel.carfaxForm, Tmatex.CheckBox.isChecked(THIS.vhrPanel.find(".carfaxBlock .checkbox")));
            }
        });

        this.vhrPanel.autoCheckForm = new Tmatex.Form(this.vhrPanel.find(".autoCheckBlock .form"), Tmatex.DataTypes);
        this.vhrPanel.autoCheckAgree = this.vhrPanel.find(".autoCheckAgree:first").click(function() {
            var checked = Tmatex.CheckBox.isChecked(THIS.vhrPanel.autoCheckAgree);
            if (!checked) {
                THIS.vhrPanel.autoCheckForm.resetErrors();
                THIS.vhrPanel.find(".autoCheckBlock input").val("");
                Tmatex.CheckBox.setChecked(THIS.vhrPanel.find(".autoCheckBlock .checkbox"), false);
                saveClickHandler("ac", THIS.vhrPanel.autoCheckForm);
            }
            THIS.markup.find(".autoCheckBlock input, .autoCheckBlock .autoPurchase").toggleEnable(checked);
            THIS.vhrPanel.autoCheckSaveButton.setEnabled(checked);
        });
        this.vhrPanel.autoCheckSaveButton = new Tmatex.Button(this.vhrPanel.find(".autoCheckBlock button.save"), {
            onClick: function() {
                saveClickHandler("ac", THIS.vhrPanel.autoCheckForm, Tmatex.CheckBox.isChecked(THIS.vhrPanel.find(".autoCheckBlock .checkbox")));
            }
        });

        // Account Profile Panel
        this.profilePanel = this.markup.find(".profile");
        this.profilePanel.form = new Tmatex.Form(this.profilePanel.find(".form"), Tmatex.DataTypes);
        this.profilePanel.form.superPopulate = this.profilePanel.form.populate;
        this.profilePanel.form.populate = function(dataArray) {
            THIS.profilePanel.form.superPopulate.apply(this, [jQuery.extend(dataArray, {
                passwdConfirm: dataArray.passwd,
                stateDomain: Autoniq.CCStateUSA
            })])
        };

        this.profilePanel.saveButton = new Tmatex.Button(this.profilePanel.find("button.save"), {
            onClick: function(button) {
                var dataFields = THIS.profilePanel.form.validate();
                if (dataFields) {
                    if (dataFields.passwd.trim().length < 4) {
                        THIS.profilePanel.form.setError(THIS.profilePanel.find('input[data-type^="passwd"]'), "Minimum password length is 4 characters.");
                        return;
                    } else if (dataFields.passwd != dataFields.passwdConfirm) {
                        THIS.profilePanel.form.setError(THIS.profilePanel.find('input[data-type^="passwd"]'), "Passwords do not match.");
                        return;
                    }
                    THIS.ajax(url, {
                        type: "POST",
                        data: jQuery.extend({profile: true}, dataFields),
                        success: function() {
                            THIS.profilePanel.form.applyChanges(THIS.userSettings, dataFields);
                            THIS.welcomePanel.html(THIS.userSettings.fullName || THIS.userSettings.login);
                            alert(Autoniq.Message.infoUpdated);
                        },
                        error: THIS.profilePanel.form.serverErrorsHandler
                    });
                } else
                    THIS.profilePanel.cancelButton.setVisible(true);
            }
        });

        this.profilePanel.cancelButton = new Tmatex.Button(this.profilePanel.find("button.cancel"), {
            onClick: function(button) {
                THIS.profilePanel.form.populate(THIS.userSettings);
                button.setVisible(false);
            }
        }).setVisible(false);

        this.ajax(url, {
            success: function(userSettings) {
                THIS.userSettings = userSettings;
                THIS.loginPanel.hide();
                THIS.markup.show();
                THIS.populate();
            },
            error: function() {
                THIS.loginPanel.show();
                THIS.markup.hide();
            },
            suppressError: true
        });
    },

    populate: function() {
        this.accountActive = this.userSettings.accountStatus.toLowerCase() === "active";

        // Welcome
        this.welcomePanel.html(this.userSettings.fullName || this.userSettings.login);
        new Tmatex.Form(this.markup.find(".form.summary")).populate(this.userSettings);

        this.cancelSubscriptionLink.toggle(this.accountActive);
        this.reactivateSubscriptionText.toggle(!this.accountActive);

        // Subscription info
        if (this.userSettings.subFeatures.length > 0) {
            new Tmatex.List(this.markup.find(".form.subscription"), {
                entryTemplate: function(list, tr, id, value) {
                    tr.push(["th", value[0]], ["td", {"class": "field"}, value[1] ? "Yes" : "No"]);
//                    jQuery(tr).append(jQuery("<th>").html(value[0])).append(jQuery('<td class="field">').html(value[1] ? "Yes" : "No"));
                },
                clickHandler: function() {
                }//not clickable

            }).populate(this.userSettings.subFeatures, undefined, undefined, false);
        }

        // Payment info
        this.togglePaymentPanelEditMode(!this.accountActive || !this.userSettings.ccNumber);
        this.paymentPanel.receiptSelector.populate(this.userSettings.paymentReceipts);
        this.paymentPanel.downloadButton.setEnabled(this.userSettings.paymentReceipts.length > 0);

        // VHR
        var vhrEnabled = this.userSettings.carfaxEnabled || this.userSettings.autoCheckEnabled;
        this.vhrPanel.toggle(vhrEnabled);
        if (vhrEnabled) {
            this.vhrPanel.carfaxForm.populate(this.userSettings);
            var carfaxAgreed = !!(this.userSettings.carfaxId && this.userSettings.carfaxPasswd);
            Tmatex.CheckBox.setChecked(this.vhrPanel.carfaxAgree, carfaxAgreed);
            this.vhrPanel.find(".carfaxBlock input, .carfaxBlock .autoPurchase").toggleEnable(carfaxAgreed);
            this.vhrPanel.carfaxSaveButton.setEnabled(carfaxAgreed);

            this.vhrPanel.autoCheckForm.populate(this.userSettings);
            var autoCheckAgreed = !!(this.userSettings.autoCheckId && this.userSettings.autoCheckPasswd);
            Tmatex.CheckBox.setChecked(this.vhrPanel.autoCheckAgree, autoCheckAgreed);
            this.vhrPanel.find(".autoCheckBlock input, .autoCheckBlock .autoPurchase").toggleEnable(autoCheckAgreed);
            this.vhrPanel.autoCheckSaveButton.setEnabled(autoCheckAgreed);
        }

        // Profile
        this.profilePanel.toggle(this.accountActive);
        this.profilePanel.form.populate(this.userSettings);
    },

    isPaymentPanelEditMode: function() {
        return this.paymentPanel.find(".form tr:eq(0):first").is(':hidden');
    },

    togglePaymentPanelEditMode: function(on) {
        this.paymentPanel.find(".form tr").toggle(on);
        this.paymentPanel.find(".form tr:eq(0), .form tr:eq(1)").toggle(!on);
        this.paymentPanel.form.populate(this.userSettings);
    },

    clickForgotPasswdLink: function() {
        this.loginPanel.forgotPasswdLink.trigger("click");
    }
});

