/**
 * JS Class for the Rule Type Email Widget.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License, version 2, as
 * published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program as the file license.txt. If not, see
 * <http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt>
 *
 * @package    CMS
 * @subpackage Widget
 * @author     Squiz Pty Ltd <products@squiz.net>
 * @copyright  2010 Squiz Pty Ltd (ACN 084 670 600)
 * @license    http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt GPLv2
 */

function RuleTypeEmailWidgetType(id, value, allowEmpty)
{
    this.widgetType = 'RuleTypeEmailWidgetType';
    this.value      = value;
    this.widgetid   = '';
    this.allowEmpty = allowEmpty;

}

RuleTypeEmailWidgetType.prototype = {

    reset: function()
    {
        this.simpleResult = false;
        this.widget       = null;
        this.value        = null;
        this.server       = true;
        this.client       = true;
        this.errors       = [];

    },

    setValue: function(val)
    {
        this.value = val;

    },

    setWidgetid: function(wid)
    {
        this.widgetid = wid;

    },

    setAllowEmpty: function(op)
    {
        if (typeof op === 'string') {
            var opStr = op.toLowerCase();
            if (opStr === 'true') {
                this.allowEmpty = true;
            } else if (opStr === 'false') {
                this.allowEmpty = false;
            }
        } else {
            this.allowEmpty = op;
        }

    },

    validate: function()
    {
        var local       = '\d0-9a-zA-Z-_+';
        var localMiddle = local + '\.\\w';
        var normalPtn   = '^([' + local + ']([' + localMiddle + '\']*[' + local + ']){0,1}@(((?:[\da-zA-Z]|[\da-zA-Z][\'-.\\w]*[\da-zA-Z])\.)+[a-zA-Z]{2,7}))$';
        var disNamePtn  = '^[a-zA-Z]+(([ \'\,\.\-][ a-zA-Z])?[a-zA-Z]*)*\s+<([' + local + ']([' + localMiddle + ']*[' + local + ']){0,1}@(((?:[\da-zA-Z]|[\da-zA-Z][\'-\w]*[\da-zA-Z])\.)+[a-zA-Z]{2,7}))>$';
        var normalRe    = new RegExp(normalPtn, "g");
        var disNameRe   = new RegExp(disNamePtn, "g");

        if (this.allowEmpty === true && this.value.length === 0) {
            return true;
        } else if (disNameRe.test(this.value) === true) {
            return true;
        } else if (normalRe.test(this.value) === true) {
            return true;
        } else {
            this.errors = [];
            this.errors.push('Email address is not valid.');
            return false;
        }

    },

    getErrors: function()
    {
        return this.errors;

    }

};

