// Success/Error codes - caller can process the codes however it sees fit
var PASS = true;
var FAIL = false;
// keys for message array
var EMAIL_FAIL = "EMAIL_FAIL";
var IS_EMPTY = "IS_EMPTY";
var TOO_LONG = "TOO_LONG";
var ONE_EMAIL = "ONE_EMAIL";

// default error messages
var defaultErrorMessages = new Array();
defaultErrorMessages[ EMAIL_FAIL ] = " is not a valid email address.";
defaultErrorMessages[ TOO_LONG ] = " is too long to fit in our database; please choose an alternative email address.";
defaultErrorMessages[ IS_EMPTY ] = "Please specify at least one recipient's email for your card.";
defaultErrorMessages[ ONE_EMAIL ] = "Please enter one email address at a time.";

function isEmpty(val){
    if(trim(val) == "")
        return true;
    return false;
}

function ltrim(val){
    //  ltrim removes leading whitespace characters from a string
    //        @param    val  string to be modified
    //        @return   val  modified string
    return val.replace(/^\s*/g,"");
}

function rtrim(val){
    //  rtrim removes trailing whitespace characters from a string
    //        @param    val  string to be modified
    //        @return   val  modified string
    return val.replace(/\s*$/g,"");
}

function trim(val){
    //  trim removes leading and trailing whitespace characters
    //  from a string
    //        @param    val  string to be modified
    //        @return   val  modified string
    if (typeof(val)=="object")
        return val
    return val.replace(/^\s*|\s*$/g,"");
}

function write_message(message_id, message, class_name)
{
    var message_div = document.getElementById(message_id);
    var curr_class = message_div.className;

    if(message)
    {
        if(class_name)
        {
            message_div.setAttribute('class', class_name);
            message_div.setAttribute('className', class_name);
        }
        message_div.style.display = 'block';
        message_div.innerHTML = message;
        scroll_into_view(message_id);
    }
    else
    {
        message_div.style.display = 'none';
    }
}

function reformat_emails(emails, email_object){
    var reformatted_emails = '';
    for(var i=0; i<emails.length; i++)
    {
        if(!isEmpty(emails[i]))
        {
            reformatted_emails += trim(emails[i]);
            if(i < emails.length-1)
                reformatted_emails += ', ';
        }
    }
    if(email_object)
        email_object.value = reformatted_emails;
    return reformatted_emails;
}

function validate_email(email, maxlen, allow_empty) {
    // validate_email validates a single email address
    //      @param      email   email address to be validated
    //      @param      maxlen  maximum length allowed for email address
    //      @exception  IS_EMPTY|TOO_LONG|FAIL
    //                      raise error code via "throw()"
    //      @return     PASS    return PASS if no tests fail
    var strEmail = trim(email);
    var strUser;
    var strDomain;
    var arrDomainParts = Array();
    var intDomainLength;

    if(!maxlen)
        maxlen = 75;

    if(!allow_empty)
        allow_empty

    // empty email address
    if(strEmail == "" && !allow_empty)
        throw(IS_EMPTY);
    else if(strEmail == "")
        return;

    // email address too long
    if(strEmail.length > maxlen)
        throw(TOO_LONG);

    // check for: '@' at beginning, multiple '@', '@' at end, no '@'
    if (strEmail.match(/.*@$|.*@.*@.|^@.*|^[^@]*$/))
        throw(EMAIL_FAIL);

    strUser = strEmail.split("@")[ 0 ];
    strDomain = strEmail.split("@")[ 1 ];

    // missing part of email
    if (strUser == "" || strDomain == "")
        throw(EMAIL_FAIL);

    // user shouldn't contain '()<>:;,[ ]\" ' (delivermail.py)
    if(strUser.match(/.*[*()<>;:,\[\]\\'" ].*/))
        throw(EMAIL_FAIL);

    // domain should only contain alphanumerics or a hyphen. Single letter subdomains are allowed. (delivermail.py)
    if (!(strDomain.match(/^([0-9a-zA-Z\-\.]+\.)+[a-zA-Z]{2,9}$/)))
        throw(EMAIL_FAIL);

    // domain should be text.text[ .text ]*
    if (strDomain.indexOf("..") != -1) // part of domain missing
        throw(EMAIL_FAIL);

    arrDomainParts = strDomain.split(".");
    intDomainLength = arrDomainParts.length;
    if (intDomainLength == 1)
        throw(EMAIL_FAIL);
    // top level is wrong length (2-char country code, or 3-6 char whatchallit)
    if (arrDomainParts[ intDomainLength-1 ].length < 2 || arrDomainParts[ intDomainLength-1 ].length > 6)
        throw(EMAIL_FAIL);

    // passed all the tests
    return PASS;
}

function validate_emails(email_object, reformat, message_array){

    var valid           = true;
    var emails          = email_object.value.replace(/;/g,',');
    var result_object   =   {
                            'error_message' : '',
                            'error_codes' : new Array(),
                            'pass_validation' : FAIL,
                            'emails': ''
                            }
    if(!reformat)
        reformat = true;
    if(!message_array)
        message_array = defaultErrorMessages;

    if(reformat)
    {
        emails = emails.replace(/\n/g,', ');
        emails = emails.replace(/\r/g,', ');
    }

    if(isEmpty(emails) || isEmpty(emails.replace(/,/g,'')))
    {
        valid = FAIL;
        result_object.error_message += '<p>'+message_array[IS_EMPTY]+'</p>';
    }

    emails = emails.split(',');
    for (i=0; i<emails.length; i++)
    {
        try
        {
            validate_email(emails[i],'',true);
        }
        catch(e_code)
        {
            result_object.error_message += '<p>'+emails[i]+' '+message_array[e_code]+'</p>';
            valid = FAIL;
            result_object.error_codes[result_object.error_codes.length] = e_code+'|'+emails[i];
        }
    }

    if(reformat)
        reformat_emails(emails, email_object);

    result_object.emails = emails;
    result_object.pass_validation = valid;
    return result_object;
}

function validate_checkboxes(checkbox_name){
    var checkboxes = document.getElementsByName(checkbox_name);
    var is_checked = false;
    for(var i=0; i < checkboxes.length; i++)
    {
        if(checkboxes[i].checked)
        {
            is_checked = true;
            break;
        }
    }
    if(!is_checked)
        return FAIL;
    return PASS;
}

function Error(field, message, type)
{
	var e_obj = this;
	this.message = message;
	this.field = field;
	this.type = type
}

function Errors(display_div)
{
	var e_obj = this;
	this.errors = new Array();
	this.display_div = document.getElementById(display_div);
	this.error_html = "<p>%s</p>";
	this.error_color = "#FF0000";

	this.ERROR = "agi-message-area agi-error";
	this.MESSAGE = "agi-message-area agi-message-demo";
	this.SUCCESS = "agi-message-area agi-message-success";

	this.count = function()
	{
		return this.errors.length;
	}

	this.is_error = function()
	{
		return (this.errors.length > 0);
	}

	this.display = function(blnShow)
	{
		if (blnShow)
		{
			write_message(this.display_div.id, this.to_html(), "agi-message-area agi-error");
//			this.display_div.innerHTML = this.to_html();
//			this.display_div.style.color = this.error_color;
			this.mark_fields();
		} else {
			write_message(this.display_div.id, null, "agi-message-area agi-error");
//			this.display_div.innerHTML = "";
			this.clear_fields();
		}
	}

	this.set_class = function(class_name)
	{
		var curr_class = this.display_div.className;
		if(class_name && (curr_class.indexOf(class_name) == -1))
		{
			message_class = (this.display_div.className) ? this.display_div.className+' '+class_name : class_name
			this.display_div.setAttribute('class', message_class);
			this.display_div.setAttribute('className', message_class);
		}
	}

	this.write_message = function(message, class_name)
	{

    if(message)
    {
        this.display_div.style.display = 'block';
        this.display_div.innerHTML = message;
    }
    else
    {
        this.display_div.style.display = 'none';
    }
	}

	this.mark_fields = function()
	{
		for (i = 0; i < this.errors.length; i++)
		{
			try{
				document.getElementById(this.errors[i].field + "-error").className = "agi-mesage-area agi-error";

			} catch(e) {
			}
		}
	}

	this.clear_fields = function()
	{
		for (i = 0; i < this.errors.length; i++)
		{
			try{
				document.getElementById(this.errors[i].field + "-error").className = "";
			} catch(e) {
			}
		}
	}

	this.to_html = function()
	{
		var html = "";
		for (i = 0; i < this.errors.length; i++)
		{
			html += this.error_html.replace("%s", this.errors[i].message);
		}
		return html;
	}

	this.show = function()
	{
		this.display(true);
	}

	this.hide = function()
	{
		this.display(false);
	}

	this.reset = function()
	{
		this.hide();
		this.errors = new Array();
	}

	this.add = function(error)
	{
		this.errors.push(error);
	}

	this.add_error = function(field, message, type)
	{
		if (!type)
			type = this.ERROR;
		this.add(new Error(field, message, type));
	}
}

