// TODO: Is this worth putting somewhere more general?
jQuery.fn.replaceAttr = function(aName, rxString, repString) {
    return this.attr(
        aName,
        function() { return jQuery(this).attr(aName).replace(rxString, repString); }
    );
};

// This function expects the add & delete links to be descendants of an
// element with an id matching the form_prefix argument.  This is needed
// to accommodate multiple formsets in a given page.
function attach_upload_handlers(form_prefix, attach_top) {
    $('#' + form_prefix + ' .addelete .add').click(function(evt) {
        clone_upload_form(form_prefix, $(evt.target).parents('.upload'), attach_top)
        return false
    })

    $('#' + form_prefix + ' .addelete .delete').click(function(obj) {
        var counter_id = '#id_' + form_prefix + '-TOTAL_FORMS'
        $(obj.target).parents('.upload').remove()
        $(counter_id).attr('value', parseInt($(counter_id).attr('value'))-1)
        return false
    })

    $('#' + form_prefix + ' .show_upload').click(show_upload_form)
    $('#' + form_prefix + ' .show_upload').data('attach_top', attach_top)
    $('#' + form_prefix + ' .show_upload').data('form_prefix', form_prefix)

    var formcount = parseInt($('#id_' + form_prefix + '-TOTAL_FORMS').attr('value'))
    // If there's more than one, a form with errors is likely being redisplayed,
    // so we need to unhide the image forms
    if (formcount > 1) {
        var existing = $('#' + form_prefix + ' .upload')

        if (attach_top) {
            // The first shall be last
            var reorder_target = $(existing).slice(0).get(0)
            $(reorder_target).insertAfter(existing.slice(-1))

            for (var i = existing.length-1; i > 0; i--) {
                //alert($(existing[i]).text())
                $(existing[i]).insertBefore(reorder_target)
            }
        }
        $(existing[1]).toggleClass('bordlast')
        $(existing[existing.length-1]).toggleClass('bordlast')
        $(existing).slice(1).css('display', 'block')
    }
}

function show_upload_form(obj) {
    var attach_top = $(obj.target).data('attach_top')
    var form_prefix = $(obj.target).data('form_prefix')
    var existing = $('#' + form_prefix + ' .upload')

    // Don't add with this link as long as a visible form still exists
    if (existing.length > 1) {
        return false;
    }

    var src = existing.get(0)
    clone_upload_form(form_prefix, src, attach_top)
    return false
}

function clone_upload_form(form_prefix, obj, attach_top) {
    var counter_id = '#id_' + form_prefix + '-TOTAL_FORMS'
    var newform_idx = parseInt($(counter_id).attr('value'))
    if (newform_idx > 6) {
        return false
    }
    var lastform_idx = newform_idx - 1
    var newtotal = newform_idx + 1
    var old_prefix = form_prefix + '-' + lastform_idx
    var new_prefix = form_prefix + '-' + newform_idx
    var old_re = new RegExp(old_prefix)

    if (attach_top) {
        var target = $(obj).parent().children('.upload:first')
        var attach = 'before'
    } else {
        var target = $(obj).parent().children('.upload:last')
        var attach = 'after'
    }
    var cloneform = $(target).clone(true)

    $(cloneform).find('input').replaceAttr('name', old_re, new_prefix)
    $(cloneform).find('input').replaceAttr('id', old_re, new_prefix)
    $(cloneform).find('input').attr('value', '')
    $(cloneform).css('display', 'block')

    target[attach](cloneform)
    $(counter_id).attr('value', newtotal)
    return cloneform
}
