/*global-block-begin*/

dojo.require("dojox.widget.Toaster");
dojo.require("dojo.date.locale");
dojo.require("dojo.dnd.Moveable");

var commonHeader = {
    actions: [],
    actionMap: {},
    hrefMap: {},
    appendixMap: {},
    
    addAction: function(name, action, href, appendix) {
        this.actions.push(name);
        this.actionMap[name] = action;
        if (href) { this.hrefMap[name] = href; }
        if (appendix) { this.appendixMap[name] = appendix; }
    },
    getActions: function() { return this.actions; },
    execute: function(name) { 
        var action = this.actionMap[name];
        if (action != null) { action(); }
    },
    getHref: function(name) {
        var href = commonHeader.hrefMap[name];
        if (typeof href == 'function') { return href(); } 
        else if (typeof href != 'undefined') { return href; }
        return null;
    },
    onKeyDown: function(keyCode) {
        for (var i = 0; i < this.actions.length; i++) {
            var actionName = this.actions[i];
            if (actionName.toUpperCase().charCodeAt(0) == keyCode) {
                this.actionMap[actionName]();
                return true;
            }
        } 
        if (browserContext.isEditable()) { 
            if (keyCode == 2000+'S'.charCodeAt(0)) {
                commonEditPage.save();
                return true;
            }
            if (keyCode == 2000+'P'.charCodeAt(0)) {
                commonEditPage.publish();
                return true;
            }
        }
        
        return false;
    },
    displayInfo: function(message, iconName) {
        if (iconName == null) { iconName = 'actions/info'; }
        this.displayMessage(message, iconName, 'INFO');
    },
    displayWarning: function(message, iconName) {
        if (iconName == null) { iconName = 'actions/status_unknown'; }
        this.displayMessage(message, iconName, 'WARNING');
    },
    displayError: function(message, iconName) {
        if (iconName == null) { iconName = 'actions/status_unknown'; }
        this.displayMessage(message, iconName, 'ERROR');
    },
    displayMessage: function(message, iconName, type) {
        var html = '';
        if (iconName != null) {
            html += '<img src="'+barrique.base.getIconHref(iconName, 16)+'" width="16" height="16" style="vertical-align:middle;">&nbsp;';
        }
        html += message;
        dojo.publish('commonHeaderMessageTopic', [{message: html, type: type}]);
    }
};
pageContext.addOnKeyDown(dojo.hitch(commonHeader, 'onKeyDown'));

if (browserContext.isGuestUser()) {
    commonHeader.addAction('login', function() {
        windowManager.openModalWindow(barrique.contextPath+'/sx/security/LoginForm', 'LoginModalDialog'); },
        barrique.contextPath+'/sx/security/LoginForm' );
    if (openSearchDialog) { commonHeader.addAction('search', commonHeaderSearch); }
} else {
	//var logoutAppendix = '&nbsp;<i>(<a href="'+barrique.contextPath+'/sx/security/UserHome">'+sessionUserName+'</a>)</i>';
	var logoutAppendix = ' (<a href="'+barrique.contextPath+'/sx/security/UserHome">'+sessionUserName+'</a>)';
    commonHeader.addAction('logout', logout, null, logoutAppendix);
    if (openSearchDialog) { commonHeader.addAction('search', commonHeaderSearch); }
    
    if (browserContext.isEditModeEnabled()) {
        commonHeader.addAction('browse mode', function() { 
            browserContext.disableEditMode(); window.location.reload(); });
    } else {
        commonHeader.addAction('edit mode', function() { 
            browserContext.enableEditMode(); window.location.reload(); });
    }
}

function logout() {
    serverManager.asyncRequest('security/Logout', null, {onOk: onLogout, onError: onLogoutError}, null);
}
function onLogout() {
    browserContext.disableEditMode();
    window.location.reload();
}
function onLogoutError(exception) {
    console.debug('Exception while log out user', exception);
}
function commonHeaderSearch() {
    openSearchDialog(commonEditPage.mainArtifact);
}
function tagCommonHeader(args, nestedHtmlGetter) {
    return getHtmlCommonHeader(nestedHtmlGetter);
}
function tagCommonHeaderAction(args, nestedHtmlGetter) {
    commonHeader.addAction();
}
function onMouseOverHeaderLink(index) {
    var headerLink = document.getElementById('Header-Link-'+index);
    var href = commonHeader.getHref(commonHeader.actions[index]);
    if (href != null) { headerLink.href = href; }
}
function onClickHeaderLink(index) {
    var headerLink = document.getElementById('Header-Link-'+index),
        name = commonHeader.actions[index],
        action = commonHeader.actionMap[name];
    if (action != null) { 
        headerLink.href = 'javascript:commonHeader.execute(\''+name+'\')'; 
    }
}

function tagFooterCtrl(args, nestedHtmlGetter) {
    var artifacts = args.artifacts ? args.artifacts : null;
    return getHtmlCommonFooter(artifacts, nestedHtmlGetter);
}


function tagSubstituteLinkCtrl(args, nestedHtmlGetter) {
    var relationPath = args.artifact.getRelationPath(),
        targetPath = relationPath ? relationPath.getPath() : null;
        targetId = args.artifact.getArtifactId(),
        html = '',
        nestedHtml = nestedHtmlGetter();
    
    if (!browserContext.isGuestUser()) {
        html += '<span id="substitute-element-'+targetId+'" class="substitute-link-ctrl"><img title="Create a private URL" onclick="createSubstituteToken(\''+targetPath+'\')" src="'+barrique.base.getIconHref('actions/bookmark', 16)+'"/></span>';
    }
    
    return html;
}
function createSubstituteToken(targetPath) {
    if (confirm('The substitute link will give users your rights of all objects on this page.\nDo you want to continue?')) {
        serverManager.asyncRequest('security/CreateSubstitute', null, {onOk: onSubstituteCreated, onError: onSubstituteCreatedError}, {path:targetPath});
    }
}
function onSubstituteCreated(targetId, href, substituteToken) {
    var substituteDiv = dojo.byId('substitute-element-'+targetId),
        link = href;
    if (targetId == artifactManager.getMainArtifact().getArtifactId()) {
        if (window.location.search.length > 1) { link += '&'+window.location.search.substring(1); }
        if (window.location.hash.length > 1) { link += window.location.hash; }
    }
    substituteDiv.innerHTML = '<a href="'+link+'"><img src="'+barrique.base.getIconHref('actions/bookmark_add', 16)+'"/></a>';
} 
function onSubstituteCreatedError(exception) {
    console.debug('Cannot create substitute link', exception);
    alert('Cannot create substitute link.\n');
}

var commonEditPage = {
    managedArtifacts: [],
    mainArtifact: null,
    htmlGetter: null,
    hasModifications: false,
    commonSaveButtonsId: null,
    saveRequestParameter: null,
    onSaveLocation: null,
    hasEditToolbar: browserContext.isEditModeEnabled(),
    toolbarHideCount: 0,

    setMainArtifact: function(artifact) {
        this.mainArtifact = artifact;
        this.addArtifact(artifact);
    },
    addArtifact: function(artifact) {
        if (typeof(artifact) == 'undefined' || artifact == null) { console.debug('commonEditPage.addArtifact - invalid argument', artifact); artifact.foobar(); }
        if (!barrique.array.contains(this.managedArtifacts, artifact)) { this.managedArtifacts.push(artifact); }
        if (artifact.isModified()) { this.onArtifactModification(artifact, null); }
    },
    isManaged: function(artifact) {
        var artifactWriter = new ArtifactWriter(true);
        for (var i = 0; i < this.managedArtifacts.length; i++) {
            //console.debug('isManaged', i, this.managedArtifacts[i].getArtifactId());
            artifactWriter.write(this.managedArtifacts[i], 'artifact'+i);
        }
        return artifactWriter.isWritten(artifact);
    },
    addSaveRequestParameter: function(params) {
        if (params == null) { return; }
        if (this.saveRequestParameter != null) {
            for (x in params) { this.saveRequestParameter[x] = params[x]; }
        } else {
            this.saveRequestParameter = params;
        }
    },
    setOnSaveLocation: function(location) { this.onSaveLocation = location; },
    save: function (sync, publishAcl) {
        var callback, 
            artifacts = this.managedArtifacts;
        for (var i = 0; i < artifacts.length; i++) {
            var artifact = artifacts[i];
            if (artifact && artifact.onSave) {
                var result = artifact.onSave(); 
                if (typeof(result) == 'boolean' && !result) {
                    return;
                }
            }
        }
        if (sync) { callback = new AsyncRequestCallback(dojo.hitch(this, 'onSyncSaved'), dojo.hitch(this, 'onSyncSavedError')); }
        else { callback = new AsyncRequestCallback(dojo.hitch(this, 'onSaved'), dojo.hitch(this, 'onSavedError')); }
        if (publishAcl) { 
            var artifactId = this.mainArtifact.getArtifactId();
            this.addSaveRequestParameter({publish:artifactId.toString()});
            var responseArtifact = new barrique.web.ResponseArtifact('reponseArtifact');
            responseArtifact.setParameter('publishAcl', publishAcl, 'Acl');
            artifacts = artifacts.concat([responseArtifact]); 
        }
        serverManager.asyncArtifactRequest(artifacts, 'SaveArtifact', callback, this.saveRequestParameter, sync);
        this.hasModifications = false;
        this.saveRequestParameter = null;
        this.updateButtons();
    },
    onSaved: function() {
        commonHeader.displayInfo('Successfully saved', 'actions/filesave');
        //this.updateButtons();
        if (this.onSaveLocation != null) {
            window.location.replace(this.onSaveLocation);
        } else {
            window.location.reload();
        }
    },
    onSavedError: function(exceptions) {
        console.debug('Cannot save the common edit artifact', exceptions);
        alert('Cannot save data');
        //dojo.byId(this.commonSaveButtonsId).innerHTML = ;
    },
    onSyncSaved: function() {
        alert('Sucessfully saved!');
    },
    onSyncSavedError: function(exceptions) {
        console.debug('Cannot save the common edit artifact', exceptions);
        alert('Cannot save data');        
    },
    publish: function() {
        var acl = null,
	        subjectMatrix = this.mainArtifact.getAcl()[1],
	        aclEntryCounter = 0;
	    for (var rightIndex = 0; rightIndex < subjectMatrix.length; rightIndex++) {
	        var subjectTypeVector = subjectMatrix[rightIndex];
	        for (var subjectTypeIndex = 0; subjectTypeIndex < subjectTypeVector.length; subjectTypeIndex++) {
	            var subjectArray = subjectTypeVector[subjectTypeIndex];
	            for (var subjectIndex = 0; subjectIndex < subjectArray.length; subjectIndex++) {
		            aclEntryCounter++;
	            }
	        }
	    }
	    if (aclEntryCounter > 0) {
	        if (this.mainArtifact.getParents() != null) {
	            var parents = this.mainArtifact.getParents();
	            if (parents.length > 0 && parents[0].getSource()) {
	                var parent = parents[0].getSource();
	                if (parent.getAcl) {
			       		acl = this.mainArtifact.getParents()[0].getSource().getAcl();
			       		acl[0] = browserContext.getUserId();
	                }
	            }
	        } 
	        if (!acl) { acl = artifactManager.addPublic(this.mainArtifact.getAcl()); }
	    } else {
		    acl = this.mainArtifact.getAcl();
	    }   
        var that = this;
        editAcl.editAcl({ 
            getAcl: function() { return acl; }, 
            setAcl: function(acl) {
                setTimeout('commonEditPage.onPublishAcl(\''+toJavaAcl(acl)+'\')', 0); 
            },
            getArtifactId: function() { return null; } }, false);
    },
    onPublishAcl: function(param) {
        this.save(false, param);
    },
    enablePreview: function() {
        browserContext.enablePreviewMode();
        this.updateButtons();
        this.updatePageDiv();
    },
    disablePreview: function() {
        browserContext.disablePreviewMode();
        this.updateButtons();
        this.updatePageDiv();
    },
    hideToolbar: function() {
        commonEditPage.toolbarHideCount++;
        if (commonEditPage.toolbarHideCount > 1) { return; }
        var toolbar = document.getElementById(commonEditPage.commonSaveButtonsId);
        if (!toolbar) { return; }
        toolbar.style.visibility = 'hidden';
    },
    showToolbar: function() {
        if (commonEditPage.toolbarHideCount > 0) { commonEditPage.toolbarHideCount--; }
        if (commonEditPage.toolbarHideCount > 0) { return; }
        var toolbar = document.getElementById(commonEditPage.commonSaveButtonsId);
        if (!toolbar) { return; }
        toolbar.style.visibility = 'visible';
    },
    updateButtons: function() {
        var buttons = document.getElementById(commonEditPage.commonSaveButtonsId).getElementsByTagName('td');
        for (var i = 0; i < buttons.length; i++) {
            if (buttons[i].id == 'CommonEditButtonEdit') {
                buttons[i].style.display = browserContext.isPreviewModeEnabled() ? 'table-cell' : 'none';
            } else {
                if (buttons[i].id == 'CommonEditButtonSave') {
                    buttons[i].style.display = browserContext.isPreviewModeEnabled() || !this.hasModifications ? 
                            'none' : 'table-cell';
                } else {
                    buttons[i].style.display = browserContext.isPreviewModeEnabled() ? 'none' : 'table-cell';
                }
            }
        }
    },
    updatePageDiv: function() {
        var element = dojo.byId('CommonEditPageDiv');
        element.innerHTML = this.htmlGetter();
        pageContext.processDeferred();
    },
    onArtifactModification: function(artifact, attributeName) {
        if (!this.hasModifications && this.isManaged(artifact)) {
            this.hasModifications = true;
            this.updateButtons();
        }
    },
    onPageUnload: function() {
        if (this.hasModifications && confirm('You have unsaved data.\nDo you want to save your changes?')) {
            this.save(true, false);
        }
        exit = false;
    },
    onRelationAdded: function(artifact, newRelation, attributeName) {
        if (!this.onRelationAttributeModified(artifact, newRelation, attributeName)) {
            console.debug('fixme: save unmanaged artifact');
            //commonHeader.displayInfo('Added to '+firstCharToUpperCase(attributeName)+': '+artifact.getTitle(), 'filesystems/folder');
        }
    },
    onRelationRemoved: function(artifact, newRelation, attributeName) {
        if (!this.onRelationAttributeModified(artifact, newRelation, attributeName)) {
            console.debug('fixme: save unmanaged artifact');
            //commonHeader.displayInfo('Removed from '+firstCharToUpperCase(attributeName)+': '+artifact.getTitle(), 'filesystems/folder');
        }
    },
    onRelationAttributeModified: function(artifact, newRelation, attributeName) {
        var target = newRelation.getTarget(),
            isSourceManaged = this.isManaged(artifact); 
        if (this.isManaged(target) && !isSourceManaged) { 
            this.addArtifact(artifact);
            return true; 
        }
        return isSourceManaged;
    }
};

dojo.connect(artifactManager, 'onRelationAdded', commonEditPage, 'onRelationAdded');
dojo.connect(artifactManager, 'onRelationRemoved', commonEditPage, 'onRelationRemoved');

function tagCommonEditPage(args, nestedHtmlGetter) {
    var html = '',
        toolbarButtons = args.toolbarButtons ? args.toolbarButtons : [];
    commonEditPage.htmlGetter = nestedHtmlGetter;
    commonEditPage.setMainArtifact(args.artifact);
    commonEditPage.commonSaveButtonsId = typeof(args.toolbarId) != 'undefined' ? args.toolbarId : null;
    //if (browserContext.isEditModeEnabled() && artifactManager.hasWriteRight(commonEditPage.mainArtifact)) {
    if (commonEditPage.hasEditToolbar) {
        artifactManager.addModificationListener(dojo.hitch(commonEditPage, 'onArtifactModification'));
        if (!commonEditPage.commonSaveButtonsId) { commonEditPage.commonSaveButtonsId = 'CommonEditPageToolbar'; } 
        pageContext.addOnLoad(function() {
            var toolbar = document.getElementById(commonEditPage.commonSaveButtonsId);
            toolbar.innerHTML = getHtmlCommonSaveButtons(toolbarButtons);
            dojo.parser.parse(toolbar);
        });
    }
    html += '<div id="CommonEditPageDiv" class="common-edit-page-div">'+commonEditPage.htmlGetter()+'</div>';
    pageContext.addOnUnload(dojo.hitch(commonEditPage, 'onPageUnload'));
    return html;
}

function DateControl(id, artifact, attribute, nestedHtmlGetter) {
    this.id = id;
    this.artifact = artifact;
    this.getter = 'get'+firstCharToUpperCase(attribute);
    this.setter = 'set'+firstCharToUpperCase(attribute);
    this.nestedHtmlGetter = nestedHtmlGetter;
    
    this.getAttributeValue = function() {
        var date = this.artifact[this.getter]();
        return date ? date : new Date();
    };
    this.getDateTime = function() {
        var date = this.getAttributeValue();
        return this.getDate(date)+' - '+this.getTime(date);
    };
    this.getDate = function(date) { 
        if (!date) { date = this.getAttributeValue(); }
        return dojo.date.locale.format(date, {formatLength:'full',selector:'date'}); 
    };
    this.getTime = function(date) { 
        if (!date) { date = this.getAttributeValue(); }
        return dojo.date.locale.format(date, {formatLength:'full',selector:'time'}); 
    };
    this.getHtml = function() {
        return '<span id="DateControl-'+this.id+'">'+getHtmlDateControl(this, this.nestedHtmlGetter)+'</span>';
    };
    this.getHtmlContextMenu = function(isDate) {
        var method = isDate ? 'onOpenDatePicker' : 'onOpenTimePicker',
            text = isDate ? 'date' : 'time';
        return '<a id="DialoagControlPicker-'+this.id+'-'+text+'" '+
            'onMouseOver="dojo.addClass(this.parentNode, \'context-menu-hover\')" '+
            'onMouseOut="dojo.removeClass(this.parentNode, \'context-menu-hover\')" '+
            'onclick="DateControls.get('+this.id+').'+method+'()" '+
            'class="context-menu-handle" title="Click to edit the '+text+'">&nabla;</a>';
    };
    this.setDate = function(date) { 
        var d = new Date(this.getAttributeValue().getTime());
        d.setFullYear(date.getFullYear());
        d.setMonth(date.getMonth());
        d.setDate(date.getDate());
        this.artifact[this.setter](d);
        this.closePopup(); 
    }
    this.setTime = function(date) { 
        var d = new Date(this.getAttributeValue().getTime());
        d.setHours(date.getHours());
        d.setMinutes(date.getMinutes());
        d.setSeconds(date.getSeconds());
        d.setMilliseconds(date.getMilliseconds());
        this.artifact[this.setter](d);
        this.closePopup(); 
    }
    this.closePopup = function() {
        var widget = dojo.widget.byId('DateControlPickerPopup');
        
        document.getElementById('DateControl-'+this.id).innerHTML = this.getHtml();
        widget.close();
        dojo.widget.byId('DateControlPicker').destroy();
    }
    this.onOpenDatePicker = function() { 
        var oldWidget = dijit.byId('DateControlPicker');
        if (oldWidget) { oldWidget.destroy(); }
        var date = this.getAttributeValue(),
            dp = new dijit._Calendar('DatePicker', {id:'DateControlPicker', value: date, langX:'de'});
        dojo.connect(dp, 'onValueChanged', this, 'setDate');
        this.createPicker('date', dp);
    };
    this.onOpenTimePicker = function() { 
        var oldWidget = dojo.widget.byId('DateControlPicker');
        if (oldWidget) { oldWidget.destroy(); }
        var date = this.getAttributeValue(),
            value = dojo.date.format(date, {timePattern:'HH:mm:ss',selector:'timeOnly'});
            dateControl = this,
            dp = new dijit.form.DateTextBox('TimeTextbox', {id:'DateControlPicker', value:value, displayFormat: 'HH:mm:ss'});
        dojo.connect(dp.domNode, 'onkeypress', function(event) {
            var keyCode;
            if (!event) event = window.event;
            if (event.keyCode) keyCode = event.keyCode;
            else if (event.which) keyCode = event.which;
            if (keyCode == 13) {
                var value = dp.isValid();
                if (value != null) {          
                    dateControl.setTime(dp.isValid());
                }
            }
        });
        this.createPicker('time', dp);
    };
    this.createPicker = function(type, pickerWidget) {
        var pickerPopup = dojo.widget.byId('DateControlPickerPopup');
        if (pickerPopup == null) {
            var element = document.createElement('DateControlPickerDiv');
            document.documentElement.appendChild(element);
            element.style.position = 'absolute';
            pickerPopup = dojo.widget.createWidget('PopupContainer', {id:'DateControlPickerPopup'}, element);
        }
        pickerPopup.domNode.appendChild(pickerWidget.domNode);
        var target = document.getElementById('DialoagControlPicker-'+this.id+'-'+type),
            pos = dojo.html.getAbsolutePosition(target, false),
            scroll = dojo.html.getScroll(),
            height = dojo.html.getBorderBox(target).height;
        pickerPopup.open(pos.x+scroll.left, pos.y+scroll.top+height, target, {domNode:null});
    }
};
var DateControls = {
    instances: [],
    createInstance: function(artifact, attribute, nestedHtmlGetter) {
        var id = this.instances.length,
            instance = new DateControl(id, artifact, attribute, nestedHtmlGetter);
        this.instances.push(instance);
        return instance;
    },
    get: function(id) { return this.instances[id]; }
}

function tagDateControl(args, nestedHtmlGetter) {
    var artifact = args.artifact,
        attribute = args.attribute ? args.attribute : 'date',
        editable = args.editable ? args.editable === true || args.editable == 'true' : true;
    if (browserContext.isEditModeEnabled() && editable) {
        return DateControls.createInstance(artifact, attribute, nestedHtmlGetter).getHtml();
    } else {
        return DateControls.createInstance(artifact, attribute).getDateTime()+nestedHtmlGetter();
    }
}


/*global-block-end*/
/*function-begin (getHeadHtml11) */
function getHeadHtml11() {
    var html = '';
    html += '\n\n\n\<link rel=\"shortcut icon\" href=\"';
    var scriptlet = barrique.contextPath; if (scriptlet != null) html += scriptlet;
    html += '\/pages\/';
    scriptlet = barrique.buildNumber; if (scriptlet != null) html += scriptlet;
    html += '\/favicon.png\"\>\n\n';
    return html;
}
/*function-end (getHeadHtml11) */
/*function-begin (getBodyHtml11) */
function getBodyHtml11() {
    var html = '';
    html += '\n\n';
    html += '\n\n';
    html += '\n\n';
    html += '\n';
    html += '\n\n';
    html += '\n\n';
    html += '\n\n\n';
    return html;
}
/*function-end (getBodyHtml11) */
/*function-begin (getHtmlCommonHeader) */
function getHtmlCommonHeader(nestedHtmlGetter) {
    var html = '';
    html += '\n    ';

        var breadCrumbingPath = pageContext.getAttribute('breadCrumbingPath');
        if (breadCrumbingPath == null) {
            breadCrumbingArtifact = artifactManager.getMainArtifact();
            if (breadCrumbingArtifact != null) {
                breadCrumbingPath = breadCrumbingArtifact.getRelationPath();
            }
        }
        html += '\n    ';
    if (breadCrumbingPath != null) { 
    html += '\n        \<div id=\"CommonHeaderBreadCrumbingDiv\" class=\"header-bread-crumbing-div glossy  ';
    var scriptlet = commonEditPage.hasEditToolbar?'editmode-top':''; if (scriptlet != null) html += scriptlet;
    html += '\"\>\n            ';
    scriptlet = getHtmlBreadCrumbingSegments(breadCrumbingPath); if (scriptlet != null) html += scriptlet;
    html += '\n        \<\/div\>\n    ';
    }
    html += '\n\n    ';
    if (commonEditPage.hasEditToolbar) { 
    html += '    \n      \<div class=\"common-save-buttons\"\>\<div id=\"CommonEditPageToolbar\"\>\<\/div\>\<div class=\"common-save-buttons-info\"\>Edit Mode Active\<\/div\>\<\/div\>\n      \<div class=\"';
    scriptlet = commonEditPage.hasEditToolbar ? 'editmode-gap' : ''; if (scriptlet != null) html += scriptlet;
    html += '\"\>\<\/div\>\n    ';
    }
    html += '\n\n    \<div id=\"CommonHeaderDiv\" class=\"header-div ';
    scriptlet = commonEditPage.hasEditToolbar?'editmode-top':''; if (scriptlet != null) html += scriptlet;
    html += '\"\>\n        \<div id=\"BackgroundChannelAsyncIndicator\" class=\"background-channel-async-off\"\>\<img src=\"';
    scriptlet = barrique.contextPath; if (scriptlet != null) html += scriptlet;
    html += '\/pages\/';
    scriptlet = barrique.buildNumber; if (scriptlet != null) html += scriptlet;
    html += '\/barrique\/base\/images\/async-indicator.gif\"\>\<\/div\>\n        &nbsp;\n        ';

            var actions = commonHeader.getActions();
            html += '<span class="glossy">';
            for (var ai = actions.length-1; ai >= 0; ai--) {
                if (ai != (actions.length-1)) html += ' | ';
                html += '<a id="Header-Link-'+ai+'" onmouseover="onMouseOverHeaderLink('+ai+')" onclick="onClickHeaderLink('+ai+')" href=\"javascript:commonHeader.execute(\''+actions[ai]+'\')\">'+actions[ai]+'</a>';
                if (commonHeader.appendixMap[actions[ai]]) {
                    html += commonHeader.appendixMap[actions[ai]];
                }
            }
            html += '</span>';
            if (nestedHtmlGetter != null) { html += nestedHtmlGetter(); }
            html += '\n    \<\/div\>\n    \n    \<div dojoType=\"dojox.widget.Toaster\" id=\"';
    scriptlet = pageContext.addDojoWidget('CommonHeaderToaster', true); if (scriptlet != null) html += scriptlet;
    html += '\" messageTopic=\"commonHeaderMessageTopic\"\>\<\/div\>\n    \n    \<div id=\"BackgroundChannelProgressInfo\" class=\"background-channel-progress-info nodisplay\"\>\n        \<table\>\<tr\>\n            \<td id=\"BackgroundChannelInfoText\"\>\<\/td\>\n            \<td class=\"background-channel-progress-info-throbber\"\>\<img src=\"';
    scriptlet = barrique.contextPath; if (scriptlet != null) html += scriptlet;
    html += '\/pages\/';
    scriptlet = barrique.buildNumber; if (scriptlet != null) html += scriptlet;
    html += '\/barrique\/base\/images\/server-processing.gif\" width=\"32\" height=\"32\"\>\<\/td\>\n        \<\/tr\>\<\/table\>\n    \<\/div\>\n';
    return html;
}
/*function-end (getHtmlCommonHeader) */
/*function-begin (getHtmlCommonSaveButtons) */
function getHtmlCommonSaveButtons(additionalButtonList) {
    var html = '';
    html += '\n    \<table id=\"CommonSaveButtonsToolbar\"\>\n    \n    \<td id=\"CommonEditButtonEdit\" style=\"display:none;\"\>\n        ';
    var tagargs0 = new Object();
    tagargs0['onclick'] = 'commonEditPage.disablePreview()';
    tagargs0['id'] = 'CommonSaveButtonEdit';
    tagargs0['name'] = 'actions\/edit';
    tagargs0['size'] = '16';
    html += tagIconButton(tagargs0, function() {
    var html = '';
    html += 'Close Preview';
    return html;
}
    );
    html += '\n    \<\/td\>\n    \<td id=\"CommonEditButtonPreview\"\>\n        ';
    var tagargs1 = new Object();
    tagargs1['onclick'] = 'commonEditPage.enablePreview()';
    tagargs1['id'] = 'CommonSaveButtonPreview';
    tagargs1['name'] = 'mimetypes\/html';
    tagargs1['size'] = '16';
    html += tagIconButton(tagargs1, function() {
    var html = '';
    html += 'Preview';
    return html;
}
    );
    html += '\n    \<\/td\>\n    ';
    if (artifactManager.isOwner(commonEditPage.mainArtifact)) { 
    html += '\n    \<td id=\"CommonEditButtonPublish\"\>\n        ';
    var tagargs2 = new Object();
    tagargs2['onclick'] = 'commonEditPage.publish()';
    tagargs2['id'] = 'CommonSaveButtonPublish';
    tagargs2['name'] = 'actions\/news_subscribe';
    tagargs2['size'] = '16';
    html += tagIconButton(tagargs2, function() {
    var html = '';
    html += 'Publish';
    return html;
}
    );
    html += '\n    \<\/td\>\n    ';
    }
    html += '\n    \<td id=\"CommonEditButtonSave\" style=\"display:none;\"\>\n        ';
    var tagargs3 = new Object();
    tagargs3['onclick'] = 'commonEditPage.save()';
    tagargs3['id'] = 'CommonSaveButtonSave';
    tagargs3['name'] = 'actions\/filesave';
    tagargs3['size'] = '16';
    html += tagIconButton(tagargs3, function() {
    var html = '';
    html += 'Save';
    return html;
}
    );
    html += '\n    \<\/td\>\n    ';
    var list4 = additionalButtonList;
    var len4 = list4.length;
    for (var i4 = 0; i4 < len4; i4++) {
        var buttonHtml = list4[i4];
    html += '\n      \<td\>';
    var scriptlet = buttonHtml(); if (scriptlet != null) html += scriptlet;
    html += '\<\/td\>\n    ';
    }
    html += ' \n    \<\/TR\>\<\/table\>\n';
    return html;
}
/*function-end (getHtmlCommonSaveButtons) */
/*function-begin (getHtmlProgressInformation) */
function getHtmlProgressInformation(message, percent) {
    var html = '';
    html += '\n    ';
    var scriptlet = message; if (scriptlet != null) html += scriptlet;
    html += ' - \<span style=\"padding-right:';
    scriptlet = 100-percent; if (scriptlet != null) html += scriptlet;
    html += 'px;height:0.5em;position:relative;border:1px solid white;\"\>\<span style=\"background:white;padding-right:';
    scriptlet = percent; if (scriptlet != null) html += scriptlet;
    html += 'px;height:0.5em;\"\>\<\/span\>\<\/span\>\<br\>\n';
    return html;
}
/*function-end (getHtmlProgressInformation) */
/*function-begin (getHtmlDefaultProgressInformation) */
function getHtmlDefaultProgressInformation() {
    var html = '';
    html += '\<i\>Working...\<\/i\>';
    return html;
}
/*function-end (getHtmlDefaultProgressInformation) */
/*function-begin (getHtmlDateControl) */
function getHtmlDateControl(dateControl, nestedHtmlGetter) {
    var html = '';
    html += '\n    ';
    if (browserContext.isEditable()) { 
    html += '\n        \<span class=\"context-menu\"\>';
    var scriptlet = dateControl.getDate(); if (scriptlet != null) html += scriptlet;
    html += '';
    scriptlet = dateControl.getHtmlContextMenu(true); if (scriptlet != null) html += scriptlet;
    html += '\<\/span\> - \n        \<span class=\"context-menu\"\>';
    scriptlet = dateControl.getTime(); if (scriptlet != null) html += scriptlet;
    html += '';
    scriptlet = dateControl.getHtmlContextMenu(false); if (scriptlet != null) html += scriptlet;
    html += '\<\/span\>\n    ';
    } else { 
    html += '\n        ';
    scriptlet = dateControl.getDateTime(); if (scriptlet != null) html += scriptlet;
    html += '\n    ';
    }
    html += '\n    ';
    scriptlet = nestedHtmlGetter(); if (scriptlet != null) html += scriptlet;
    html += '\n';
    return html;
}
/*function-end (getHtmlDateControl) */
/*function-begin (getHtmlCommonFooter) */
function getHtmlCommonFooter(artifacts, nestedHtmlGetter) {
    var html = '';
    html += '\n    \<table id=\"CommonFooterTable\" class=\"footer-div\" style=\"width:100%;\"\>\n        \<tr\>\n            \<td style=\"text-align:left;\" class=\"glossy\"\>\n            ';
    if (artifacts != null) { 
    html += '\n                ';
    var list5 = artifacts;
    var len5 = list5.length;
    for (var i5 = 0; i5 < len5; i5++) {
        var artifact = list5[i5];
    html += '\n                    ';

                        var url = artifact.getHref(),
                            icon = artifact.getIcon ? artifact.getIcon() : null,
                            mimeType = icon ? icon.getMimeType() : null;

                        if (icon) { 
                            if (!url) { url = artifact.getUrl ?  artifact.getUrl() : null; }
                            
                            html += '<a href="'+url+'"';
                            if (barrique.isinstanceof(artifact, 'barrique.module.tag.license.LicenseTag')) {
                                html += ' rel="license"';
                            }
                            html += '>'; 
                            
                            if (mimeType != null && mimeType.match(/^image\/.*/)) {
                                html += '<img src="'+icon.getUrl('icon')+'" class="footer-icon">';
                            } else if (typeof(artifact.getTitle) != 'undefined') {
                                html += artifact.getTitle();
                            }
                            html += '</a>';
                        }
                        html += '\n                ';
    }
    html += '\n            ';
    }
    html += '\n            \<\/td\>\n            \<td style=\"text-align:center;\"\>&nbsp;\<\/td\>\n            \<td style=\"text-align:right;\" class=\"glossy\"\>\n                ';
    var scriptlet = nestedHtmlGetter(); if (scriptlet != null) html += scriptlet;
    html += '\n                \<a href=\"http:\/\/barrique.corvusalbus.com\/\" target=\"_blank\" title=\"Download the source code for this web application.\"\>\<img src=\"';
    scriptlet = barrique.contextPath; if (scriptlet != null) html += scriptlet;
    html += '\/pages\/';
    scriptlet = barrique.buildNumber; if (scriptlet != null) html += scriptlet;
    html += '\/favicon.png\"\>\<\/a\>\n            \<\/td\>\n        \<\/tr\>\n    \<\/table\>\n';
    return html;
}
/*function-end (getHtmlCommonFooter) */
