/*jslint browser: true */
/*global $, resourcePath, showModal, closeModal, escape: true */
var arrCache = [];
function setValidEmailIcon(val)
{
    if (val === 'supported' || val === 'unsupported' || val === 'invalid')
    {
        var path, alt;
        path = resourcePath + (val === 'supported' ? '/images/icn_success.gif' : '/images/icn_failure.gif');
        alt = (val === 'supported' ? 'Supported Email Address' : (val === 'unsupported' ? 'Unsupported Email Address' : 'Invalid Email Address'));
        if ($('#valid_email').length > 0)
        {
            $('#valid_email').attr('src', path).attr('alt', alt);
        }
        else
        {
            $('#import_email').after('<img id="valid_email" src="' + path + '" alt="' + alt + '" width="13" height="13" />'); // email, but not valid
        }
    }
    else
    {
        $('#valid_email').remove(); // remove icon
    }
}
function setInstructions(val)
{
    if (val === 'supported' || val === 'unsupported' || val === 'invalid')
    {
        $('#instructions ol').hide();
        var text = '';

        if (val === 'supported')
        {
            text = 'Enter account password';
        }
        else if (val === 'unsupported')
        {
            text = 'We do not support contacts from:<br /><strong>' + $('#importAddresses #import_email').val().match(/\b[A-Z0-9.\-]+\.[A-Z]{2,4}\b/i) + '</strong><br />Please enter an email address from: gmail, Yahoo!, AOL or Hotmail';
        }
        else if (val === 'invalid')
        {
            text = $('#importAddresses #import_email').val() + ' is not a valid email address';
        }
        if ($('#stepInstructions').length === 0)
        {
            $('<p id="stepInstructions"></p>').appendTo('#instructions');
        }
        $('#stepInstructions').html(text);
    }
    else
    {
        $('#instructions ol').show();
    }
}

function enablePassword(val)
{
    if (val)
    {
        $('#importAddresses #import_password').removeAttr("disabled").removeClass("disabled"); // enabled password field
    }
    else
    {
        $('#importAddresses #import_password').attr("disabled", true).addClass("disabled").val('');
        $('#btnImport').attr("disabled", true).parent('span').addClass("disabled");
    }
}

function renderJSON(data)
{
    $('#sourceEmail').html(data.addressesFrom); // add heading
    if (data.message === 'success')
    {
        $.each(data.addresses, function (i, address) {
            if (address.email !== '')
            {
                var display, checked, output;
                display  = address.name === '' ? address.email : '<span>' + address.name + ',</span> ' + address.email;
                checked = $('#email_addresses').val().match(address.email) === null ? '' : ' checked="checked"';
                output = '<label><input type="checkbox" class="radio" value="' + address.email + '"' + checked + '></input>' + display + '</label>';
                $('<li></li>').html(output).appendTo("#addressList");
            }
        });
        $('#importedAddresses')
            .find('#importMessageArea').hide().find('#importMessage').html('').end().end() // hide message
            .find('.linkButton a, #btnInclude').removeClass("disabled").parent().removeClass('disabled').end().end() // enable buttons
            .find('#addressList').show(); // show list
    } else {
        //error message
        $('#importedAddresses')
            .find('#progressBar').hide().end() // hide progress bar
            .find('#importMessage').html(data.message); // show error message
    }
}

function getCacheKey(username, password)
{
    var seperator = '||';
    return username + seperator + password;
}

function checkCache(username, password)
{
    var cacheKey, cache, x;
    cacheKey = getCacheKey(username, password);
    cache = null;
    for (x = 0; x < arrCache.length; x = x + 1) {
        if (arrCache[x][0] === cacheKey)
        {
            cache = arrCache[x][1];
            break;
        }
    }
    return cache;
}

$(function () {
    $('<img>').attr('src', resourcePath + '/images/icn_success.gif');
    $('<img>').attr('src', resourcePath + '/images/icn_failure.gif');
    $('#importAddresses #import_password').attr("disabled", true).addClass("disabled").val('');
    $('#btnImport').parent('span').addClass('disabled').end().attr('disabled', true).click(function () {
        var username, password, rpc_url, cacheValue;
        // Add overlay to body
        $('#submitOverlay').width($(document).width()).height($(document).height()); // add overlay
        $('#sourceEmail').html($('#import_email').val());
        $('#importedAddresses')
            .find('#addressList').empty().hide().end() // clear and hide address list
            .find('#importMessageArea').show().find('#progressBar').show().end().end() // show message area and image
            .find('#importMessage').html('Importing address list from <strong>' + $('#import_email').val() + '</strong>').end() // add wait message
            .find('.linkButton a, #btnInclude').addClass("disabled").parent().addClass('disabled'); // disable buttons
        showModal($('#importedAddresses'));
        username = $('#import_email').val();
        password = $('#import_password').val();
        rpc_url = $('#rpc_url').val() + '?e=' + escape(username) + '&p=' + escape(password);
        // Check Cache
        cacheValue = checkCache(username, password);
        if (cacheValue !== null) {
            renderJSON(cacheValue);
        } else {
            // import the addresses
            $.getJSON(rpc_url,
                function (data) {
                    arrCache.push([getCacheKey(username, password), data]);
                    renderJSON(data);
                } // end function
            ); // end getJSON
        }
        return false;
    });
    $('#importAddresses #import_email').keyup(function () {
        // check if email is supported
        if ($(this).val().match(/^[A-Z0-9._%+\-]+@(gmail|googlemail|yahoo|aol|aim|hotmail)\.com$/i) !== null)
        {
            $(this).removeClass('invalid');
            enablePassword(true); // enabled password field
            setInstructions('supported');
            setValidEmailIcon('supported'); // email is valid
        }
        else if ($(this).val().match(/^[A-Z0-9._%+\-]+@[A-Z0-9.\-]+\.[A-Z]{2,4}$/i) !== null)
        {
            $(this).addClass('invalid');
            setInstructions('unsupported');
            enablePassword(false); // disable password field
            setValidEmailIcon('unsupported'); // email, but not valid
        }
        else
        {
            $(this).removeClass('invalid');
            setInstructions('invalid');
            enablePassword(false); // disable password field
            setValidEmailIcon('invalid'); // remove icon
        }
    });
    $('#importAddresses #import_password').keyup(function () {
        var bDisable = $(this).val().match(/^.+$/i) === null;
        $('#btnImport').attr("disabled", bDisable);
        if (bDisable) {
            $('#btnImport').parent('span').addClass('disabled');
        } else {
            $('#btnImport').parent('span').removeClass('disabled');
        }
    });
    $('#importLink').click(function () {
        $('#import_email').focus();
        return false;
    });
    $('#btnSelect').click(function () {
        if (!$(this).hasClass('disabled'))
        {
            $('#addressList input').attr("checked", true);
        }
        return false;
    });
    $('#btnUnselect').click(function () {
        if (!$(this).hasClass('disabled'))
        {
            $('#addressList input').attr("checked", false);
        }
        return false;
    });
    $('#btnCancel').click(function () {
        $('#submitOverlay').remove();// remove overlay
        closeModal($('#importedAddresses'));
        return false;
    });
    $('#btnInclude').click(function () {
        if (!$(this).hasClass('disabled'))
        {
            var emails = [];
            $('#addressList input:checked').each(function () {
                var email = $(this).val().match(/\b[A-Z0-9._%+\-]+@[A-Z0-9.\-]+\.[A-Z]{2,4}\b/i);
                if ((email !== null) && ($('#email_addresses').val().match(email) === null))
                {
                    emails.push($(this).val());
                }
            });
            if (($('#email_addresses').val().length > 0) && ($('#email_addresses').val().match(/,\s*$/i) === null))
            {
                $('#email_addresses').val($('#email_addresses').val() + ', ');
            }
            $('#email_addresses').val($('#email_addresses').val() + emails.join(', '));
            $('#submitOverlay').remove();// remove overlay
            closeModal($('#importedAddresses'));
        }
        return false;
    });
});
