/*
* File: unsubscribe.js
* Purpose: Provides functionality for email unsubscribing submission.
* Dependencies: coreresources\docs\scripts\core-standard.js
* Last JSLint: 10/05/2009
* By: Kyle Brown
*/
if (!window.iwin) {
    var iwin = {};
}

if (!iwin.notification) {
    iwin.notification = {};
}

iwin.notification.Unsubscribe = function () {

    this.init = function () {
        try {
            this.systemHID = window.external.GetSystemHID();
        } catch(systemHIDErr) {
            this.systemHID = null;
        }

        try {
            this.appHeader = window.external.GetIWinAppHeader();
        } catch(AppHeaderErr) {
            this.appHeader = null;
        }

        this.ajax = {
            url: '/profiles/notification/unsubscribe.json',
            sending: false
        };
        this.elements = {
            form: i$('emailUnsubForm'),
            formSubmit: i$('submit'),
            loadingImage: new Element('img', {
                src: '/images/auth/loading.gif',
                style: 'position: relative; top: 3px; left: 3px'
            }),
            content: $$('.container div.unsubscribe')[0],
            errorContent: null,
            preFetchEmail: document.location.search.split('?email=')[1],
            failureText: 'An error has occurred while processing your request. Please wait a moment and try again. If the error persists, please contact <a href="http://support.iwin.com/" target="_blank">iWin customer service</a>.'
        };
        this.elements.form.email.value = (this.elements.preFetchEmail) ? this.elements.preFetchEmail : this.elements.form.email.value;
        this.elements.form.observe('submit', this.submitForm.bind(this));
    };

    this.validateForm = function (form) {
        console.debug('Unsubscribe[validateForm]');

        if (this.elements.form.email && this.elements.form.email.value) {
            if (is_valid_email(this.elements.form.email.value)) {
                this.hideError();
                return true;
            } else {
                this.showError('The email you provided does not appear to be valid.');
                return false;
            }
        } else {
            this.showError('Please enter a e-mail address.');
            return false;
        }
    };

    this.showError = function (content) {
        if (!this.elements.errorContent) {
            this.elements.errorContent = new Element('p', {
                'class': 'error'
            });
            this.elements.errorContent.update(content);
            this.elements.form.insert({
                before: this.elements.errorContent
            });
        } else {
            this.elements.errorContent.update(content);
            this.elements.errorContent.show();
        }
    };

    this.hideError = function () {
        if (this.elements.errorContent) {
            this.elements.errorContent.hide();
        }
    };

    this.submitForm = function (event) {
        console.debug('Unsubscribe[submitForm]');
        Event.stop(event);
        if (!this.ajax.sending && this.validateForm()) {
            console.debug('Unsubscribe[submitForm:Ajax] Submitting Ajax Request');
            var emailSubmit = new Ajax.Request(this.ajax.url, {
                method: 'post',
                contentType: 'application/json',
                evailJSON: true,
                postBody: Object.toJSON(this.elements.form.serialize(true)),
                requestHeaders: ((this.systemHID && this.appHeader) ? {
                    'iWin-HardID': this.systemHID,
                    'iWin-App': this.appHeader
                } : {}),
                onFailure: function () {
                    this.showError(this.elements.failureText);
                    console.error('Unsubscribe[submitForm:onFailure');
                }.bind(this),
                onSuccess: function () {
                    this.hideError();
                    window.location.href = '/profiles/emails/notifications?email=' + encodeURIComponent(this.elements.form.email.value);
                }.bind(this),
                onException: function (req, e) {
                    this.showError(this.elements.failureText);
                    console.error('Unsubscribe[submitForm:Ajax:onException]: %s', e);
                }.bind(this),
                /*on400: function (req, e) {
                    console.error('Unsubscribe[submitForm:Ajax:on400] %s', req.responseJSON.message);
                    this.showError(req.responseJSON.message);   
                }.bind(this),*/
                onComplete: function () {
                    this.elements.loadingImage.hide();
                    this.ajax.sending = false;
                }.bind(this),
                onCreate: function () {
                    this.ajax.sending = true;
                    if (this.elements.loadingImage.parentNode) {
                        this.elements.loadingImage.show();
                    } else {
                        this.elements.formSubmit.insert({
                            after: this.elements.loadingImage
                        });
                    }
                }.bind(this)
            });
        }
    };
};

Event.observe(document, 'dom:loaded', function () {
    iwin.notification.unsub = new iwin.notification.Unsubscribe();
    iwin.notification.unsub.init();
});
