com.openapps.BillingProcedure = new Class({

    Implements: [Events, Options],

    initialize: function(options) {
        this.setOptions(options);
        this.setView();
        this.setEventListeners();
    },

    setView: function() {
        this.view = this.options.view;
        this.view.iframe.set('src', '/billing/loading.html');
        this.view.popup = new DOL.PopupContainer({
            'view': {
                'wrapper': $$('.fullScreenPopupContainer')[0],
                'className': 'fullscreenIframeWindow',
                'content':  this.view.wrapper
            }
        });
        try { this.view.lbtSetupBilling = $('billing-setup'); } catch (err) {};
        try { this.view.lbtChangeBilling = $('billing-change-settings'); } catch (err) {};
    },

    setEventListeners: function() {
        try {
            this.view.lbtSetupBilling.addEvent('click', function() {
                this.showSetupBillingView();
            }.bind(this));
        } catch (err) {};

        try {
            this.view.lbtChangeBilling.addEvent('click', function() {
                this.showChangeBillingView();
            }.bind(this));
        } catch (err) {};
    },

    open: function(url) {
        this.view.iframe.set('src', url);
        this.view.popup.open();
    },

    close: function () {
        this.view.iframe.set('src', '/billing/loading.html');
        this.view.popup.close();
    },
    
    cancelled: function() {
        this.context = null;
        this.close();
    },

    completed: function() {
        if ($chk(this.context)) {
            com.openapps.billingProcedure.context._run();
            this.context = null;
            this.close();
        } else {
            location.reload(true);
        }
    },

    showSetupBillingView: function() {
        this.open('/billing/splash-setup.html');
    },

    showChangeBillingView: function() {
        this.open('/billing/splash-change-settings.html');
    },

    showExceptionView: function(exception) {
        this.open('/billing/exception/' + exception + '.html');
    }
});


com.openapps.Subscription = new Class({

    Implements: [Events, Options],

    initialize: function(options) {
        this.setOptions(options);
        this.setData();
        this.setView();
        this.setWidgets();
        this.setEventListeners();
    },

    setData: function() {
        this.data = JSON.decode(this.options.view.wrapper.get('app_instance'));
    },

    setView: function() {
        this.view = this.options.view;

        this.view.name = this.view.wrapper.getElement('.name');
        this.view.description = this.view.wrapper.getElement('.description');

        try {
            this.view.priceValue = this.view.wrapper.getElement('.price-value');
            this.view.tierTrigger  = this.view.wrapper.getElement('.tier-trigger');
        } catch (err) {}

        try {
            this.view.appConfig  = this.view.wrapper.getElement('.app-config');
        } catch (err) {}

        try {
            this.view.formRun = this.view.wrapper.getElement('form.run');
            this.view.btnRun  = this.view.wrapper.getElement('form.run button');
        } catch (err) {}

        try {
            this.view.formStop = this.view.wrapper.getElement('form.stop');
            this.view.btnStop  = this.view.wrapper.getElement('form.stop button');
        } catch (err) {}

        try {
            this.view.formBilling = this.view.wrapper.getElement('form.billing');
            this.view.btnBilling  = this.view.wrapper.getElement('form.billing button');
        } catch (err) {}

        try {
            this.view.formDelete = this.view.wrapper.getElement('form.delete');
            this.view.btnDelete  = this.view.wrapper.getElement('form.delete button');
        } catch (err) {}

        this.view.statucBar = this.view.wrapper.getElement('.status-bar');
    },

    setWidgets: function() {
        this.widgets = {};
        this.widgets.status = new DOL.StatucBar({
            view: {
                wrapper: this.view.statucBar
            }
        });
    },

    setEventListeners: function() {
        try {
            this.view.tierTrigger.addEvent('mouseover', function (e) {
                com.openapps.Subscription.currentInstance = this;
            }.bind(this));
        } catch (err) {}
        
        try {
            this.view.appConfig.addEvent('click', function (e) {
                com.openapps.Subscription.currentInstance = this;
            }.bind(this));
        } catch (err) {}

        try {
            this.view.btnRun.addEvent('click', function() {
                com.openapps.Subscription.currentInstance = this;
                this.toRun();
            }.bind(this));
        } catch (err) {}

        try {
            this.view.btnStop.addEvent('click', function() {
                this.stop();
            }.bind(this));
        } catch (err) {}

        try {
            this.view.btnDelete.addEvent('click', function() {
                this.remove();
            }.bind(this));
        } catch (err) {}

        try {
            this.view.btnBilling.addEvent('click', function() {
                this.run();
            }.bind(this));
        } catch (err) {}

        try {
            this.view.name.addEvent('click', function() {
                com.openapps.Subscription.currentInstance = this;
                this.textField = 'name';
            }.bind(this));
        } catch (err) {}

        try {
            this.view.description.addEvent('click', function() {
                com.openapps.Subscription.currentInstance = this;
                this.textField = 'description';
            }.bind(this));
        } catch (err) {}
    },

    toRun: function() {
        if (this.data['agreement_ready']) {
            this.run();
        } else {
            com.openapps.Agreement.open('Agreement', '/dashboard/ajax/project_id/subscription_id/agreement');
        }
    },

    run: function () {
        if (this.data.price == '0') {
            this._run();
            return;
        }

        var details = this.data.name
                + this.data.version
                + '. Price: <strong>$' + this.data.price + ' US</strong>/month. '
                +  com.openapps.confirmations.billingRequired.details;

        DOL.Confirmation.confirm({
            'title': com.openapps.confirmations.billingRequired.title,
            'details': details,
            'yes': com.openapps.confirmations.billingRequired.yes,
            'no': com.openapps.confirmations.billingRequired.no,
            'onYes': function() {
                var url = "/billing/ajax/account-status";
                new Request.JSON({url: url, onSuccess: function(data){
                    if (data["status"] == "none" || data["status"] == "active_non-billable") {
                        DOL.Confirmation.confirm({
                            'title': com.openapps.confirmations.billingSetupRequired.title,
                            'details': com.openapps.confirmations.billingSetupRequired.details,
                            'yes': com.openapps.confirmations.billingSetupRequired.yes,
                            'no': com.openapps.confirmations.billingSetupRequired.no,
                            'onYes': function() {
                                com.openapps.billingProcedure.context = this;
                                com.openapps.billingProcedure.showSetupBillingView();
                            }.bind(this),
                            'onNo': function() {}
                        });

                    } else if (data["status"] == "active") {
                        this._run();
                    } else {
                        com.openapps.billingProcedure.showExceptionView(data["status"]);
                    }
                }.bind(this)}).get();
            }.bind(this),

            'onNo': function() {}
        });        
    },

    _run: function () {
        this.view.formRun.submit();
    },

    stop: function () {
        DOL.Confirmation.confirm({
            'title': com.openapps.confirmations.stopApp.title,
            'details': com.openapps.confirmations.stopApp.details,
            'yes': com.openapps.confirmations.stopApp.yes,
            'no': com.openapps.confirmations.stopApp.no,
            'onYes': function() { this.view.formStop.submit() }.bind(this),
            'onNo': function() {}
        });
    },

    remove: function () {
        DOL.Confirmation.confirm({
            'title': com.openapps.confirmations.deleteApp.title,
            'details': com.openapps.confirmations.deleteApp.details,
            'yes': com.openapps.confirmations.deleteApp.yes,
            'no': com.openapps.confirmations.deleteApp.no,
            'onYes': function() { this.view.formDelete.submit() }.bind(this),
            'onNo': function() {}
        });
    },

    changePrice: function (price, url) {
        this.showStatus('Changing plan...');
        new Request.JSON({
            url: url,
            onSuccess: function(tier) {
                this.onPriceChangeSuccess(tier.price);
            }
        }).post();
    },

    toChangePrice: function (price, changePriceActionUrl) {
        var details = 'Price: <strong>$' + price + ' US</strong>/month. '
                +  com.openapps.confirmations.billingRequired.details;

        DOL.Confirmation.confirm({
            'title': com.openapps.confirmations.billingRequired.title,
            'details': details,
            'yes': com.openapps.confirmations.billingRequired.yes,
            'no': com.openapps.confirmations.billingRequired.no,
            'onYes': function() {
                var url = "/billing/ajax/account-status";

                new Request.JSON({url: url, onSuccess: function(data){
                    if (data["status"] == "none" || data["status"] == "active_non-billable") {
                        DOL.Confirmation.confirm({
                            'title': com.openapps.confirmations.billingSetupRequired.title,
                            'details': com.openapps.confirmations.billingSetupRequired.details,
                            'yes': com.openapps.confirmations.billingSetupRequired.yes,
                            'no': com.openapps.confirmations.billingSetupRequired.no,
                            'onYes': function() {
                                com.openapps.billingProcedure.context = this;
                                com.openapps.billingProcedure.showSetupBillingView();
                            }.bind(this),
                            'onNo': function() {}
                        });

                    } else if (data["status"] == "active") {
                        this.changePrice(price, changePriceActionUrl);
                    } else {
                        com.openapps.billingProcedure.showExceptionView(data["status"]);
                    }
                }.bind(this)}).get();
            }.bind(this),

            'onNo': function() {}
        });
    },

    onPriceChangeSuccess: function(price) {
        this.view.priceValue.set('text', price);
        this.showEvent('Your plan has been changed.');
    },

    showEvent: function (message) {
        this.widgets.status.display(message, 3000);
    },

    showStatus: function (message) {
        this.widgets.status.display(message, -1);
    },

    agreeTermOfService: function() {
        this.showEvent('Agreed!');
        this.run();
    },

    changeText: function(text) {
        var url = ['/dashboard/ajax', this.data.project_id, this.data.subscription_id, "new-" + this.textField].join('/');
        this.view[this.textField].getElement('span').set('load', {
            method: 'post',
            data: this.textField + '=' + text,
            onSuccess: function() {
               this.showEvent('Change was accepted.')
            }.bind(this),
            onFailure: function() {
               this.showStatus('Change was not accepted.')
            }.bind(this)
        }).load(url);
        this.showStatus('Making change...')
    }
});


com.openapps.Tier = new Class({

    initialize: function(options) {
        $$('#tiers a.tier').each(function(el){
            $(el).addEvent('click', function(e) {
                e.preventDefault();
                var price = $(e.target).get('price');
                var url = $(e.target).get('href');
                com.openapps.Subscription.currentInstance.toChangePrice(price, url);
            })
        });
    }
});


com.openapps.TOSAgreement = function () {
    var view = {};
    var options;

    function initialize(opts) {
        options = opts;
        setView();
        setEventListeners();
    }

    function setView() {
        view.wrapper = $('tos-agreement');
        view.btnYes = view.wrapper.getElement('.btnYes');
        view.btnNo = view.wrapper.getElement('.btnNo');
        view.popup = new DOL.PopupContainer({
            'view': {
                'wrapper': $$('.popupContainer')[0],
                'className': 'popupWindow',
                'content': view.wrapper
            }
        });
    }

    function setEventListeners() {
        view.btnYes.addEvent('click', function() {
            view.popup.close();
            options.onAgree();
        });
        
        view.btnNo.addEvent('click', function() {
            view.popup.close();
            options.onNotAgree();
        });
    }

    return {

        open: function(opts) {
            view.popup.open();
        },

        init: function(opts) {
            initialize(opts);
        }
    }
}();


com.openapps.Agreement = function () {

    function submit(method, url, data) {

        new Request({method: method, url: url,
            onSuccess: function() {
                com.openapps.Subscription.currentInstance.showEvent('Thanks!');
            },

            onFailure: function() {
                com.openapps.Subscription.currentInstance.showEvent('Sorry');
            }
        }).send(data);
    }

    function close() {
        DOL.AjaxWindow.close();
    }

    return {
        agree: function(method, url, data) {
            close();
            submit(method, url, data);
            com.openapps.Subscription.currentInstance.showEvent('Agreement was submitted.');
        },

        disagree: function() {
            close();
        },

        open: function(title, url) {

            DOL.AjaxWindow.addEvent('load', function() {
                var wrapper = $('agreement');
                DOL.Tooltip.init(wrapper);
                com.openapps.Agreement.wizard = new DOL.Wizard({
                    view: {
                        viewStack: wrapper.getElement('.wizard')
                    },
                    onCancel: function() {
                        com.openapps.Agreement.disagree();
                    },
                    onFinish: function(method, url, data) {
                        com.openapps.Agreement.agree(method, url, data);
                    }
                });
                com.openapps.Agreement.wizard.switchTo(0);
            });
            DOL.AjaxWindow.open(title, url);
        }
    }
}();


window.addEvent('domready', function() {

    DOL.Alert.init();
    DOL.Notification.init();
    DOL.Confirmation.init();
    DOL.PopupIframe.init();
    DOL.AdvancedTooltip.init();
    DOL.AjaxPopupWindow.init();
    DOL.AjaxWindow.init();
    DOL.InlineEditor.init();

    $$('li.subscription').each(function(wrapper) {
        new com.openapps.Subscription({
            view: {
                wrapper: wrapper
            }
        })
    });

    $$('#billingProcedure').each(function(el) {
        com.openapps.billingProcedure = new com.openapps.BillingProcedure({
            view: {
                wrapper: $(el),
                iframe: $(el).getElement('iframe')
            }
        });
    });

    $$('.editable').each(function(editable) {
        new DOL.InlineEditable({
            view: {
                wrapper: editable,
                target: editable.getElement('span')
            },

            onSave: function(text) {
                com.openapps.Subscription.currentInstance.changeText(text);
            }
        });
    });

});
