﻿/// <reference name="prototype.js"/>     
/// <reference name="CMS.js"/>     
/// <reference name="CMSEditArea.js"/>     
/// <reference name="VDSToolkit.js"/>     

/* ------------------------------------------------------------------------
 * AuthorArea inherits from EditArea
 * ------------------------------------------------------------------------ */        
var AuthorArea = Class.create(EditArea,
{
    ConfigureActionBar: function(editActionText)
    {
        var actionBar = new ActionBar(this.mEditActions, editActionText, false, "");
    },
        
    ExtractAuthor: function()
    {
        this.mCreatedMessage = 'by ';
        var message = this.mTag.innerHTML;
        this.mAuthor = message.substring(message.indexOf(this.mCreatedMessage) + 3);
        this.mMessage = message.substring(0, message.length - this.mAuthor.length);
    },
    
    GetAuthor: function()
    {
        this.ExtractAuthor();
        return this.mAuthor;
    },
    
    BeginEditingInput: function()
    {                
        this.ExtractAuthor();        
        this.AddInputDiv();
        this.mActionsInput.value = this.mAuthor;
        this.mActionsInput.activate();        
    },
    
    ConfirmEditingInput: function()
    {
        this.mTag.innerHTML = this.mMessage + this.mActionsInput.value;
        this.EditingComplete();              
		this.mTag.show();			
    }    
    
});
    
/* ------------------------------------------------------------------------
* SharedResourcesEditArea inherits from ResourcesEditArea
* ------------------------------------------------------------------------ */
var SharedResourcesEditArea = Class.create(ResourcesEditArea,
    {

        BeginEditingResources: function() {
            this.BeginEditingEditor();
        },

        BeginEditingEditor: function() {
            this.mActions.setStyle({
                width: this.mTag.getWidth()
            });

            var handler = this["HandlerForResourceAssigned"].bind(this);

            if (this.mEditingLink) {

                window.VDS$CSPage.HandlerForOpenLinkManager(null, handler);
            }
            else if (this.mEditingDocument)
            {
                var link = document.createElement("a");
                var arguments = { get_value: function() { return link; }, CssClasses: [] };

                this.GetActionsAndInputContainer().control.open('FileManager', arguments, handler);
            }
            else {
                var radWindow = RadWindow();
                radWindow.control.show();
            }

            this.mTag.show();
        },

        ConfigureLinkActionBar: function() {
            var actionBar = new LinkActionBar(this.mEditActions, "", false);
        },

        ConfigureResourceActionBar: function() {
            var actionBar = new ResourceActionBar(this.mEditActions, "", false);
        },

        ConfigureResourceLinkActionBar: function() {
            var actionBar = new ResourceLinkActionBar(this.mEditActions, "", false);
        },

        GetEmptyElementClassName: function() {
            return 'emptyResource';
        },

        GetActionsAndInputContainer: function() {
            return RadResourceEditorManager();
        },

        HandlerForActionsTarget: function(event) {
            if (event.target.hasClassName('cancelLnk'))
                this.CancelEditing();
            else if (event.target.hasClassName('commitLnk'))
                this.ConfirmEditing(event);
            else if (event.target.hasClassName('actionsTarget')) {
                this.mEditingLink = event.target.hasClassName('addLink');
                this.mEditingDocument = event.target.hasClassName('addDocument');
                this.BeginEditing();
            }
        },

        HandlerForResourceSelected: function(radWindow, returnValue) {
            this.EditSection().SaveResource(returnValue);
            this.mTag.show();
            this.EditingComplete();
        },

        HandlerForResourceAssigned: function(sender, args) {
            if (this.mEditingLink) {
                this.EditSection().SaveLink(args);
                this.mTag.show();
                this.EditingComplete();
            }
            else if (this.mEditingDocument) {
                if (args.value.title.length > 0) {
                    this.EditSection().SaveDocument(args);
                    this.mTag.show();
                    this.EditingComplete();
                }
                else {
                    alert("Please enter a document title in the Tooltip field");
                    this.BeginEditingEditor();
                }
            }
        },

        SetEmptyTags: function() {
            if (this.mTag.innerHTML == '') {
                if (this.mTag.id.include('Full'))
                    this.mTag.addClassName('emptyFullCopy');
                else
                    this.mTag.addClassName('emptyCopy');
            }
        }
    });


/* ------------------------------------------------------------------------ 
 * PermissionsSection represents an inherited EditSection
 * ------------------------------------------------------------------------ */        
var PermissionsSection = Class.create(EditSection,
    {
        initialize: function(chkList) 
		{
		    this.mChkListCtl = chkList;
		    this.mSection = $(this.mChkListCtl).up('div.section');
		    this.mSaveBtn = this.mSection.down('a.saveSection');	
		    this.mIsDirty = false;
		    
		    this.BindHandlers();
        },
        
        BindHandlers: function()
        {           
		    this.mSaveBtn.observe('click', this["HandlerForSaveClicked"].bind(this));	
		    $(this.mChkListCtl).observe('click', this["HandlerForEditStarted"].bind(this));	
        },
                
        HandlerForEditStarted: function(event)
        {   
            if (!window.VDS$CSPage.IsNew())
                window.VDS$PermissionsSection.SetIsDirty(true);        
        },
        
        HandlerForSaveComplete: function(result, userContext)
        {                  
            window.VDS$PermissionsSection.SetIsDirty(false);        
            window.VDS$CSPage.DisplayServerOperation(false); 
            window.VDS$CSPage.SetPageDetails(result);  
            window.VDS$CSPage.LoadVersionViewer();      
        },
        
        HandlerForSaveException: function(result, userContext)
        {   
            alert(result._message);                            
            window.VDS$PermissionsSection.SetIsDirty(false);  
            window.VDS$CSPage.DisplayServerOperation(false);  
        },
        
        Save: function()
        {
            if (this.mIsDirty)
            {
                window.VDS$CSPage.DisplayServerOperation(true);
                
                // Retrieve selected keywords                  
                var wContent = window.VDS$CSPage.PageDetails();
                var idList = this.BuildSelectedList($(this.mChkListCtl));
		            		        
		        if (idList.length > 0)
		        {
		            var wResource = new VDS.VWeb.ClientSideUI.WebResourceDTO(); 
		            wResource.Permissions = idList;
                    VDS.VWeb.Services.WebContentService.SaveWebResourcePermissions(wContent, wResource,
                        this.HandlerForSaveComplete, this.HandlerForSaveException);  
                }
                
                window.VDS$CSPage.DisplayServerOperation(false);
            }
        },
        
        BuildSelectedList: function(list)
        {
            var idList = new Array();    
            var nodes = null;
            
            if (list.childNodes.length > 1)
                nodes = list.childNodes[1];
            else
                nodes = list.childNodes[0];
                
            if (nodes == null)
                return;
                
            for (var i=0; i < nodes.childNodes.length; i++)
            {
                var currentTd = null;
                if (nodes.childNodes[i].childNodes.length > 2)
                    currentTd = nodes.childNodes[i].childNodes[1];
                else
                    currentTd = nodes.childNodes[i].childNodes[0];
                    
                if (currentTd == null)
                    break;
                    
                var chkBox = currentTd.childNodes[0];
                if (chkBox.checked == true)    
		            idList.push(currentTd.childNodes[1].innerHTML);    		            
            }	
            
            return idList;	        
        }                
});


/* ------------------------------------------------------------------------ 
 * WebResourceEditSection represents an inherited EditSection
 * ------------------------------------------------------------------------ */        
var WebResourceEditSection = Class.create(EditSection,
    {
        AssignEditControls: function(userCtl, title, author, abstrct)
        {
            this.mUserCtl = userCtl;
            this.mTitle = title
            this.mTitle.SetEditSection(this);            
            this.mAuthor = author;
            this.mAuthor.SetEditSection(this);
            this.mAbstract = abstrct;
            this.mAbstract.SetEditSection(this);
            //this.mSnippet = snippet;
            //this.mSnippet.SetEditSection(this);
        },
        
        Delete: function()
        {
            if (!window.VDS$CSPage.PromptForConfirm('Are you sure you want to delete this Resource?'))
                return;
                
            window.VDS$CSPage.DisplayServerOperation(true);
                            
            VDS.VWeb.Services.WebContentService.DeleteWebResource(window.VDS$CSPage.PageDetails(),
                 this.HandlerForDeleteComplete, this.HandlerForSaveException, this.mUserCtl);                                                                    
        },
        
        HandlerForDeleteClicked: function(event) 
		{
		    if (!window.VDS$CSPage.IsDirtyWithMessage())		    		        
                this.Delete();
		}, 
		
        HandlerForDeleteComplete: function(result, userContext) 
		{		                 		    
		    //window.VDS$CSPage.DisplayServerOperation(false);
		    
		    WebForm_DoCallback(userContext, '',
                    window.VDS$EditSections[0].HandlerForUpdateComplete, null,
                    window.VDS$EditSections[0].HandlerForSaveException, true);     
		}, 
		
        HandlerForSaveComplete: function(result, userContext)
        {
            window.VDS$CSPage.SetPageDetails(result);                                               
            window.VDS$EditSections[userContext].SetIsDirty(false);        
            window.VDS$CSPage.DisplayServerOperation(false);      
            window.VDS$CSPage.LoadVersionViewer();  
        },
        
        HandlerForSaveException: function(result, userContext)
        {   
            alert(result._message);                                         
            window.VDS$CSPage.DisplayServerOperation(false);  
        },
        
        HandlerForUpdateComplete: function(result, userContext)
        {
            eval(result);
        },
        
        Save: function()
        {
            if (this.mIsDirty)
            {
                window.VDS$CSPage.DisplayServerOperation(true);
                
                var wResource = new VDS.VWeb.ClientSideUI.WebResourceDTO(); 
                
                wResource.ContainerName = this.mContainerName;
                wResource.IsNew = this.mIsNew; 
                wResource.IsNewVersion = this.mIsNewVersion;
                wResource.Title = this.mTitle.mTag.innerHTML;                          
                wResource.Author = this.mAuthor.GetAuthor();                          
                wResource.Abstract = this.mAbstract.mTag.innerHTML;                          
                wResource.AuthorisedSnippet = "";//this.mSnippet.mTag.innerHTML;                          
                
                if (wResource.Title.toLowerCase() == VDS$CSPage.EmptyTitleMsg)            
                    wResource.Title = '';

                                      
                VDS.VWeb.Services.WebContentService.SaveWebResource(window.VDS$CSPage.PageDetails(),
                     wResource, this.HandlerForSaveComplete, 
                     this.HandlerForSaveException, this.mIndex);  
            }
        }
});                        


/* ------------------------------------------------------------------------ 
 * KeywordSection represents an inherited EditSection
 * ------------------------------------------------------------------------ */        
var KeywordSection = Class.create(EditSection,
    {
        initialize: function(cbo, assignBtn, displayDiv) 
		{
		    
		    this.mCombo = cbo;
		    this.mAssignBtn = assignBtn;
		    this.mPane = $(displayDiv);
		    this.mIsDirty = false;
		    this.mID = 0;
		    this.mKeyword = '';
		    
		    this.BindHandlers();
		    
            if (window.VDS$Nubbins == null)       
                window.VDS$Nubbins = new Array();  
                
		    window.VDS$Nubbins.push(new HoverObserver($(this.mCombo).up('div.keywordsViewer')));
        },
        
        BindHandlers: function()
        {
            var handler = this["HandlerForAssignBtnClick"].bind(this);
            $(this.mAssignBtn).observe('click', handler);
                        
		    handler = this["HandlerForItemsRequesting"].bind(this);
		    $(this.mCombo).observe('clientItemsRequesting', handler);			    	    
        },
        
        Delete: function(keywordID)
        {                                        
            if (!window.VDS$CSPage.PromptForConfirm('Are you sure you want to delete this keyword?'))
                return;
                
            window.VDS$CSPage.DisplayServerOperation(true);
                
            VDS.VWeb.Services.WebContentService.DeleteWebContentSearchKeyword(window.VDS$CSPage.PageDetails(),
                 keywordID, this.HandlerForSaveComplete, 
                 this.HandlerForSaveException);                                                                    
        },
        
        HandlerForDeleteClicked: function(event) 
		{
		    if (!window.VDS$CSPage.IsDirtyWithMessage())		    		        
		            this.Delete();            
		}, 
        
        HandlerForAssignBtnClick: function(event)
        {                        
            var items = $(this.mCombo).control.get_items();
            var itemCount = items.get_count();
            var item = null;
            
            if (itemCount > 0)
            {                
                for (var index = 0; index < itemCount; ++index) 
                {
                    if ($(this.mCombo).value == items.getItem(index)._text)
                    {
                        item = items.getItem(index);                        
                        break;
                    }
                }                                            
            }
                
            if (this.IsNewWordBeingAdded(item))  
            {                 
                this.mID= 0;           
                this.mKeyword = $(this.mCombo).value;
            }
            else if (item != null)
            {
                this.mID = item.get_value();                        
                this.mKeyword = item._text;
            }
            
            if (!this.KeywordExists())
                this.Save();
        },
        
        HandlerForItemsRequesting: function(sender, eventArgs)
        {
            //var context = eventArgs.get_context();
            //context["FilterString"] = eventArgs.get_text();
        },
        
        HandlerForLoadingComplete: function(result, userContext)
        {
            window.VDS$CSPage.DisplayServerOperation(false); 
            if (result == null)
                return;
                
            var html = result[0];
            var js = result[1];
            
            if (html == null | userContext == null)
                return;
                
            var container = $(userContext);
            container.update(html);            
            eval(js);
        }, 
        
        HandlerForSaveComplete: function(result, userContext)
        {                  
            window.VDS$CSPage.SetPageDetails(result);   
            window.VDS$KeywordSection.ReLoad();       
            window.VDS$CSPage.DisplayServerOperation(false);      
            window.VDS$CSPage.LoadVersionViewer(); 
        },
        
        HandlerForSaveException: function(result, userContext)
        {   
            alert(result._message);                            
            window.VDS$CSPage.DisplayServerOperation(false);  
        },
        
        IsNewWordBeingAdded: function(item)
        {               
            return $(this.mCombo).value.length > 0 &  item == null;                 
        },
        
        KeywordExists: function()
        {
            if (this.mKeyword.length == 0)
                return true;
                
            var links = $$('span.keyword');
            for (var index = 0; index < links.length; ++index) 
            {
                if (links[index].innerHTML.toLowerCase() == this.mKeyword.toLowerCase())
                    return true;
            }
            return false;                    
        },
        
        ReLoad: function()
        {                        
            window.VDS$CSPage.DisplayServerOperation(true); 
            VDS.VWeb.Services.WebContentService.RetrieveSearchKeywordsPane(window.VDS$CSPage.PageDetails(), 
                    this.HandlerForLoadingComplete, 
                    this.HandlerForSaveException, this.mPane);                
        }, 
        
        Save: function()
        {
                window.VDS$CSPage.DisplayServerOperation(true);
                                
                VDS.VWeb.Services.WebContentService.SaveWebContentSearchKeywords(window.VDS$CSPage.PageDetails(),
                        this.mID, this.mKeyword,
                        this.HandlerForSaveComplete, this.HandlerForSaveException);  
        }
});

/* ------------------------------------------------------------------------ 
 * WebResourceDocumentSection represents an inherited EditSection
 * ------------------------------------------------------------------------ */        
var WebResourceDocumentSection = Class.create(EditSection,
    {
        initialize: function(resourceEA) 
		{
		    this.mResourceEA = resourceEA;
		    this.mResourceEA.SetEditSection(this);
		    this.mReloadContainer = this.mResourceEA.mTag.up().id;
		    this.mSection = $(this.mResourceEA.mContainer);
		    //.up('div.editSection');
		    this.mSaveBtn = this.mSection.up('div.editSection').down('a.saveSection');	
		    this.mIsDirty = false;	
		    
		    if (window.VDS$Nubbins == null)       
                window.VDS$Nubbins = new Array();  
                
		    window.VDS$Nubbins.push(new HoverObserver(this.mResourceEA.mContainer));	    		    
        },                       
        
        AddEditSection: function()
        {
            window.VDS$EditSections.push(this);
            this.mEditSectionIndex = window.VDS$EditSections.length - 1;
        },
        
        AssignDeleteSectionClass: function(display, scroll)        
        {
            this.AssignClass(display, scroll, 'deleteHL');
        },
        
        Delete: function(documentID)
        {                           
            if (documentID == null)             
                return;
                
            if (!window.VDS$CSPage.PromptForConfirm('Are you sure you want to delete this Document/Link?'))
                return;
                
            window.VDS$CSPage.DisplayServerOperation(true);

            var document = new VDS.VWeb.ClientSideUI.WebResourceDocumentDTO();                 
            document.DBID = documentID;
            VDS.VWeb.Services.WebContentService.DeleteWebResourceDocument(window.VDS$CSPage.PageDetails(),
                 document, this.HandlerForSaveComplete, this.HandlerForSaveException, this.GetIndex());           
        },
        
        GetIndex: function()
        {
            if (this.mEditSectionIndex != null)
                return this.mEditSectionIndex;
                
            for(var index = 0;index < window.VDS$EditSections.length;++index)
            {
                if (window.VDS$EditSections[index] == this)
                    return index;
            }
            
            return -1;
        },
        
        HandlerForResourcePaneComplete: function(result, userContext)
        {
            window.VDS$CSPage.DisplayServerOperation(false); 
            if (result == null)
                return;
                
            var html = result[0];
            var js = result[1];
            
            if (html == null | userContext == null)
                return;
                
            html = html.replace(/.Delete\(/g, "VDS$EditSections[" + userContext[0] + "].Delete(");
            var container = $(userContext[1]);
            if (container != null)       
                container.update(html);
            //container.insert( { before: html } );
            eval(js);
        },       
                
        HandlerForSaveComplete: function(result, userContext)
        {                  
            window.VDS$CSPage.SetPageDetails(result);  
            window.VDS$EditSections[userContext].LoadResourcePane(userContext);
            window.VDS$EditSections[userContext].SetIsDirty(false);  
            window.VDS$CSPage.LoadVersionViewer();           
            window.VDS$CSPage.DisplayServerOperation(false);      
        },
        
        HandlerForSaveException: function(result, userContext)
        {   
            alert(result._message);                            
            window.VDS$EditSections[userContext].SetIsDirty(false);  
            window.VDS$CSPage.DisplayServerOperation(false);  
        },
        
        LoadResourcePane: function(editSectionIndex)
        {            
            var params = new Array();
            params.push(editSectionIndex);
            params.push(this.mReloadContainer);
            window.VDS$CSPage.DisplayServerOperation(true); 
            VDS.VWeb.Services.WebContentService.RetrieveResourcePane(window.VDS$CSPage.PageDetails(), 
                        this.HandlerForResourcePaneComplete, 
                        this.HandlerForSaveException, params);    
        },
        
        SaveDocument: function(args)
        {
            var document = new VDS.VWeb.ClientSideUI.WebResourceDocumentDTO();

            document.ResourceType = -1;

            if (args.value.title.length > 0)
                document.Title = args.value.title;
            else
                document.Title = args.value.nameProp;
                
            document.Path = args.value.pathname;
            document.FileName = args.value.nameProp;
            document.FileSize = 0; // no longer supported by telerik FileManager
            document.FileType = args.value.mimeType;
            this.SaveWebResourceDocumentDTO(document);
        },
        
        SaveLink: function(args)
        {
            var document = new VDS.VWeb.ClientSideUI.WebResourceDocumentDTO();

            document.ResourceType = 2;
            document.Title = args.value.innerHTML;
            document.Path = args.value.href;
            document.Url = args.value.href;
            this.SaveWebResourceDocumentDTO(document);
        },
        
        SaveResource: function(args)
        {
            var document = new VDS.VWeb.ClientSideUI.WebResourceDocumentDTO(); 
            
            document.ResourceType = 1;        
            document.ResourceDatabaseIdentifier  = args.Resource.ChildDBID;        
            document.DBID = args.Resource.ChildDBID;
            document.Title = args.Resource.title;
            //document.FileName = args.Resource.name;
            //document.FileSize = args.Resource.shortSize;
            //document.FileType = args.Resource.extension;                        
            this.SaveWebResourceDocumentDTO(document);
        },
        
        SaveWebResourceDocumentDTO: function(document)
        {
                window.VDS$CSPage.DisplayServerOperation(true);
                
                // Retrieve selected keywords                  
                var wContent = window.VDS$CSPage.PageDetails();                                                                                        
                    		            
                VDS.VWeb.Services.WebContentService.SaveWebResourceDocument(wContent, document, 
                        this.HandlerForSaveComplete, this.HandlerForSaveException, this.GetIndex());           
        }
});

/* ------------------------------------------------------------------------ 
 * LinkSection represents an inherited WebResourceDocumentSection
 * ------------------------------------------------------------------------ */        
var LinkSection = Class.create(WebResourceDocumentSection,
    {
        LoadResourcePane: function(editSectionIndex)
        {            
            var params = new Array();
            params.push(editSectionIndex);
            params.push(this.mReloadContainer);
            window.VDS$CSPage.DisplayServerOperation(true); 
            VDS.VWeb.Services.WebContentService.RetrieveLinksPane(window.VDS$CSPage.PageDetails(), 
                        this.HandlerForResourcePaneComplete, 
                        this.HandlerForSaveException, params);     
        }
});


/* ------------------------------------------------------------------------ 
 * ResourceViewer represents a list of available resources for selection
 * ------------------------------------------------------------------------ */         
var ResourceViewer = Class.create();

Object.extend(ResourceViewer.prototype, {  

    initialize: function() 
	{
    },
                        
    GetRadWindow: function()
    {
		var oWindow = null;
		if (window.radWindow) 
		    oWindow = window.radWindow;
		else if (window.frameElement.radWindow) 
		    oWindow = window.frameElement.radWindow;
				    
	    return oWindow;
	},
            
    Select: function(childDBID, childDOID, title, url)
    {
        var oWnd = this.GetRadWindow();
        
        var args = new Object();
        args.Resource = new Object
        args.Resource.Title = title;        
        args.Resource.ChildDBID = childDBID;
        args.Resource.ChildDOID = childDOID;        
        args.Resource.Url = url;
        oWnd.Argument = args;        
        oWnd.Close(oWnd.Argument);                    
    }
});	 


/* ------------------------------------------------------------------------
* SharedCategoryEditArea inherits from SharedResourcesEditArea
* ------------------------------------------------------------------------ */ 
var SharedCategoryEditArea = Class.create(SharedResourcesEditArea,  
    {        
        BeginEditingEditor: function()
        {             
            this.mActions.setStyle({                                
                                width: this.mTag.getWidth()                                
            });
         
            var radWindow = RadCategoryWindow();
            
            if (radWindow.control == null)
                radWindow.show();                        
            else
                radWindow.control.show();                        
                
            this.mTag.show();                                    
        },
        
        ConfigureActionBar: function()
        {
            var actionBar = new CategoryActionBar(this.mEditActions, "", false);
        }
});

/* ------------------------------------------------------------------------ 
 * CategorySection represents an inherited EditSection
 * ------------------------------------------------------------------------ */
var CategorySection = Class.create(EditSection,
{
    initialize: function(resourceEA) {
        this.mResourceEA = resourceEA;
        this.mResourceEA.SetEditSection(this);
        this.mReloadContainer = this.mResourceEA.mTag.up().id;
        this.mSection = $(this.mResourceEA.mContainer);
        //.up('div.editSection');
        this.mSaveBtn = this.mSection.up('div.editSection').down('a.saveSection');
        this.mIsDirty = false;

        if (window.VDS$Nubbins == null)
            window.VDS$Nubbins = new Array();

        window.VDS$Nubbins.push(new HoverObserver(this.mResourceEA.mContainer));
    },

    Delete: function(categoryID) {
        if (categoryID == null)
            return;

        if (!window.VDS$CSPage.PromptForConfirm('Are you sure you want to delete this Category?'))
            return;

        window.VDS$CSPage.DisplayServerOperation(true);

        var document = new VDS.VWeb.ClientSideUI.WebResourceDocumentDTO();
        document.DBID = categoryID;
        VDS.VWeb.Services.WebContentService.DeleteWebResourceCategory(window.VDS$CSPage.PageDetails(),
                 document, this.HandlerForCategoriesSaveComplete, this.HandlerForCategoriesSaveException, this.GetIndex());
    },

    GetIndex: function() {
        if (this.mEditSectionIndex != null)
            return this.mEditSectionIndex;

        for (var index = 0; index < window.VDS$EditSections.length; ++index) {
            if (window.VDS$EditSections[index] == this)
                return index;
        }

        return -1;
    },

    HandlerForCategoryPaneComplete: function(result, userContext) {
        window.VDS$CSPage.DisplayServerOperation(false);
        if (result == null)
            return;

        var html = result[0];
        var js = result[1];

        if (html == null | userContext == null)
            return;

        html = html.replace(/.Delete\(/g, "VDS$EditSections[" + userContext[0] + "].Delete(");
        var container = $(userContext[1]);
        if (container != null)
            container.update(html);
        //container.insert( { before: html } );
        eval(js);
    },

    HandlerForCategoriesSelected: function(radWindow, returnValue) {

        if (returnValue == null)
            return;

        this.SaveCategories(returnValue.IDList);
        this.mResourceEA.mTag.show();
        this.mResourceEA.EditingComplete();
    },

    HandlerForCategoriesSaveComplete: function(result, userContext) {
        window.VDS$CSPage.SetPageDetails(result);
        window.VDS$CategorySection.LoadCategoryPane();
        window.VDS$CategorySection.SetIsDirty(false);
        window.VDS$CSPage.LoadVersionViewer();
        window.VDS$CSPage.DisplayServerOperation(false);
    },

    HandlerForCategoriesSaveException: function(result, userContext) {
        alert(result._message);
        window.VDS$CategorySection.SetIsDirty(false);
        window.VDS$CSPage.DisplayServerOperation(false);
    },

    LoadCategoryPane: function() {
        var params = new Array();
        params.push(this.GetIndex());
        params.push(this.mReloadContainer);
        window.VDS$CSPage.DisplayServerOperation(true);
        VDS.VWeb.Services.WebContentService.RetrieveCategoryPane(window.VDS$CSPage.PageDetails(),
                        this.HandlerForCategoryPaneComplete,
                        this.HandlerForSaveException, params);
    },

    SaveCategories: function(list) {
        window.VDS$CSPage.DisplayServerOperation(true);

        if (list.length > 0) {
            var idList = new Array();
            for (var i = 0; i < list.length; i++)
                idList.push(list[i]);

            VDS.VWeb.Services.WebContentService.SaveWebResourceCategories(window.VDS$CSPage.PageDetails(),
                    idList, this.HandlerForCategoriesSaveComplete, this.HandlerForCategoriesSaveException);
        }
    }
});

/* ------------------------------------------------------------------------ 
 * CategoryPicker represents a list of available resources for selection
 * ------------------------------------------------------------------------ */         
var CategoryPicker = Class.create();

Object.extend(CategoryPicker.prototype, {  

    initialize: function(tree, btn) 
	{
	    this.mTreeCtl = $(tree);
	    this.mAssignBtn = this.mTreeCtl.previous().down('input.assignButton');
	    
        this.mAssignBtn.observe('click', this["HandlerForAssignBtnClick"].bind(this));
    },
                        
    GetRadWindow: function()
    {
		var oWindow = null;
		if (window.radWindow) 
		    oWindow = window.radWindow;
		else if (window.frameElement.radWindow) 
		    oWindow = window.frameElement.radWindow;
				    
	    return oWindow;
	},
    
    HandlerForAssignBtnClick: function(event)
    {                
        var oWnd = this.GetRadWindow();
        
        if (this.IsValid())
        {
            var args = new Object();
            args.IDList = this.BuildSelectedList(this.mTreeCtl);
            oWnd.Argument = args;
            oWnd.Close(oWnd.Argument);                            
        }
        else
            alert("Only two categories can be assigned");
    },
    
    BuildSelectedList: function(list)
    {          
        var treeView = list.control;
        var selectedNodes = treeView.get_checkedNodes();
        var idList = new Array();
        if (selectedNodes.length > 0)
        {
            for (var i=0; i < selectedNodes.length; i++)            
                idList.push(selectedNodes[i].get_value());            
        }
        
        return idList;                                    
    },
    
    IsValid: function()
    {
        var treeView = this.mTreeCtl.control;
        var selectedNodes = treeView.get_checkedNodes();
        
        return selectedNodes.length <= 2;
    }
     
});	 

