﻿/* ------------------------------------------------------------------------ 
 * CSPage represents a client side page, holds editable, isdirty, etc.
 * ------------------------------------------------------------------------ */         
var CSPage = Class.create();

Object.extend(CSPage.prototype, {

    initialize: function(container, editable, ctlPrefix) {
        this.mContainer = container;
        this.mEditable = editable;
        this.mIsDirty = false;
        this.mBackgroundClass = 'background';
        this.mCtlPrefix = ctlPrefix;
        //this.CreateBackground1();
    },

    BlueprintID: function() {
        return this.mBlueprintID;
    },

    CreateBackground1: function() {
        this.mContainer.toggleClassName('foreground');
        var top = this.mContainer.up('div.centrewrapper')
        top.toggleClassName(this.mBackgroundClass);
        top = this.mContainer.up('div.rootwrapper')
        top.toggleClassName(this.mBackgroundClass);
        top = this.mContainer.up('div.bodyright')
        top.toggleClassName(this.mBackgroundClass);
    },

    CtlPrefix: function() {
        return this.mCtlPrefix;
    },

    DisplayServerOperation: function(display) {
        if (display) {
            //this.show();
            RadLoadingPanel().show();
            RadLoadingPanel().scrollTo();
            //this.element.addClassName('busy');
        }
        else
            RadLoadingPanel().hide();
        //window.VDS$CSPage.mContainer.removeClassName('busy');
    },

    DomainObject: function() {
        return this.mDomainObject;
    },

    EditStatus: function() {
        return this.mEditStatus;
    },

    GetCurrentSection: function() {
        return this.mCurrentSection;
    },

    HandlerForLoadVersionViewerComplete: function(result, userContext) {
        window.VDS$CSPage.DisplayServerOperation(false);
        var html = result[0];
        var js = result[1];

        if (html == null | userContext == null)
            return;

        var container = $(userContext);
        container.insert({ before: html });
        eval(js);
    },

    HandlerForLoadVersionViewerException: function(exception) {
        window.VDS$CSPage.DisplayServerOperation(false);
        alert(exception);
    },

    HandlerForOpenCustomLink: function(args) {
        this.mEditorRestorePoint = RadEditor().control.createRestorePoint();
        this.mEditorRestorePoint.Select();
        RadEditor().control.pasteHtml(String.format("<a href='{0}' target='{1}' class=''>{2}</a>", args.value.href, args.value.target, args.value.innerHTML));
    },

    HandlerForOpenLinkManager: function(args, handler) {
        if (args == null) {
            var params = new Object();
            var a = new Element('a', { 'class': 'link', href: 'http://' });
            params.realLink = a;
            params.showText = true;
            params.CssClasses = new Array('link');
            params.documentAnchors = new Array();
            params.get_value = function() { return a; };
        }

        RadEditor().control.showDialog("LinkManager", params, handler);

        if (args != null) {
            if (args.set_cancel != null)
                args.set_cancel(true);
        }
        
    },

    HandlerForOpenDocumentManager: function(args) {
        RadEditor().control.showDialog("DocumentManager", args, this.HandlerForDocumentSelected);
        args.set_cancel(true);
    },

    HandlerForOpenSimpleLinkManager: function(args) {
        this.mEditorRestorePoint = RadEditor().control.createRestorePoint();
        this.mEditorRestorePoint.Select();
        RadEditor().control.setFocus();

        //FireFox - will work only if there is selection of text, otherwise built-in browser command does not work
        if (!document.all) {
            var href = prompt("Enter a URL:", "http://");
            if (href)
                RadEditor().control.get_document().execCommand("createlink", false, href);
        }
        else
            RadEditor().control.get_document().execCommand("createlink", true, null);

        args.set_cancel(true);
    },

    HandlerForOpenResourceManager: function() {
        this.mEditorRestorePoint = RadEditor().control.createRestorePoint();
        RadWindow().control.show("ResourceManager");
    },

    HandlerForTools: function(hiddenTools) {
        if (hiddenTools.length == 0)
            return;

        var tools = hiddenTools.split(',').toArray();

        if (tools.length < 1)
            return;

        for (var i = 0; i < tools.length; ++i) {
            var tool = RadEditor().control.getToolByName(tools[i]);
            var elem = tool.get_element();
            elem.style.display = "none"; //hide the bold tool
        }
    },

    HandlerForDocumentSelected: function(sender, args) {
        //this.mEditorRestorePoint = RadEditor().control.createRestorePoint();         
        //this.mEditorRestorePoint.Select();                                                                        
        RadEditor().control.pasteHtml(String.format("<a href='{0}' target='{1}' class='documentLink'>{2}</a>", args.Result.href, args.Result.target, args.Result.title));
    },

    HandlerForResourceSelected: function(sender, args) {

        if (args == null)
            return;

        var snippet = new CSSnippetLink();
        snippet.SaveResourceLink(args.Resource, this.PageDetails(), this.mCurrentSection.SectionDetails());
    },

    InsertSection: function(html, js, section, userContext) {
        var container = $(userContext).up('div.insertionPointContainer');
        //var container = $(userContext);
        container.insert({ before: html });
        eval(js);

        if (container.previous('div.insertionPointContainer') == null)
            container.up().scrollTo();
        else
            container.previous('div.insertionPointContainer').scrollTo();
    },

    IsDirty: function() {
        for (var index = 0; index < window.VDS$EditSections.length; ++index) {
            var item = window.VDS$EditSections[index];
            if (item.IsDirty())
                return true;
        }
        return false;
    },

    IsDirtyWithMessage: function() {
        if (this.IsDirty()) {
            for (var index = 0; index < window.VDS$EditSections.length; ++index) {
                var item = window.VDS$EditSections[index];
                if (item.IsDirty()) {
                    if (item.mTitle != null)
                        item.mTitle.mContainer.up().scrollTo();
                    else
                        item.mHtml.mContainer.up().scrollTo();
                    break;
                }
            }
            alert('Please save current section before editing a new section');
            return true;
        }

        return false;
    },

    IsEditable: function() {
        return this.mEditable;
    },

    IsNew: function() {
        return this.mIsNew;
    },

    IsNewVersion: function() {
        return this.mIsNewVersion;
    },

    LoadVersionViewer: function() {
        if (window.VDS$VV == null) {
            window.VDS$CSPage.DisplayServerOperation(true);
            VDS.VWeb.Services.WebContentService.RetrieveVersionViewer(this.PageDetails(),
                    this.HandlerForLoadVersionViewerComplete,
                    this.HandlerForLoadVersionViewerException, this.mContainer);
        }
    },

    PageDetails: function() {
        var wContent = new VDS.VWeb.ClientSideUI.WebContentDTO();

        wContent.BlueprintID = this.mBlueprintID;
        wContent.ContainerName = this.mWebContent.ContainerName;
        wContent.EditStatus = this.mEditStatus;
        wContent.IsNew = this.mIsNew;
        wContent.IsNewVersion = this.mIsNewVersion;
        wContent.ID = this.mID;
        wContent.DatabaseIdentifier = this.mDBID;
        wContent.DomainObject = this.mDomainObject;
        wContent.Sections = window.VDS$EditSections.length;
        wContent.Title = $(this.mTitle).innerHTML;
        wContent.TabID = this.mWebContent.TabID;
        wContent.ModuleID = this.mWebContent.ModuleID;

        return wContent;
    },

    PromptForCancel: function() {
        if (this.IsDirty()) {
            return this.PromptForConfirm('Are you sure you want to close this page, you have unsaved changes?');
        }
    },

    PromptForCancelGlobal: function() {
        if (window.VDS$CSPage.IsDirty())
            return 'Are you sure you want to close this page, you have unsaved changes?';
    },

    PromptForUpdate: function() {
        return this.PromptForConfirm('Are you sure you want to update the edit status?');
    },

    PromptForConfirm: function(message) {
        if (confirm(message))
            return true;
        else
            return false;
    },

    RetrievePosition: function(textDiv) {
        var container = $(this.mContainer);
        var point = container.down('div.insertionPointContainer');
        var index = 1;

        while (point != null) {
            var iteration = point.down('div.text');

            if (iteration.id == textDiv)
                return index;

            point = point.next('div.insertionPointContainer');
            index++;
        }

        return 1;
    },

    SetCurrentSection: function(section) {
        this.mCurrentSection = section;
    },

    SetEmptyText: function(title, subTitle) {
        this.EmptyTitleMsg = title;
        this.EmptySubTitleMsg = subTitle;
    },

    SetTitleElement: function(titleElement) {
        this.mTitle = titleElement;
    },

    SetPageDetails: function(wContent) {
        this.mEditable = wContent.IsEditable;
        this.mBlueprintID = wContent.BlueprintID;
        this.mEditStatus = wContent.EditStatus;
        this.mIsNew = wContent.IsNew;
        this.mIsNewVersion = wContent.IsNewVersion;
        this.mID = wContent.ID;
        this.mDBID = wContent.DatabaseIdentifier;
        this.mDomainObject = wContent.DomainObject;
        this.mWebContent = wContent;

        if (window.VDS$VV != null)
            window.VDS$VV.DisplayOperations(wContent);
    },

    WebContentDBID: function() {
        return this.mWebContentDBID;
    },

    WebContentID: function() {
        return this.mWebContentID;
    }
});

/* ------------------------------------------------------------------------ 
 * InsertionPoint allows new section to be inserted 
 * ------------------------------------------------------------------------ */        
var InsertionPoint = {
    active: true,

    Init: function(editable, elementName)
        {
            this.element = $(elementName);
            
            if (!this.element) 
                return;
            
            this.element.hide();
            
            if (!editable)
            {   
                var div = this.element.next('div.insertionPointContainer');
                while (div != null)
                {
                    div.down().hide();
                    div = div.next('div.insertionPointContainer');
                }
                return;
            }
                
            var moveHandler = this["HandlerForMouseMove"].bind(this);
            var downHandler = this["HandlerForMouseDown"].bind(this);
            var clickHandler = this["HandlerForClick"].bind(this);
            this.element.observe('mousemove', moveHandler);
            this.element.observe('mousedown', downHandler);           
            this.element.observe('click', clickHandler);        
            
            this["HandlerForRetrieveComplete"].bind(this);
		    this["HandlerForSaveException"].bind(this);   
        },
            
    HandlerForClick: function(event)
        {
            if (this.mLastActiveElement == null)
                return;
                
            if (!window.VDS$CSPage.IsDirtyWithMessage())
            {
                window.VDS$CSPage.DisplayServerOperation(true);
                var section = new VDS.VWeb.ClientSideUI.WebContentSectionDTO(); 
                                                                                   		    
                VDS.VWeb.Services.WebContentService.RetrieveNewWebContentSection(window.VDS$CSPage.PageDetails(),
                         section, this.HandlerForRetrieveComplete, 
                         this.HandlerForSaveException, this.mLastActiveElement.id);         
            }
        },
        
    HandlerForMouseDown: function(event) 
        {
            this.set();
            event.stop();
        },  
          
    HandlerForMouseMove: function(event) 
        {
            event.stop();
        },

    HandlerForRetrieveComplete: function(result, userContext)
        {
            var html = result[0];
            var js = result[1];
            var section = result[2];
            window.VDS$CSPage.InsertSection(html, js, section, userContext);
            window.VDS$CSPage.DisplayServerOperation(false);
        },
        
    HandlerForSaveException: function(result)
        {
            alert(result);
        },
        
    MouseOver: function(element, position)
        {
            if (!VDS$CSPage.IsEditable)
                return false;

            if (this.mActiveElement == element && this.mActivePosition == position)
                return false;

            this.MouseLeave();
            
            if (element.hasClassName('insertionPointImgBtm'))
                this.mLastActiveElement = element;
            else
                this.mLastActiveElement = element.next().down('div.title');                
                //this.mLastActiveElement = element.next('div.insertionPointContainer');
                
                
            this.mActiveElement = element;
            this.mActiveElement.hide();
            this.mActivePosition = position;
            
            if (!this.active) 
                return;

            this.move(position, element);
            this.show();            
        },
        
    MouseLeave: function() 
        {
            if (this.mActiveElement)
            {
                if (!this.active) 
                    return;
                
                this.mActiveElement.show();
                this.hide();
            }
        
            this.mActiveElement = this.mActivePosition = null;
        },
        
    show: function() 
        {
            this.element.show();
            document.body.addClassName("nubbinless");
        },

    hide: function() 
        {
            this.element.hide();
            document.body.removeClassName("nubbinless");
        },

    move: function(position, widget) 
        {
             if (position == "top")                 
                widget.insert({ before: this.element });
            else 
                widget.insert({ after: this.element });                
        },

     set: function() 
        {
            this.element.fire("insertionpoint:set");
        },

     stop: function() 
        {
            this.active = false;
        },

     start: function() 
        {
             this.hide();
             this.active = true;
        }
};
