var arrCache = [];
function validateCustomEmail(el, setMessage)
{
   var valid, message;
   valid = false;
   // check if email is supported
   if (el.val().length === 0)
   { // empty
      message = '';
   }
   else if (el.val().match(/^[A-Z0-9._%+\-]+@(gmail|googlemail|yahoo|aol|aim|hotmail)\.com$/i) !== null)
   {
      message = '';
      valid = true;
   }
   else if (el.val().match(/^[A-Z0-9._%+\-]+@[A-Z0-9.\-]+\.[A-Z]{2,4}$/i) !== null)
   { // unsupported
      message = '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
   { // invalid email
      message = 'A valid email account is required';
   }
   if (setMessage === undefined || setMessage)
   {
      setError(el, message);
      validateRequired(el, true, valid);
   }
   return valid;
}

function renderJSON(data)
{
    $('#sourceEmail').html(data.addressesFrom); // add heading
    if (data.message === 'success')
    {
        $.each(data.addresses, function (i, address) {
            if (address.email !== '')
            {
                var display = address.name === '' ? address.email : '<span>' + address.name + ',</span> ' + address.email;
                var checked = $('#email_addresses').val().match(address.email) === null ? '' : ' checked="checked"';
                var 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 = getCacheKey(username, password);
    var cache = null;
    for (var x = 0; x < arrCache.length; x = x + 1) {
        if (arrCache[x][0] === cacheKey)
        {
            cache = arrCache[x][1];
            break;
        }
    }
    return cache;
}
$(function () {
   $('#btnImport').attr("disabled", true).click(function () {
      // Add overlay to body
      $('#importedAddresses').prependTo('body').parent('body').prepend('<div id="overlay"></div>');
      sizeOverlay();

      $('#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').end().end() // disable buttons
         .show(); // show popin
      var username = $('#import_email').val();
      var password = $('#import_password').val();
      var rpc_url = $('#rpc_url').val() + '?e=' + escape(username) + '&p=' + escape(password);
      // Check Cache
      var 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 getJSON
      }
      return false;
   });
   $('#importAddresses #import_email').bind('keyup mouseup change', function () {
      // check if email is supported
      enableEl($('#btnImport'), validateCustomEmail($(this)) && validateRequired($('#importAddresses #import_password'), false));
   });
   $('#importAddresses #import_password').bind('keyup mouseup change', function () {
      enableEl($('#btnImport'), validateRequired($(this)) && validateCustomEmail($('#importAddresses #import_email'), false));
   });
    $('#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 () {
        $('#overlay').remove();// remove overlay
        $('#importedAddresses').hide();
        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(', '));
            $('#overlay').remove();// remove overlay
            $('#importedAddresses').hide();
        }
        return false;
    });
});
