var uploadLimit = 5;
var uploadLimitMsg = 'You may only add ' + uploadLimit + ' photos.';
var numPhotoUploads = 1;
var photoUploadId = 'photo_upload_';
var photoUploadClass = 'photoUpload';
var radioButtonClass = 'radioButton';
var profilePhotoId = 'profile_photo';
var profilePhotoCurrent = 1;
var lastPhotoUpload;

function add_photo_upload() {
    if (numPhotoUploads >= uploadLimit) {
        alert(uploadLimitMsg);
        return;
    }

    // Get unique number for this one.
    var i = 1;
    while (document.getElementById(photoUploadId + i)) {
        ++i;
    }

    var row = document.createElement('tr');
    row.id = photoUploadId + i;
    row.className = photoUploadClass;

    var td1 = document.createElement('td');

    var td2 = document.createElement('td');

    var fInput = document.createElement('input');
    fInput.type = 'file';
    fInput.name = photoUploadId + i;
    fInput.size = '30';

    var rInput = document.createElement('input');
    rInput.id = profilePhotoId + '_' + i;
    rInput.className = 'radioButton';
    rInput.type = 'radio';
    rInput.name = profilePhotoId;
    rInput.value = i;

    var link = document.createElement('a');
    link.id = 'make_' + profilePhotoId + '_' + i;
    link.className = 'makeProfilePhoto';
    link.href = 'javascript:make_profile_photo(' + i + ');';
    link.appendChild(document.createTextNode('Make profile photo'));

    td2.appendChild(fInput);
    td2.appendChild(link);
    td2.appendChild(rInput);

    row.appendChild(td1);
    row.appendChild(td2);

    var appendAfter;
    if (lastPhotoUpload) {
        appendAfter = lastPhotoUpload;
    }
    else {
        appendAfter = document.getElementById(photoUploadId + 1);
    }

    appendAfter.parentNode.insertBefore(row, appendAfter.nextSibling);
    lastPhotoUpload = row;
    ++numPhotoUploads;
}

function make_profile_photo(n) {
    var label = document.getElementById('make_' + profilePhotoId + '_' + profilePhotoCurrent);
    var link = document.getElementById('make_' + profilePhotoId + '_' + n);
    var newLabel = label.cloneNode(1);

    newLabel.id = newLabel.id.replace(/\d*$/, n);
    link.id = link.id.replace(/\d*$/, profilePhotoCurrent);
    link.href = link.href.replace(/make_profile_photo\(\d*\)/, 'make_profile_photo(' + profilePhotoCurrent + ')');

    link.parentNode.insertBefore(newLabel, link);
    label.parentNode.replaceChild(link, label);
    document.getElementById(profilePhotoId + '_' + n).checked = true;
    profilePhotoCurrent = n;
}
