/// <reference name="MicrosoftAjax.js" />
/// <reference name="dnn.js" assembly="DotNetNuke.WebUtility" />
/// <reference name="dnn.xmlhttp.js" assembly="DotNetNuke.WebUtility" />

Type.registerNamespace('Pg');
    
Pg.ViewNewsletterRegistrationModule = function()
{
    //Call Base Method
    Pg.ViewNewsletterRegistrationModule.initializeBase(this);
    //Member Variables
    this._msgs = {};
    this._settings = {};
    this._helloButton = null;

    //Associated delegates to single member variable dictionary to make it easy to dispose
    this._delegates = {
        _helloSuccessDelegate: Function.createDelegate(this, this._helloSuccess),
        _helloFailDelegate: Function.createDelegate(this, this._helloFail),
        _onLoadDelegate: Function.createDelegate(this, this._onLoad)
        //componentPropChangedDelegate: Function.createDelegate(this, this._onPropChanged)
        };

    //Event Hookup
    Sys.Application.add_load(this._delegates._onLoadDelegate);
}

Pg.ViewNewsletterRegistrationModule.prototype =
{
    //Properties
    get_ns: function() { return this.get_id() + '_'; },
    get_msgs: function() { return this._msgs; },
    set_msgs: function(value) { this._msgs = value; },
    get_settings: function() { return this._settings; },
    set_settings: function(value) { this._settings = value; },

    //Events
    initialize: function() {
        //Call Base Method    
        Pg.ViewNewsletterRegistrationModule.callBaseMethod(this, 'initialize');

        //create UI
        this._helloButton = this._createChildControl('btnSave', 'input', 'button');
		$(this._helloButton).addClass('myButton');
        //this._helloButton.setAttribute('class', 'myButton');
        this._helloButton.value = this.getMessage('btnSave'); //get localized value
        $get(this.get_ns() + 'lblBtn').parentNode.appendChild(this._helloButton);

        //hookup event handlers
        $addHandlers(this._helloButton, { "click": this._onHello }, this);
    },

    _onLoad: function(src, arg) {
        /*//page is completely loaded, you can now access any element or component
        var components = arg.get_components();
        //sample of how to do client-side IMC - look for other components we are interested in
        //in this case, we will look for other instances of the same module that are not ourselves
        //but you can communicate with any components
        for (var i=0; i<components.length; i++)
        {
        if (Object.getTypeName(components[i]) == Object.getTypeName(this) && components[i].get_id() != this.get_id())
        this.add_propertyChanged(components[i]._delegates.componentPropChangedDelegate);
        }*/
    },

    _onHello: function(src, arg) {
        this._displayWait(true);
        this._updateSettings();
        this._validate();

        if (this._settings['IsValid'] == '1') {
            dnn.xmlhttp.callControlMethod('Pg.Modules.NewsletterRegistrationModule.ViewNewsletterRegistrationModule.' + this.get_id(),
                'SaveNewsletterRegistration', { Settings: this._settings }, this._delegates._helloSuccessDelegate, this._delegates._helloFailDelegate);
        }
        //this.raisePropertyChanged('SayHello');
    },

    _validate: function() {
        var Msg = '';
        var errorFN = '';
        var errorLN = '';
        var errorE = '';
        var bok = false;

        if ($get(this.get_ns() + 'txtFirstName').value == null || $get(this.get_ns() + 'txtFirstName').value == '')
            errorFN = this.getMessage('FirstNameErrorMessage');

        if ($get(this.get_ns() + 'txtLastName').value == null || $get(this.get_ns() + 'txtLastName').value == '')
            errorLN += this.getMessage('LastNameErrorMessage');

        if ($get(this.get_ns() + 'txtEmail').value == null || $get(this.get_ns() + 'txtEmail').value == '')
            errorE += this.getMessage('EmailErrorMessage');
        else if (!this._validateEmail($get(this.get_ns() + 'txtEmail').value))
            errorE += this.getMessage('EmailErrorMessage');

        if (errorFN != '' || errorLN != '' || errorE != '') {
            Msg = this.getMessage('ErrorMessage');
            if (errorFN != '')
                Msg += errorFN + ', ';
            if (errorLN != '')
                Msg += errorLN + ', ';
            if (errorE != '')
                Msg += errorE + ', ';
            Msg = Msg.substring(0, Msg.lastIndexOf(', '));
            this._settings['IsValid'] = '0';
            this.showMessage(Msg);
        }
        else 
        {
            this._settings['IsValid'] = '1';
        }
    },

    _validateEmail: function(email) {
        var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
        if (reg.test(email) == false) {
            return false;
        }
        else {
            return true;
        }
    },

    _updateSettings: function() {
        this._settings['FirstName'] = $get(this.get_ns() + 'txtFirstName').value;
        this._settings['LastName'] = $get(this.get_ns() + 'txtLastName').value;
        this._settings['Email'] = $get(this.get_ns() + 'txtEmail').value;
    },

    /*_onPropChanged: function(src, args)
    {
    this.showMessage(String.format('You {0} to {1} but not to me?', args.get_propertyName(), src.get_name()));
    },*/

    //Methods
    getMessage: function(key) {
        return this._msgs[key];
    },

    showMessage: function(msg) {
        $get(this.get_ns() + 'lblResponse').innerHTML = msg;
    },

    //Private Methods
    _createChildControl: function(id, tag, type) {
        var ctl = document.createElement(tag);
        ctl.id = this.get_ns() + id;
        if (type)
            ctl.type = type;
        return ctl;
    },

    _displayWait: function(show) {
        //$get(this.get_ns() + 'imgAjax').className = (show ? '' : 'ceHidden');
    },

    _helloSuccess: function(payload, ctx, req) {
        document.getElementById(this.get_ns() + 'txtEmail').value = '';
        document.getElementById(this.get_ns() + 'txtLastName').value = '';
        document.getElementById(this.get_ns() + 'txtFirstName').value = '';
        
        this.showMessage(this.getMessage('SuccessMessage'));
    },

    _helloFail: function(payload, ctx, req) {
        //this._displayWait(false);
        //alert('error: ' + payload);
    },

    dispose: function() {
        $clearHandlers(this._helloButton);
        this._helloButton = null;
        this._delegates = null;
        Pg.ViewNewsletterRegistrationModule.callBaseMethod(this, 'dispose');
    }
}

//register class and inherit from Sys.Component
Pg.ViewNewsletterRegistrationModule.registerClass('Pg.ViewNewsletterRegistrationModule', Sys.Component);

