/*global-block-begin*/


var titlePaneCtrlCounter = 0,
    multiColumnCtrlCounter = 0,
    columnCtrlCounter = 0;

titlePaneCtrlManager = {
    panes: [],
    add: function(id, htmlGetter, collapsed) {
        this.panes.push({id:id, htmlGetter:htmlGetter, lazy:collapsed});
    },
    collapse: function(id) {
        var body = document.getElementById('title-pane-body-'+id);
        if (body) {
            body.style.display = 'none';
            document.getElementById('title-pane-collapse-icon-'+id).innerHTML = 
            	getHtmlTitlePaneCollapseIcon(id, true);
        }
    },
    expand: function(id) {
        var body = document.getElementById('title-pane-body-'+id);
        if (body) {
	        for (var i = 0; i < this.panes.length; i++) {
	            if (this.panes[i].id == id) {
		            if (this.panes[i].lazy) {
		                body.innerHTML = this.panes[i].htmlGetter();
		                this.panes[i].lazy = false;
		            }
		            body.style.display = 'block'; 
		            break;
	            }
	        }
            document.getElementById('title-pane-collapse-icon-'+id).innerHTML = 
                getHtmlTitlePaneCollapseIcon(id, false);
        }
    }
}

function getHtmlTitlePaneCollapseIcon(id, collapsed) {
    if (collapsed) {
        return '<img src="'+barrique.base.getIconHref('actions/2downarrow', 16)+
            '" title="Click to expand this box" onclick="titlePaneCtrlManager.expand(\''+id+'\')">';
    } else {
        return '<img src="'+barrique.base.getIconHref('actions/2uparrow', 16)+
            '" title="Click to collapse this box" onclick="titlePaneCtrlManager.collapse(\''+id+'\')">';
    }
}

function tagTitlePaneCtrl(args, nestedHtmlGetter) {
    var collapsed = args.collapsed ? true : false,
        hideCollapse = args.hideCollapse ? true : false,
        nestedHtml = collapsed ? '' : nestedHtmlGetter();
    var html = '',
        id = typeof(args.id) != 'undefined' ? args.id : 'TitlePaneCtrl'+(titlePaneCtrlCounter++),
        title = pageContext.setAttribute('TitleCtrl', null);

    if (!title) { title = typeof(args.title) != 'undefined' ? args.title : null; }
    html += '<div class="title-pane-ctrl-container" id="'+id+'">';
    if (title) { 
        html += '<div class="title-pane-ctrl-head"><table><tr><td width="100%">'+title+
            '</td>';
        if (!hideCollapse) {
            html += '<td><span id="title-pane-collapse-icon-'+id+
                    '" style="text-align:right;cursor:pointer;vertical-align:middle">'+
                    getHtmlTitlePaneCollapseIcon(id, collapsed)+'</span></td>';
        }
        html += '</tr></table></div>'; 
    }
    html += '<div class="title-pane-ctrl-body" style="display:'+(collapsed?'none':'block')+
            '" id="title-pane-body-'+id+'">';
    if (!collapsed) {  html += nestedHtml; }
    html += '</div></div>';
    titlePaneCtrlManager.add(id, nestedHtmlGetter, collapsed);
    return html;
}
function tagTitleCtrl(args, nestedHtmlGetter) {
    pageContext.setAttribute('TitleCtrl', nestedHtmlGetter());
    return '';
}

function tagMultiColumnCtrl(args, nestedHtmlGetter) {
    var html = '',
        id = typeof args.id != 'undefined' ? args.id : 'MultiColumnCtrl'+(multiColumnCtrlCounter++);
    html += '<div class="multi-column-ctrl" id="'+id+'">'+nestedHtmlGetter()+'</div>';
    html += '<div class="columns-ctrl-cleaner"></div>';
    return html;
}

function tagColumnCtrl(args, nestedHtmlGetter) {
    var html = '',
        id = typeof args.id != 'undefined' ? args.id : 'ColumnCtrl'+(columnCtrlCounter++);
    html += '<div class="column-ctrl-'+args.position+'" id="'+id+'"><div class="column-ctrl-content">'+nestedHtmlGetter()+'</div></div>';
    return html;
}

var filledElements = {
    buffer: {},
    add: function(id, html) {
        if (typeof(this.buffer[id]) != 'undefined') {
            this.buffer[id] = this.buffer[id]+html;
        } else {
            this.buffer[id] = html;
        }
    },
    onLoad: function() {
        for (id in this.buffer) {
            var html = this.buffer[id],
                element = document.getElementById(id);
            element.innerHTML = element.innerHTML+html;
            delete this.buffer[id];
        }
    }
}
pageContext.addOnLoad(function() {filledElements.onLoad();});

function tagAddElementHtml(args, nestedHtmlGetter) {
    var id = args.id,
        html = nestedHtmlGetter();
    filledElements.add(id, html);
    return '';
}

var sourceRelationAttributeStubs = [];
function SourceRelationAttributeStub(artifact, attribute, title, relationJavaClass, sourceJavaClass, sourceAttribute) {
    this.artifact = artifact;
    this.attribute = attribute;
    this.title = title;
    this.relationJavaClass = relationJavaClass;
    this.sourceJavaClass = sourceJavaClass;
    this.sourceAttribute = sourceAttribute;
    this.id = sourceRelationAttributeStubs.length;
    this.relations = eval('artifact.get'+firstCharToUpperCase(attribute)+'()');
    
    sourceRelationAttributeStubs.push(this);
    
    this.getSourceRelations = function() { return this.relations; };
    this.updateContainer = function() {
        document.getElementById('SourceRelationTitleContainerContent-'+this.id).innerHTML = 
            getHtmlSourceRelationTitleContainerContent(this);
    };
    this.prepareTarget = function(target) {
        var stub = this;
        target.onContextMenuSraTarget =  function(context, menu) {
            if (browserContext.isEditable()) {
                menu.addEntry('Category', dojo.hitch(stub, 'addSourceRelation'), 'Add', 'filesystems/folder');
            }
        }
    };
	this.addSourceRelation = function() {
        var skipArtifacts = '';
        for (var i = 0; i < this.relations.length; i++) {
            if (i > 0) { skipArtifacts += ' '; }
            skipArtifacts += this.relations[i].getSource().getArtifactId();
        }
        windowManager.openModalWindow(barrique.contextPath+'/sx/ArtifactHtmlPage?class=barrique.base.artifact.Artifact'+
            '&view=search-artifact-dialog&artifactClass='+this.sourceJavaClass+
            '&callback=sourceRelationAttributeStubs['+this.id+'].onSearchHit'+
            '&skipArtifacts='+encodeURIComponent(skipArtifacts)+
            '&right=LINK', 'SelectArtifactDialog');
    };
    this.prepareSource = function(relation) {
        var source = relation.getSource(),
            stub = this;
        source.onContextMenuSraSource =  function(context, menu) {
            if (browserContext.isEditable() && artifactManager.hasWriteRight(source)) {
                menu.addEntry('Remove from '+stub.title, function() { stub.removeSourceRelation(source); }, null, 'actions/editdelete');
            }
        }
    };
    this.removeSourceRelation = function(source) {
        for (var i = 0; i < this.relations.length; i++) {
            var relation = this.relations[i];
            if (relation.getSource() == source) {
                eval('source.removeFrom'+firstCharToUpperCase(this.sourceAttribute)+'(relation)');
                this.relations = barrique.array.remove(this.relations, relation);
                this.updateContainer();
                if (commonEditPage.isManaged(relation.getTarget())) {
                    commonEditPage.addArtifact(source);
                }
                break;
            }
        }
    };
    this.onSearchHit = function(artifactId) {
        if (artifactId == null) { return; }
        serverManager.loadArtifact(artifactId, null, new AsyncRequestCallback(dojo.hitch(this, 'onSearchHitLoaded'), dojo.hitch(this, 'onSearchHitLoadedError')), 'barrique.base.artifact.compound.EmptyCompound');
    };
    this.onSearchHitLoaded = function(source) {
        var shortName = null;
        for (var i = 0; i < this.relations.length; i++) {
            var name = this.relations[i].getName();
            if (name != null && name.length > 0) { shortName = name; break; }
        }
        var relation = eval('new '+this.relationJavaClass+'()');
        relation.setTarget(this.artifact);
        relation.setSource(source);
        if (shortName) { relation.setName(shortName); }
        var sourceHref = source.getHref();
        if (source != null) { commonEditPage.setOnSaveLocation(sourceHref); }
        this.prepareSource(relation);
        eval('source.addTo'+firstCharToUpperCase(this.sourceAttribute)+'(relation)');
        this.relations.push(relation);
        this.updateContainer();
    };
    this.onSearchHitLoadedError = function(exceptions) {
        console.debug(exceptions);
        commonHeader.displayError('Cannot load category');
    };
    this.init = function() {
        this.prepareTarget(this.artifact);
        barrique.array.each(this.relations, dojo.hitch(this, 'prepareSource'));
    }
    this.init();
}

function tagSourceRelationAttributeTitlePane(args, nestedHtmlGetter) {
    var stub = new SourceRelationAttributeStub(args.artifact, args.attribute, args.title, 
            args.relationJavaClass, args.sourceJavaClass, args.sourceAttribute);
    return getHtmlSourceRelationTitleContainer(stub);
}

function DivCache() {
    barrique.divCacheCount = typeof(barrique.divCacheCount) != 'undefined' ?  barrique.divCacheCount+1 : 0;
    this.id = barrique.divCacheCount;
    this.slots = {};
    this.entries = {};
    this.bodyElement = null;
    
    this.getSlotContainerId = function(slotId) {
        this.slots[slotId] = {entryId:null};
        return 'DivCache-'+this.id+'-'+slotId;
    };
    this.getEntryId = function(slotId) {
        return this.slots[slotId].entryId;
    };
    this.add = function(entryId, htmlGetter, entryListener) {
        if (this.bodyElement == null) { this.bodyElement = document.getElementsByTagName("body")[0]; }
        var element = document.createElement('div');
        element.style.display = 'none';
        this.bodyElement.appendChild(element);
        this.entries[entryId] = { htmlGetter:htmlGetter, element:element, isCached:false, slotId:null, entryListener:entryListener };
    };
    this.getHtmlSlot = function(slotId, entryId) {
        var entry = this.entries[entryId];
        this.slots[slotId].entryId = entryId;
        entry.slotId = slotId;
        var html = entry.isCached ? entry.element.innerHTML : entry.htmlGetter.call(); 
        entry.isCached = true;
        return html;
    };
    this.updateSlot = function(slotId, entryId) {
        if (entryId != null) {
            for (var x in this.slots) {
                if (x != slotId && this.slots[x].entryId == entryId) { 
                    this.updateSlot(x, null); 
                }
            }
        }
        
        var slot = this.slots[slotId],
            oldEntryId = slot.entryId;
        //console.debug('Update slot', slotId, 'was', oldEntryId, 'now', entryId);
        if (oldEntryId == entryId) { return; }
        if (oldEntryId != null) { 
            if (this.entries[slot.entryId].entryListener) { this.entries[slot.entryId].entryListener.onHide(this.getSlotElement(slotId), oldEntryId, entryId); }
            this.moveEntry(slotId, true); 
        }
        slot.entryId = entryId;
        if (entryId == null) { return; }
        var entry = this.entries[entryId];
        //console.debug('Update slot, cached:', entry.isCached);
        if (!entry.isCached) {
            var slotElement = this.getSlotElement(slotId);
            slotElement.innerHTML = entry.htmlGetter.call();
            entry.isCached = true;
            entry.slotId = slotId;
        } else {
            this.moveEntry(slotId, false);
        }
        if (entry.entryListener) { entry.entryListener.onShow(this.getSlotElement(slotId), entryId, oldEntryId); }
    };
    this.moveEntry = function(slotId, intoCache) {
        var slot = this.slots[slotId],
            slotElement = this.getSlotElement(slotId),
            entry = this.entries[slot.entryId],
            entryElement = entry.element,
            fromElement = intoCache ? slotElement : entryElement,
            toElement = intoCache ? entryElement : slotElement,
            childNodes = fromElement.childNodes;
        entry.slotId = intoCache ? null : slotId;
        while (toElement.firstChild) { toElement.removeChild(toElement.firstChild); }
        while (fromElement.firstChild) { toElement.appendChild(fromElement.firstChild); }
    };
    this.getSlotElement = function(slotId) { return document.getElementById('DivCache-'+this.id+'-'+slotId); };
    this.invalidate = function(entryId) {
        for (var x in this.entries) {
            if (!entryId || x == entryId) {
                var entry = this.entries[x];
                if (entry.isCached && entry.slotId == null) { 
                    entry.isCached = false; 
                    while (entry.element.firstChild) { entry.element.removeChild(entry.element.firstChild); }
                }
            }
        }
    }
    this.forceCached = function(entryId) {
        for (var cachedEntryId in this.entries) {
            if (!entryId || cachedEntryId == entryId) {
                var entry = this.entries[cachedEntryId];
                if (!entry.isCached && entry.slotId == null) { 
                    entry.isCached = true; 
                    entry.element.innerHTML = entry.htmlGetter.call();
                }
            }
        }
    }
}



/*global-block-end*/
/*function-begin (getHeadHtmlv) */
function getHeadHtmlv() {
    var html = '';
    html += '\n\n\n';
    return html;
}
/*function-end (getHeadHtmlv) */
/*function-begin (getBodyHtmlv) */
function getBodyHtmlv() {
    var html = '';
    html += '\n    \n';
    html += '\n';
    html += '\n\n    \n';
    return html;
}
/*function-end (getBodyHtmlv) */
/*function-begin (getHtmlSourceRelationTitleContainer) */
function getHtmlSourceRelationTitleContainer(stub) {
    var html = '';
    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'] = stub.artifact;
    tagargs2['aspect'] = 'SraTarget';
    html += tagContextMenu(tagargs2, function() {
    var html = '';
    html += '';
    var scriptlet = stub.title; if (scriptlet != null) html += scriptlet;
    html += '';
    return html;
}
    );
    return html;
}
    );
    html += '\n        \<div id=\"SourceRelationTitleContainerContent-';
    var scriptlet = stub.id; if (scriptlet != null) html += scriptlet;
    html += '\"\>\n            ';
    scriptlet = getHtmlSourceRelationTitleContainerContent(stub); if (scriptlet != null) html += scriptlet;
    html += '\n        \<\/div\>\n    ';
    return html;
}
    );
    html += '\n';
    return html;
}
/*function-end (getHtmlSourceRelationTitleContainer) */
/*function-begin (getHtmlSourceRelationTitleContainerContent) */
function getHtmlSourceRelationTitleContainerContent(stub) {
    var html = '';
    html += '\n    ';
    var list3 = stub.getSourceRelations();
    var len3 = list3.length;
    for (var i3 = 0; i3 < len3; i3++) {
        var relation = list3[i3];
    html += '\n        \<div\>\n            ';
    var tagargs4 = new Object();
    tagargs4['artifact'] = relation.getSource();
    tagargs4['context'] = new ContextInfo(stub.artifact);
    tagargs4['aspect'] = 'SraSource';
    html += tagContextMenu(tagargs4, function() {
    var html = '';
    html += '\<a href=\"';
    var scriptlet = relation.getSource().getHref(); if (scriptlet != null) html += scriptlet;
    html += '\" title=\"';
    scriptlet = relation.getSource().getDescription ? relation.getSource().getDescription() : relation.getSource().getTitle(); if (scriptlet != null) html += scriptlet;
    html += '\"\>';

                    if (relation.getSource().getIcon) {
                        var icon = relation.getSource().getIcon();
                        if (icon) {
                            html += '<img src="'+icon.getUrl()+'" width="16" height="16" style="vertical-align:middle;margin-right:2px;"/>';
                        }
                    }
                    html += '';
    scriptlet = relation.getSource().getTitle(); if (scriptlet != null) html += scriptlet;
    html += '\<\/a\>';
    return html;
}
    );
    html += '\n        \<\/div\>\n    ';
    }
    html += '\n';
    return html;
}
/*function-end (getHtmlSourceRelationTitleContainerContent) */
