/*global-block-begin*/


dojo.require('barrique.widget.TextInput');

var inPlaceEditArtifacts = {};
var inPlaceEditCounter = 0;

function isEditInPlaceEnabled(artifact) {
    return browserContext.isEditModeEnabled() && !browserContext.isPreviewModeEnabled() && 
        artifactManager.hasEditRight(artifact);
}
function tagInPlaceEdit(args, innerHtml) {
    var clazz = typeof args['class'] != 'undefined' ? args['class'] : '',
        style = typeof args.style != 'undefined' ? args.style : '',
        id = typeof args.id != 'undefined' ? args.id : 'in-place-edit-'+inPlaceEditCounter++,
        isEditable = args.editable == null ? isEditInPlaceEnabled(args.artifact) : 
            (args.editable == true || args.editable == 'true' ? true : false);
    inPlaceEditArtifacts[id] = {};
    inPlaceEditArtifacts[id].artifact = args.artifact;
    inPlaceEditArtifacts[id].attribute = args.attribute;
    inPlaceEditArtifacts[id].attributeType = barrique.getAttributeType(args.artifact, args.attribute);
    inPlaceEditArtifacts[id].mode = 'passive';
    inPlaceEditArtifacts[id].save = typeof args.save != 'undefined' ? args.save : false;
    inPlaceEditArtifacts[id].id = id;
    inPlaceEditArtifacts[id].alt = args.alt && isEditable ? args.alt : '';
    inPlaceEditArtifacts[id].isEditable = isEditable;
    if (isEditable) { clazz += '  inplaceedit-view'; }
    
    var htmlGetter = null,
        isContent = args.type ? args.type == 'content' : false;
    if (typeof args.tag != 'undefined' && args.tag == 'div') {
        htmlGetter = isContent ? getHtmlInPlaceEditContentDiv : getHtmlInPlaceEditDiv;
    } else {
        htmlGetter = isContent ? getHtmlInPlaceEditContentSpan : getHtmlInPlaceEditSpan;
    }
    
    return htmlGetter(id, args.artifact, args.attribute, clazz, style);
}
function onClickEditInPlace(id) {
    var ipea = inPlaceEditArtifacts[id];
    if (ipea.mode != 'active') {
        if (ipea.isEditable && isEditInPlaceEnabled(ipea.artifact)) {
            var s = getArtifactAttribute(ipea.artifact, ipea.attribute);
            if (s && s.length > 0) { s = s.length; }
            else { s = ipea.alt.length; }
            ipea.mode = 'active';
            var element = document.getElementById(id);
            element.innerHTML = getHtmlInPlaceEditActive(id, ipea.artifact, ipea.attribute, s, ipea.save);
            dojo.removeClass(element, 'inplaceedit-view');
            dojo.addClass(element, 'inplaceedit-edit');
            try {
                dojo.parser.parse(element);
            } catch (e) {
                console.warn('Cannot parse input element', e);
            }
            formManager.fill('InPlaceEditForm-'+id, ipea.artifact);
            var inputElement = document.getElementById('InPlaceEditForm-'+id+'-Input-input');
            inputElement.focus();
		    commonEditPage.hideToolbar();
        }
    }
}
function onClickEditInPlaceContent(id) {
    var ipea = inPlaceEditArtifacts[id];
    if (ipea.mode != 'active') {
        if (isEditInPlaceEnabled(ipea.artifact)) {
            inplaceEditContentManager.currentIpea = ipea;
            windowManager.openModalWindow(barrique.contextPath+'/sx/ArtifactHtmlPage?class=barrique.module.upload.web.UploadArea&view=select-files-dialog&callback=inplaceEditContentManager.addFilesRequest', 'SelectUploadedFilesDialog');
        }
    }
}
var inplaceEditContentManager = {
    currentIpea: null,
    addFilesRequest: function(files) {
        serverManager.asyncRequest('upload/FileImport', this.requestHandler, 
            new AsyncRequestCallback(dojo.hitch(this, 'onFileImportSuccess'), dojo.hitch(this, 'onFileImportError')), 
            {uploadAreaFiles:files, javaClass:'barrique.module.upload.web.GenericFileImport'});
    },
    onFileImportSuccess: function(genericFileImport) {
        commonHeader.displayInfo('File successfully read');
        var ipea = this.currentIpea,
            content = genericFileImport.getContent();
        console.debug(content.getMimeType());
        eval('ipea.artifact.set'+firstCharToUpperCase(ipea.attribute)+'(content)');
        saveInPlaceEdit(ipea);
        document.getElementById(ipea.id).innerHTML = getInPlaceEditContent(ipea.id);
    },
    onFileImportError: function(exceptions) {
        console.erro(exceptions);
        alert('Cannot read file');
    }
};
function onBlurEditInPlace(id) {
    setTimeout(function() {
        var ipea = inPlaceEditArtifacts[id];
        if (ipea.mode != 'passive') {
            ipea.mode = 'passive';
            var element = dojo.byId(id);
            element.innerHTML = getInPlaceEditText(id);
            dojo.removeClass(element, 'inplaceedit-edit');
            dojo.addClass(element, 'inplaceedit-view');
            commonEditPage.showToolbar();
            var widget = dijit.byId('InPlaceEditForm-'+id+'-Input');
            if (widget) { widget.destroyRecursive(true); }
        }
    }, 10);
}
function onOkInPlaceEdit(id) {
    var ipea = inPlaceEditArtifacts[id],
        oldValue = getArtifactAttribute(ipea.artifact, ipea.attribute);
        
    formManager.readOut(document.getElementById('InPlaceEditForm-'+id));
    if (oldValue == getArtifactAttribute(ipea.artifact, ipea.attribute)) {
        console.debug('no change detected');
        onBlurEditInPlace(id);
        return;
    }
    saveInPlaceEdit(ipea);
}
function saveInPlaceEdit(ipea) {
    if (!ipea.save) { onBlurEditInPlace(ipea.id); return; }
    ipea.onSaved = function(message) { onSavedInPlaceEdit(this, message); };
    var artifactWriter = new ArtifactWriter(false);
    artifactWriter.write(ipea.artifact, 'artifact');
    var data = artifactWriter.getData();
    serverManager.asyncRequest('SaveArtifact', data, 'inPlaceEditArtifacts["'+id+'"].onSaved');
    document.getElementById(id).innerHTML = 'Saving...';
}
function onSavedInPlaceEdit(ipea, message) {
    if (message != 'ok') { alert(message); } 
    onBlurEditInPlace(ipea.id);
}
function getArtifactAttribute(artifact, attribute) { 
    return eval('artifact.get'+firstCharToUpperCase(attribute)+'()'); 
}
function getInPlaceEditText(id) { 
    var ipea = inPlaceEditArtifacts[id];
    var text = getArtifactAttribute(ipea.artifact, ipea.attribute);
    var hasValue = true;
    var type = typeof(text);
    if (type == 'number') { text = text.toString(); } 
    if (type == 'boolean') { text = text.toString(); } 
    if (ipea.attributeType == 'java.util.Date') { text = barrique.date.toString(text); }
    if (text) {
        hasValue = ipea.attributeType == 'barrique.base.artifact.Text' ? (text.toString && text.toString().length > 0) : text.length > 0;
    } else {
        hasValue = false;
    }
    if (!hasValue && isEditInPlaceEnabled(ipea.artifact)) {
        return '<span class="inplaceedit-replacementtext">Edit '+ipea.alt+'</span>';
    }
    return text;
}
function getInPlaceEditContent(id) { 
    var ipea = inPlaceEditArtifacts[id];
    var content = getArtifactAttribute(ipea.artifact, ipea.attribute);
    if (!content) {
        if (isEditInPlaceEnabled(ipea.artifact)) {
            return '<span class="inplaceedit-replacementtext">Edit '+ipea.alt+'</span>';
        }
        return '';
    }
    return '<img src="'+content.getUrl(ipea.attribute)+'">';
}
function getInplaceEditTitle(id) {
    var ipea = inPlaceEditArtifacts[id];
    if (ipea.isEditable) {
        return 'Click to edit the \'' + (ipea ? ipea.alt : '')+'\'';
    } else {
        return ipea.alt ? ipea.alt : '';
    }
}


/*global-block-end*/
/*function-begin (getHeadHtml10) */
function getHeadHtml10() {
    var html = '';
    html += '\n\n\n\n';
    return html;
}
/*function-end (getHeadHtml10) */
/*function-begin (getBodyHtml10) */
function getBodyHtml10() {
    var html = '';
    html += '\n\n';
    html += '\n';
    html += '\n\n';
    html += '\n\n';
    html += '\n';
    html += '\n\n\n';
    return html;
}
/*function-end (getBodyHtml10) */
/*function-begin (getHtmlInPlaceEditSpan) */
function getHtmlInPlaceEditSpan(id, artifact, attribute, clazz, style) {
    var html = '';
    var tagargs0 = new Object();
    tagargs0['tag'] = 'span';
    tagargs0['id'] = id;
    tagargs0['title'] = getInplaceEditTitle(id);
    tagargs0['class'] = clazz;
    tagargs0['style'] = style;
    tagargs0['onclick'] = 'onClickEditInPlace(\''+id+'\')';
    html += tagHighlightSearchTerms(tagargs0, function() {
    var html = '';
    html += '';
    var scriptlet = getInPlaceEditText(id); if (scriptlet != null) html += scriptlet;
    html += '';
    return html;
}
    );
    return html;
}
/*function-end (getHtmlInPlaceEditSpan) */
/*function-begin (getHtmlInPlaceEditDiv) */
function getHtmlInPlaceEditDiv(id, artifact, attribute, clazz, style) {
    var html = '';
    var tagargs1 = new Object();
    tagargs1['tag'] = 'div';
    tagargs1['id'] = id;
    tagargs1['title'] = getInplaceEditTitle(id);
    tagargs1['class'] = clazz;
    tagargs1['style'] = style;
    tagargs1['onclick'] = 'onClickEditInPlace(\''+id+'\')';
    html += tagHighlightSearchTerms(tagargs1, function() {
    var html = '';
    html += '';
    var scriptlet = getInPlaceEditText(id); if (scriptlet != null) html += scriptlet;
    html += '';
    return html;
}
    );
    return html;
}
/*function-end (getHtmlInPlaceEditDiv) */
/*function-begin (getHtmlInPlaceEditActive) */
function getHtmlInPlaceEditActive(id, artifact, attribute, size, save) {
    var html = '';
    html += '\n\<form id=\"InPlaceEditForm-';
    var scriptlet = id; if (scriptlet != null) html += scriptlet;
    html += '\" onblur=\"onBlurEditInPlace(\'';
    scriptlet = id; if (scriptlet != null) html += scriptlet;
    html += '\')\" action=\"javascript:onOkInPlaceEdit(\'';
    scriptlet = id; if (scriptlet != null) html += scriptlet;
    html += '\')\" class=\"inplaceedit-form\"\>\n    \<table\>\<tr\>\n    \<td\>\n        ';
    if (barrique.getAttributeType(artifact, attribute) == 'barrique.base.artifact.Text') { 
    html += '\n            \<span dojoType=\"barrique.widget.TextInput\" id=\"InPlaceEditForm-';
    scriptlet = id; if (scriptlet != null) html += scriptlet;
    html += '-Input\" name=\"';
    scriptlet = attribute; if (scriptlet != null) html += scriptlet;
    html += '\" value=\"';
    scriptlet = getArtifactAttribute(artifact, attribute); if (scriptlet != null) html += scriptlet;
    html += '\" defaultLanguage=\"';
    scriptlet = getDefaultArtifactLanguage(artifact); if (scriptlet != null) html += scriptlet;
    html += '\"\>\<\/span\>\n        ';
    } else { 
    html += '\n        ';
    if (barrique.getAttributeType(artifact, attribute) == 'java.util.Date') { 
    html += '\n            \<span type=\"text\" dojoType=\"barrique.widget.DateTimeInput\" id=\"InPlaceEditForm-';
    scriptlet = id; if (scriptlet != null) html += scriptlet;
    html += '-Input\" value=\"';
    scriptlet = getArtifactAttribute(artifact, attribute)?dojo.date.stamp.toISOString(getArtifactAttribute(artifact, attribute)):''; if (scriptlet != null) html += scriptlet;
    html += '\" name=\"';
    scriptlet = attribute; if (scriptlet != null) html += scriptlet;
    html += '\"\>\<\/span\>\n        ';
    } else { 
    html += '\n            \<span type=\"text\" dojoType=\"dijit.form.TextBox\" id=\"InPlaceEditForm-';
    scriptlet = id; if (scriptlet != null) html += scriptlet;
    html += '-Input\" name=\"';
    scriptlet = attribute; if (scriptlet != null) html += scriptlet;
    html += '\" value=\"';
    scriptlet = getArtifactAttribute(artifact, attribute); if (scriptlet != null) html += scriptlet;
    html += '\"\>\<\/span\>\n        ';
    }
    html += '\n        ';
    }
    html += '\n    \<td\>';
    var tagargs2 = new Object();
    tagargs2['onclick'] = 'onOkInPlaceEdit(\''+id+'\')';
    tagargs2['name'] = save?'actions/filesave':'actions/ok';
    tagargs2['buttonClass'] = 'icon-button-default';
    html += tagIconButton(tagargs2, function() {
    var html = '';
    html += '';
    var scriptlet = save?'Save':'Ok'; if (scriptlet != null) html += scriptlet;
    html += '';
    return html;
}
    );
    html += '\<\/td\>\<td\>';
    var tagargs3 = new Object();
    tagargs3['onclick'] = 'onBlurEditInPlace(\''+id+'\')';
    tagargs3['name'] = 'actions\/no';
    html += tagIconButton(tagargs3, function() {
    var html = '';
    html += 'Cancel';
    return html;
}
    );
    html += '\<\/td\>\<\/tr\>\<\/table\>\n\<\/form\>\n';
    return html;
}
/*function-end (getHtmlInPlaceEditActive) */
/*function-begin (getHtmlInPlaceEditContentSpan) */
function getHtmlInPlaceEditContentSpan(id, artifact, attribute, clazz, style) {
    var html = '';
    html += '\<span id=\"';
    var scriptlet = id; if (scriptlet != null) html += scriptlet;
    html += '\" title=\"';
    scriptlet = getInplaceEditTitle(id); if (scriptlet != null) html += scriptlet;
    html += '\" class=\"';
    scriptlet = clazz; if (scriptlet != null) html += scriptlet;
    html += '\" style=\"';
    scriptlet = style; if (scriptlet != null) html += scriptlet;
    html += '\" onclick=\"onClickEditInPlaceContent(\'';
    scriptlet = id; if (scriptlet != null) html += scriptlet;
    html += '\')\"\>';
    scriptlet = getInPlaceEditContent(id); if (scriptlet != null) html += scriptlet;
    html += '\<\/span\>';
    return html;
}
/*function-end (getHtmlInPlaceEditContentSpan) */
/*function-begin (getHtmlInPlaceEditContentDiv) */
function getHtmlInPlaceEditContentDiv(id, artifact, attribute, clazz, style) {
    var html = '';
    html += '\<div id=\"';
    var scriptlet = id; if (scriptlet != null) html += scriptlet;
    html += '\" title=\"';
    scriptlet = getInplaceEditTitle(id); if (scriptlet != null) html += scriptlet;
    html += '\" class=\"';
    scriptlet = clazz; if (scriptlet != null) html += scriptlet;
    html += '\" style=\"';
    scriptlet = style; if (scriptlet != null) html += scriptlet;
    html += '\" onclick=\"onClickEditInPlaceContent(\'';
    scriptlet = id; if (scriptlet != null) html += scriptlet;
    html += '\')\"\>';
    scriptlet = getInPlaceEditContent(id); if (scriptlet != null) html += scriptlet;
    html += '\<\/div\>';
    return html;
}
/*function-end (getHtmlInPlaceEditContentDiv) */
