UserPhoto = function(config) {
    if (typeof config == 'object') {
        for (var prop in config) {
            this[prop] = config[prop];
        }
    }
    this.uploadedPhotos = new Array();
    for (var i = 0; i < this.maxPhotoCount; ++i) {
        this.uploadedPhotos[i] = 0;
    }
}

UserPhoto.prototype.maxPhotoCount = 20;
UserPhoto.prototype.photosInRow = 4;
UserPhoto.prototype.removeUrl = '/plugins/ajax/remove_photo.php';
UserPhoto.prototype.uploadBusy = false;

UserPhoto.prototype.countPhotos = function () {
    for (var i = 0; i < this.maxPhotoCount; ++i) {
        if (this.uploadedPhotos[i] == 0) {
            return i;
        }
    }
    return this.maxPhotoCount;
}


UserPhoto.prototype.getDeleteOnClickHandler = function(scope, i, unifiedid) {
    return function() {
        scope.remove(i, unifiedid);
        return false;
    }
}

UserPhoto.prototype.getNextNodeParent = function () {
    var i = this.countPhotos();
    var newNodeParent;
    if (i == 0) {
        newNodeParent = $('downloaded-photo-').parentNode;
    } else if (i % this.photosInRow == 0) {
        newNodeParent = document.createElement('TR');
        $('downloaded-photo-').parentNode.parentNode.appendChild(newNodeParent);
    } else {
        newNodeParent = $('downloaded-photo-' + i).parentNode;
    }
    return newNodeParent;
}

UserPhoto.prototype.showUploadBlock = function (){
    var i = this.countPhotos();
    if (i == this.maxPhotoCount) {
        return false;
    }

    var origin 	= $('downloaded-photo-');
    var node 	= origin.cloneNode(true);
    var textplace= node.getElementsByTagName('IMG')[0].parentNode.parentNode;
    var span 	= node.getElementsByTagName('SPAN')[0];
    var input  	= node.getElementsByTagName('LABEL')[0];
    var label  	= node.getElementsByTagName('INPUT')[0];
    label.style.visibility="hidden";
    input.style.visibility="hidden";
    span.style.visibility="hidden";
    node.id += (i + 1);
    this.getNextNodeParent().appendChild(node);
    $('photoUploadButton').value="Ждите...";
    $('photoUploadButton').disabled=true;
    this.uploadBusy = true;
    textplace.innerHTML="<div style='height:57px; font-size: 12px; font-weight: bold; color: #aaaaaa'>Загрузка...</div>";
    node.style.display = '';
    return true;
}

UserPhoto.prototype.hideUploadBlock = function() {
    var i = this.countPhotos();
    if (i == this.maxPhotoCount) {
        return false;
    }

    var block = $('downloaded-photo-' + Number(i+1));
    var parentNode = block.parentNode;
    $('photoUploadButton').disabled=false;
    $('photoUploadButton').value="Загрузить фото";
    parentNode.removeChild(block);
}

UserPhoto.prototype.doneUpload = function(src, width, height, tempname,
                                          unifiedid, caption) {
    var inp = $('input-file-upload');
    if (inp) {
        var parentNode = inp.parentNode;
        if (parent) {
            parentNode.removeChild(inp);
            inp = document.createElement('INPUT');
            inp.type = 'file';
            inp.name = 'photo';
            inp.id   = 'input-file-upload';
            inp.size = 16;
            parentNode.appendChild(inp);

        }
    }

    var i = this.countPhotos();
    if (i == this.maxPhotoCount) {
        return false;
    }

    var origin 	= $('downloaded-photo-');
    var node 	= origin.cloneNode(true);
    var img 	= node.getElementsByTagName('IMG')[0];
    var link 	= node.getElementsByTagName('A')[0];
    var label 	= node.getElementsByTagName('LABEL')[0];
    var input  	= node.getElementsByTagName('INPUT')[0];
    var filename= node.getElementsByTagName('INPUT')[1];

    node.id += (i + 1);

    img.src = src;

    label.setAttribute('for', (i + 1));
    input.id 	+= (i + 1);
    if (caption) {
        input.value = caption;
    }
    filename.id += (i + 1);
    filename.value = tempname;

    link.onclick = this.getDeleteOnClickHandler(this, i, unifiedid);

    if (unifiedid) {
        link.setAttribute('unifiedid', unifiedid);
    }

    this.getNextNodeParent().appendChild(node);

    node.style.display = '';

    this.uploadedPhotos[i] = 1;

    if (this.countPhotos() == this.maxPhotoCount) {
        $('downloaded-photo-form').style.display = 'none';
    }

    this.uploadBusy = false;
}

UserPhoto.prototype.remove = function(i, unifiedid) {
    if (this.uploadBusy) {
        alert('Нельзя удалять фотографии во время загрузки');
        return;
    }

    // TODO rewrite
    var block = $('downloaded-photo-' + (i+1));
    var src = block.getElementsByTagName('IMG')[0].src;
    var parentNode = block.parentNode;

    parentNode.removeChild(block);

    var count = this.countPhotos();

    for (var j = i+1; j < count; ++j) {
        var node = $('downloaded-photo-' + (j+1));
        node.id = 'downloaded-photo-' + j;

        var link  = node.getElementsByTagName('A')[0];
        var linkUnifiedId = link.getAttribute('unifiedid');
        link.onclick = this.getDeleteOnClickHandler(this, j-1, linkUnifiedId);

        var label = node.getElementsByTagName('LABEL')[0];
        label.setAttribute('for', 'ad-caption-' + j);

        var input = node.getElementsByTagName('INPUT')[0];
        input.id = 'ad-caption-' + j;

        var filename = node.getElementsByTagName('INPUT')[1];
        filename.id = 'filename-' + j;

        if (j % this.photosInRow == 0) {
            // Move cell to previous row
            var parentNode = node.parentNode;
            parentNode.removeChild(node);
            $('downloaded-photo-' + (j-1)).parentNode.appendChild(node);
            if (j == count - 1) {
                // Removing last empty row
                parentNode.parentNode.removeChild(parentNode);
            }
        }
    }
    this.uploadedPhotos[count-1] = 0;

    new Ajax.Request(this.removeUrl, {
        parameters : 'photo=' + src + '&id=' + i + '&unid=' + unifiedid,
        onComplete : function() {
            $('downloaded-photo-form').style.display = '';
        }
    });

    return false;
}

UserPhoto.prototype.getCaptions = function(paramName, elementPrefix) {
    elementPrefix = elementPrefix || 'ad-caption-';
    paramName = paramName || 'add-captions';
    var result = Array();
    for (var i = 0; i < this.maxPhotoCount; ++i) {
        if (this.uploadedPhotos[i] == 1 && $(elementPrefix + (i + 1))) {
            result.push(paramName + '[]=' + $F(elementPrefix + (i + 1)));
        }
    }
    return result.join('&');
}

UserPhoto.prototype.getPhotos = function(elementPrefix) {
    elementPrefix = elementPrefix || 'ad-caption-';

    var ph_count = this.countPhotos();
    var params = {};
    for (i = 0; i < ph_count; i++){
        if ($('filename-'+(i+1))){
            params['photo-' + $F('filename-'+(i+1))] = $F(elementPrefix+(i+1));
        }
    }

    return params;
}