/*global-block-begin*/

    
barrique.module.attachment.Attachment.prototype.getMimeTypeFileName = function(size) {
    var mimeType = this.getContent().getMimeType(),
        index = mimeType ? mimeType.indexOf('/') : -1,
        type = index > 0 ? mimeType.substring(0, index) : mimeType,
        fileName = 'unknown';
    if (mimeType == 'application/pdf') {
        fileName = 'pdf';
    } else if (mimeType == 'text/html') {
        fileName = 'html';
    } else if (mimeType == 'text/plain') {
        fileName = 'txt';
    } else if (mimeType == 'application/zip') {
        fileName = 'tar';
    } else if (type == 'image') {
        fileName = 'image';
    } else if (type == 'video') {
        fileName = 'video';
    }
    return fileName;
}
barrique.module.attachment.Attachment.prototype.getIconUrl = function(size) {
    var fileName = this.getMimeTypeFileName();
    return barrique.contextPath+'/pages/'+barrique.buildNumber+'/barrique/base/images/icons/default/'+size+'x'+size+'/mimetypes/'+fileName+'.png';
}
barrique.module.attachment.Attachment.prototype.onContextMenu = function(context, menu) {
}
barrique.module.attachment.HasAttachment.prototype.onContextMenuAttachmentAspect = function(context, menu) {
    if (browserContext.isEditable() && artifactManager.hasWriteRight(context.getBaseArtifact())) {
        var relation = this;
        menu.addEntry('Edit', function() { window.location.href = relation.getTarget().getHref()+'?about=true'; }, null, 'actions/edit');
        menu.addEntry('Rename', function() { relation.rename() });
        menu.addEntry('Remove', function() { context.getBaseArtifact().removeFromAttachments(relation); }, null, 'actions/editdelete');
        menu.addSeparator();
        var text = new barrique.base.artifact.Text(),
            languages = text.getLanguages(),
            target = relation.getTarget(),
            content = target ? target.getContent() : null,
            currentLanguage = content ? content.getLanguage() : null;
        dojo.forEach(languages, function(language) {
            menu.addEntry(language, function() { relation.setContentLanguage(language); }, 'Language', null, language == currentLanguage);
        });
        if (barrique.base.artifact.hasPresentationHint(relation, 'teaser')) { 
            menu.addEntry('Show in Teaser', function() { barrique.base.artifact.removePresentationHint(relation, 'teaser'); }, 'Presentation', 'actions/apply'); 
        } else { 
            menu.addEntry('Show in Teaser', function() { barrique.base.artifact.addPresentationHint(relation, 'teaser'); }, 'Presentation'); 
        }
        if (barrique.base.artifact.hasPresentationHint(relation, 'context')) { 
            menu.addEntry('Show in Document View', function() { barrique.base.artifact.removePresentationHint(relation, 'context'); }, 'Presentation', 'actions/apply'); 
        } else { 
            menu.addEntry('Show in Document View', function() { barrique.base.artifact.addPresentationHint(relation, 'context'); }, 'Presentation'); 
        }
        menu.addSeparator();
        menu.addEntry('Edit Rights...', dojo.hitch(relation.getTarget(), 'onEditRights'), null, 'actions/edit_user');
    }
};
barrique.module.attachment.HasAttachment.prototype.rename = function() {
    var name = this.getName(),
        newName =  window.prompt('Change the name of the attachment', name);
    if (newName != null && newName != name) {
        var target = this.getTarget(),
            oldTitle = target.getTitle(),
            oldLanguage = oldTitle ? oldTitle.getDefaultLanguage() : getDefaultArtifactLanguage(this.getSource());
        target.setTitle(new barrique.base.artifact.Text(oldLanguage, newName));
        var segments = target.getRelationPath().getSegments();
        segments[segments.length-1][5] = newName;
        target.setRelationPath(new RelationPath(segments));
        this.setName(newName);
    }
}
barrique.module.attachment.HasAttachment.prototype.setContentLanguage = function(language) {
    var target = this.getTarget(),
        oldContent = target.getContent();
    if (oldContent) { 
        var oldLanguage = oldContent.getLanguage();
        if (oldLanguage != language) { 
            target.setContent(oldContent.changeLanguage(language));
        }
    }
}
barrique.module.attachment.HasAttachment.prototype.getHrefTitle = function() {
    var target = this.getTarget(),
        details = '';
    if (target && target.getContent()) {
        var content = target.getContent();
        details = ' ('+content.getLanguage()+', '+content.getSize()+' bytes)';
    }
    if (target && target.getDescription()) { return target.getDescription()+details; }
    if (target && target.getTitle()) { return target.getTitle()+details; }
    return this.getName()+details;
}
barrique.module.attachment.HasAttachment.prototype.getDownloadHref = function() {
    var href = this.getTarget().getHref();
    if (href == null) { return null; }
    var fileName = this.getTarget().getMimeTypeFileName();
    if (fileName == 'unknown' || fileName == 'tar') { href += '?download=true'; }
    return href;
}

function AttachmentAspect(id, artifact) {
    this.id = id; 
    this.artifact = artifact;
    
    this.onContextMenu = function(context, menu) {
        if (browserContext.isEditable() && artifactManager.hasLinkRight(artifact)) { 
            menu.addEntry('From Clipboard', dojo.hitch(this, 'addFromClipboard'), 'Add', 'actions/editpaste');
            menu.addEntry('Text Attachment', dojo.hitch(this, 'newTextAttachment'), 'New', 'mimetypes/txt');
            menu.addEntry('Remove All', dojo.hitch(this, 'removeAll'), null, 'actions/editdelete');
        }
    };
    this.addFromClipboard = function() {
        windowManager.openModalWindow(barrique.contextPath+'/sx/ArtifactHtmlPage?class=barrique.module.upload.web.UploadArea&view=select-files-dialog&callback=AttachmentAspects.get('+this.id+').onAddFromClipboard', 'AddFromClipboardDialog');
    };
    this.onAddFromClipboard = function(files) {
        serverManager.asyncRequest('upload/FileImport', this.requestHandler, new AsyncRequestCallback(dojo.hitch(this, 'onFileImportSuccess'), dojo.hitch(this, 'onFileImportError')), 
            {uploadAreaFiles:files, javaClass:'barrique.module.attachment.web.AttachmentFileImport'});
    };
    this.onFileImportSuccess = function(importedArtifact) {
        var attachments = importedArtifact.getAttachments(),
            defaultLanguage = getDefaultArtifactLanguage(this.artifact);
        commonHeader.displayInfo(attachments.length+' items added');
        for (var i = 0; i < attachments.length; i++) {
            var hasAttachment = attachments[i],
                attachment = hasAttachment.getTarget(),
                content = attachment ? attachment.getContent() : null;
            if (content) {
                var language = content.getLanguage();
                if (language == null || language.length == 0) {
                    attachment.setContent(content.changeLanguage(defaultLanguage));
                }
            }
            this.setTempRelationPath(this.artifact, hasAttachment, attachment);
        }
        this.artifact.addAttachments(attachments);
    };
    this.onFileImportError = function(exceptions) {
        console.debug(exceptions);
        alert('Sorry, cannot import file attachment!');
    };
    this.newTextAttachment = function() {
    	windowManager.openModalWindow(barrique.contextPath+'/sx/ArtifactHtmlPage?class=barrique.module.attachment.Attachment&view=add-comment&callback=AttachmentAspects.get('+this.id+').onNewTextAttachment', 'NewTextAttachmentDialog');
    };
    this.onNewTextAttachment = function(fileName, content) {
	    var attachment = new barrique.module.attachment.Attachment(),
	        hasAttachment = new barrique.module.attachment.HasAttachment(),
	        language = getDefaultArtifactLanguage(this.artifact);
		hasAttachment.setTarget(attachment);
		hasAttachment.setSource(this.artifact);
		hasAttachment.setName(fileName);
        attachment.setTitle(new barrique.base.artifact.Text(language, fileName));
        attachment.setContent(new StringContent(decodeURI(content), 'text/plain', language, 'UTF-8'));
		this.setTempRelationPath(this.artifact, hasAttachment, attachment); 
    	this.artifact.addToAttachments(hasAttachment);
    };
    this.setTempRelationPath = function(artifact, hasAttachment, attachment) {
    	if (!attachment.getRelationPath()) {
    	   var path = artifact.getRelationPath(),
    	       segments = path ? barrique.array.copy(path.getSegments()) : null;
    	   if (segments) {
    	       var segment = [hasAttachment.getJavaClass(), null, artifact.getArtifactId(), -1, null, hasAttachment.getName()];
    	       segments.push(segment);
    	       attachment.setRelationPath(new RelationPath(segments));
    	   }
    	}
    };
    this.removeAll = function() {
        var relations = this.artifact.getAttachments();
        for (var i = 0; i < relations.length; i++) {
            this.artifact.removeFromAttachments(relations[i]);
        }
    };
    this.update = function() {
        document.getElementById('AttachmentAspectAttachments-'+this.id).innerHTML = 
            getHtmlAttachmentAspectAttachments(this);
    };
    this.getAttachments = function() { return this.artifact.getAttachments(); }
    
    dojo.connect(this.artifact, 'addToAttachments', dojo.hitch(this, 'update'));
    dojo.connect(this.artifact, 'removeFromAttachments', dojo.hitch(this, 'update'));
}
var AttachmentAspects = {
    instances: [],
    getInstance: function(artifact) {
        var instance = null;
        for (var i = 0; i < this.instances.length; i++) {
            if (this.instances[i].artifact === artifact) { 
                instance = this.instances[i].instance;
            }
        }
        if (instance == null) {
            var id = this.instances.length;
            instance = new AttachmentAspect(id, artifact);
            this.instances.push({instance:instance, artifact:artifact});
        }
        return instance;
    },
    get: function(id) { return this.instances[id].instance; }
}

function tagAttachmentAspectTitlePane(args, nestedHtmlGetter) {
    return getHtmlAttachmentAspectTitlePane(AttachmentAspects.getInstance(args.artifact), nestedHtmlGetter);
}

function getVisibleAttachments(attachmentAspect, presentationHint) {
    var attachments = attachmentAspect.getAttachments()
    if (browserContext.isEditable()) { return attachments; }
    var result = [];
    for (var i = 0; i < attachments.length; i++) {
        if (barrique.base.artifact.hasPresentationHint(attachments[i], presentationHint)) {
            result.push(attachments[i]);
        }
    }
    return result;
}


/*global-block-end*/
/*function-begin (getHeadHtml32) */
function getHeadHtml32() {
    var html = '';
    html += '\n\n\n\n';
    return html;
}
/*function-end (getHeadHtml32) */
/*function-begin (getBodyHtml32) */
function getBodyHtml32() {
    var html = '';
    html += '\n    \n';
    html += '\n';
    html += '\n';
    html += '\n    \n\n';
    return html;
}
/*function-end (getBodyHtml32) */
/*function-begin (getHtmlAttachmentAspectTitlePane) */
function getHtmlAttachmentAspectTitlePane(attachmentAspect, nestedHtmlGetter) {
    var html = '';
    html += '\n    ';
    if (browserContext.isEditable() || getVisibleAttachments(attachmentAspect, 'context').length != 0) { 
    html += '\n        ';
    var tagargs0 = new Object();
    html += tagTitlePaneCtrl(tagargs0, function() {
    var html = '';
    html += '\n            ';
    var tagargs1 = new Object();
    html += tagTitleCtrl(tagargs1, function() {
    var html = '';
    var tagargs2 = new Object();
    tagargs2['artifact'] = attachmentAspect;
    html += tagContextMenu(tagargs2, function() {
    var html = '';
    html += 'Attachments';
    return html;
}
    );
    return html;
}
    );
    html += '\n            \<div id=\"AttachmentAspectAttachments-';
    var scriptlet = attachmentAspect.id; if (scriptlet != null) html += scriptlet;
    html += '\"\>';
    scriptlet = getHtmlAttachmentAspectAttachments(attachmentAspect); if (scriptlet != null) html += scriptlet;
    html += '\<\/div\>\n            ';
    if (nestedHtmlGetter != null) { 
    html += '';
    scriptlet = nestedHtmlGetter(); if (scriptlet != null) html += scriptlet;
    html += '';
    }
    html += '\n        ';
    return html;
}
    );
    html += '\n    ';
    }
    html += '\n';
    return html;
}
/*function-end (getHtmlAttachmentAspectTitlePane) */
/*function-begin (getHtmlAttachmentAspectAttachments) */
function getHtmlAttachmentAspectAttachments(attachmentAspect) {
    var html = '';
    html += '\n    ';
    if (getVisibleAttachments(attachmentAspect, 'context').length == 0) { 
    html += '\n        \<div style=\"font-style:italic;\" class=\"attachment-name\"\>No files attached\<\/div\>\n    ';
    } else { 
    html += '\n        ';
    var list3 = getVisibleAttachments(attachmentAspect, 'context');
    var len3 = list3.length;
    for (var i3 = 0; i3 < len3; i3++) {
        var hasAttachment = list3[i3];
    html += '\n        \<div class=\"attachment-name\"\>\n            ';
    if (browserContext.isEditable()) { 
    html += '\n                ';
    var tagargs4 = new Object();
    tagargs4['instance'] = hasAttachment;
    tagargs4['method'] = 'setName';
    tagargs4['tag'] = 'div';
    html += tagLiveTag(tagargs4, function(instance) {
    var html = '';
    html += '\n                    ';
    var tagargs5 = new Object();
    tagargs5['artifact'] = instance;
    tagargs5['context'] = new ContextInfo(attachmentAspect.artifact);
    tagargs5['aspect'] = 'AttachmentAspect';
    html += tagContextMenu(tagargs5, function() {
    var html = '';
    html += '\<img src=\"';
    var scriptlet = instance.getTarget().getIconUrl(16); if (scriptlet != null) html += scriptlet;
    html += '\" width=\"16\" height=\"16\" style=\"vertical-align:middle;margin-right:2px;\"\>\<a href=\"';
    scriptlet = instance.getDownloadHref(); if (scriptlet != null) html += scriptlet;
    html += '\" title=\"';
    scriptlet = instance.getHrefTitle(); if (scriptlet != null) html += scriptlet;
    html += '\"\>';
    scriptlet = instance.getTarget().getTitle(); if (scriptlet != null) html += scriptlet;
    html += '\<\/a\>';
    return html;
}
    );
    html += '\n                ';
    return html;
}
    );
    html += '\n            ';
    } else { 
    html += '\n            	';
    if (hasAttachment.getTarget().getContentHref() != null) { 
    html += '\n	                \<a href=\"';
    var scriptlet = hasAttachment.getDownloadHref(); if (scriptlet != null) html += scriptlet;
    html += '\" title=\"';
    scriptlet = hasAttachment.getHrefTitle(); if (scriptlet != null) html += scriptlet;
    html += '\"\>\n	                \<img src=\"';
    scriptlet = hasAttachment.getTarget().getIconUrl(16); if (scriptlet != null) html += scriptlet;
    html += '\" width=\"16\" height=\"16\" style=\"vertical-align:middle;margin-right:2px;\"\>';
    scriptlet = hasAttachment.getTarget().getTitle(); if (scriptlet != null) html += scriptlet;
    html += '\<\/a\>\n                ';
    } else { 
    html += '\n                	\<img src=\"';
    scriptlet = hasAttachment.getTarget().getIconUrl(16); if (scriptlet != null) html += scriptlet;
    html += '\" width=\"16\" height=\"16\" style=\"vertical-align:middle;margin-right:2px;\"\>';
    scriptlet = hasAttachment.getTarget().getTitle(); if (scriptlet != null) html += scriptlet;
    html += '\n                ';
    }
    html += '\n            ';
    }
    html += '\n        \<\/div\>\n        ';
    }
    html += '\n    ';
    }
    html += '\n';
    return html;
}
/*function-end (getHtmlAttachmentAspectAttachments) */
/*function-begin (getHtmlAttachmentAspectSearchHit) */
function getHtmlAttachmentAspectSearchHit(attachmentAspect) {
    var html = '';
    html += '\n    ';
    if (getVisibleAttachments(attachmentAspect, 'teaser').length > 0) { 
    html += '\n        \<div class=\"search-hit-relations\"\>\n            \<span class=\"relation-type\"\>Attachments:\<\/span\>\n            \<ul\>\n            ';
    var list6 = getVisibleAttachments(attachmentAspect, 'teaser');
    var len6 = list6.length;
    for (var i6 = 0; i6 < len6; i6++) {
        var hasAttachment = list6[i6];
    html += '\n            \<li\>\n                \<span class=\"attachment-name\"\>\<a href=\"';
    var scriptlet = hasAttachment.getDownloadHref(); if (scriptlet != null) html += scriptlet;
    html += '\" title=\"';
    scriptlet = hasAttachment.getHrefTitle(); if (scriptlet != null) html += scriptlet;
    html += '\"\>\<img src=\"';
    scriptlet = hasAttachment.getTarget().getIconUrl(16); if (scriptlet != null) html += scriptlet;
    html += '\" width=\"16\" height=\"16\" style=\"vertical-align:middle;margin-right:2px;\"\>';
    scriptlet = hasAttachment.getTarget().getTitle(); if (scriptlet != null) html += scriptlet;
    html += '\<\/a\>\<\/span\>\n            \<\/li\>\n            ';
    }
    html += '\n            \<\/ul\>\n        \<\/div\>\n    ';
    }
    html += '\n';
    return html;
}
/*function-end (getHtmlAttachmentAspectSearchHit) */
