jQuery(document).ready(function($) {
	var lastFocusedElement;
    var humaneMessage = document.getElementById('humane-message');
    
    if (humaneMessage) {
        $(humaneMessage).css('position', 'fixed');
        
        var fadeOnMove = function () {
            $('#humane-message').fadeOut(3500, function () {
                $(this).remove();
                $(document).unbind('mousemove', fadeOnMove);
            });
        }
        
        setTimeout(function () { $(document).mousemove(fadeOnMove); }, 1000);
    }
    
    var simpleRemove = function (evt) {
        evt.preventDefault();
        
        var data = {};
        data[this.name] = 'remove';
        var elt = this;
        
        $.post(this.form.action + '?ajax=', data, function (){
            // TODO: Send a message about success?
            $(elt).parent('li').animate({opacity:0}, 'slow', function () { $(this).remove(); });
        }, 'json');
    };
    
    $('#fresca-password').focus();
    $('.remove-website-button, .remove-tag-button').live('click', simpleRemove);
    
    $('.add-tag-field').each(
        function ()
        {
            var match = /add-tag-([a-z_]+)$/.exec(this.id);
            
            if (match)
            {
                var url = 'tags/complete/' + match[1];
                $(this).autocomplete(url, {completeParam: 'tag', width:$(this).innerWidth()});
            }
        }
    ).focus(
		function ()
		{
			lastFocusedElement = this;
		}
	).keypress(
        function (event)
        {
            if (event.keyCode == 13)
            {
                var button = document.getElementById(event.target.id + '-button');
				
				if (button)
				{
					event.stopPropagation();
                    event.preventDefault();
					$(button).click();
				}
            }
        }
    );
	
    $('.add-website-button').click(function (evt) {
        evt.preventDefault();
        
        var nameInput = $('#new-website-name');
        var name = nameInput.val();
        var hrefInput = $('#new-website-href');
        var href = hrefInput.val();
        
        var data = {};
        data[this.name] = 'add';
        data['websiteName'] = name;
        data['websiteHref'] = href;
        
        nameInput.val('');
        hrefInput.val('');
        
        $.post(this.form.action + '?ajax=', data, function (json){
            var tpl = $('#site-list-tpl').html();
            var li = document.createElement('li');
            
            $(li).html(
                tpl
                    .replace('$anchor', json.anchor, 'g')
                    .replace('$displayText', json.displayText, 'g')
                    .replace('$href', json.href, 'g')
                    .replace('$id', json.id, 'g')
                )
                .appendTo('#site-list');
        }, 'json');
    });
    
    $('.add-tag-button').click(function (evt) {
        evt.preventDefault();
        
        var tagInput = $('#' + this.id.replace('-button', ''));
        var tag = tagInput.val();
        
        var data = {};
        data[this.name] = 'add';
        data[tagInput.attr('name')] = tag;
        
        tagInput.val('');
        var match = /command\[add-tag-(\w+)\]/.exec(this.name);
        var field = match[1];
        
        $.post(this.form.action + '?ajax=', data, function (){
            var tpl = $('#tag-list-tpl-' + field).html();
            var li = document.createElement('li');
            $(li).html(
                tpl
                    .replace(/\$tag/g, tag)
                    .replace(/\$field/g, field)
                )
                .appendTo('#tag-list-' + field);
        }, 'json');
    });
    $('.student-author-list').hide();
    $('.student-author-list-control').toggle(
        function () {$(this).next('.student-author-list').show();},
        function () {$(this).next('.student-author-list').hide();}
    );
    
    $('#import-list').css('minHeight', '400px');
    
    $('#import-search').click(function (e) {
        e.preventDefault();
        var $list = $('#import-list');
        $list.addClass('loader');
        $list.html('<h3 class="ajax-import-load-title">Retrieving Publications&hellip;</h3>');
        var action = $(this).parents('form').attr('action');
        action = action.replace(/\/import\//, '/ajaximport/');
        var firstName = $('#first-name').val();
        var lastName = $('#last-name').val();
        xerxesImportSteps($list, action, false, firstName, lastName);
        return false;
    });
});

/**
 * The number of attempts to try to connect to xerxes 
 * before we consider it a failure.
 *
 * @var integer
 */
var importTries = 0;
var importProgress = 0;

/**
 * A function to handle the different request phases 
 * of a Xerxes import process.
 *
 * @param JQuery container - The object that will 
 *        hold the Xerxes data on the page.
 * @param string action - The entry point for the 
 *        ajax calls.
 * @param string redirect - The redirect address 
 *        to send to the server for the next import step.
 */
function xerxesImportSteps(container, action, redirect, firstName, lastName)
{
    var data = {};
    
    if (redirect) data.redirect = redirect;
    data.firstName = firstName;
    data.lastName = lastName;
    
    $.post(action, data, 
        function (response)
        {
            if (response.progress > 1)
            {
                if (response.progress == importProgress)
                {
                    container.removeClass('loader');
                    container.html('<p class="error">At this time, Fresca cannot access find any citations in the database with the name you searched for.</p>');
                    return;
                }
                else
                {
                    importProgress = response.progress;
                }
            }
            
            if (response.redirect)
            {
                setTimeout(
                    function () 
                    {
                        xerxesImportSteps(container, action, response.redirect, firstName, lastName);
                    }, 2000
                );
            }
            else if (response.publications)
            {
                container.removeClass('loader');
                container.html(response.publications);
                
                $('.student-author-list').hide();
                $('.student-author-list-control').toggle(
                    function () {$(this).next('.student-author-list').show();},
                    function () {$(this).next('.student-author-list').hide();}
                );
            }
            else if (response.error)
            {
                if (importTries++ < 3)
                {
                    setTimeout(
                        function () 
                        {
                            xerxesImportSteps(container, action, false, firstName, lastName);
                        }, 500
                    );
                }
                else
                {
                    container.removeClass('loader');
                    container.html('<p class="error">At this time, Fresca cannot access the online data sources for your citations.  This problem will be resolved shortly.</p>');
                }
            }
        },'json'
    );
}
