﻿// [ Start of Copy Into jsDraft.js ] 
var gjbMenu = {
    e : {
        UserAction: {
            DeleteSite : 6,
            SelectSuperUser : 12,
            SelectTasks : 13,
            NavigateToPage : 17,
            SiteMaintenance : 19,
            AddTask : 22,
            BrowseAllTasks : 23,
            DatabaseMaintenance: 37,
            SelectArticles : 41,
            BrowseAllArticles: 42,
            AddArticle: 46,
            SelectEvents: 47,
            BrowseAllEvents: 50,
            SelectBusinesses : 52,
            AddEvent: 51,
            SelectProfile : 53,
            BrowseAllBusinesses : 57,
            AddBusiness: 58,
            EditSiteProfile: 68,
            ImportPostalCodes : 69,
            SelectAdministration : 70,
            ChangeLoginName : 63,
            ChangePassword : 64,
            ChangeSecurityQuestion : 65,
            ChangeProfile: 80
        }
    }
};


// xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
// Browser Functions
// xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

// Verifies at least one row selected, user really wants to delete
function isDeleteOK() {

    var CheckCount = checkBoxCount();
    if (CheckCount === 0) {
        alert('You must select at least one row to delete.');
    }
    else if (CheckCount === 1) {
        if (confirm('Are you sure you want to delete this row?  It cannot be recovered.') === true) {
            if (confirm('Are you REALLY sure you want to delete this row?  Cannot be undone.') === true) {
                return true;
            }

        }
    }
    else if (CheckCount > 1) {
        if (confirm('Are you sure you want to delete these ' + CheckCount + ' rows?  They cannot be recovered.') === true) {
            if (confirm('Are you REALLY sure you want to delete these ' + CheckCount + ' rows?  Cannot be undone.') === true) {
                return true;
            }
        }
    }

    // Still here?
    return false;
}

// Counts the number of checked records
function checkBoxCount() {

    var Elements = document.getElementsByTagName('input');
    var CheckedCount = 0;

    // Loop through all of the elements
    for (var i = 0; i < Elements.length; i++) {

        // Get the IsDragColumn attribute
        var Element = Elements[i];
        var Attr = Element.getAttribute('type');

        if (Attr === 'checkbox') {
            if (Element.checked) {
                if (Element.name.indexOf('chkSelected') > 0) {
                    CheckedCount = CheckedCount + 1;
                }
            }
        }

    } // for

    return CheckedCount;
}

function isResetArticleCountOK() {
    return confirm('Reset article count and start counting from zero?');
}

// Verifies one record selected
function isEditOK() {

    var CheckCount = checkBoxCount();
    if (CheckCount === 1) {
        return true;
    }
    else if (CheckCount === 0) {
        alert('You must select a row to edit.');
        return false;
    }
    else if (CheckCount > 1) {
        alert('Please select only one row to edit.');
        return false;
    }
}

// Verifies at least one row selected, user really wants to delete
function isAtLeastOne(FunctionName, ConfirmMessageOne, ConfirmMessageMany) {

    var CheckCount = checkBoxCount();
    if (CheckCount === 0) {
        alert('You must select at least one row to ' + FunctionName + '.');
    }
    else if (CheckCount === 1) {
        if (confirm(ConfirmMessageOne) === true) {
            return true;

        }
    }
    else if (CheckCount > 1) {
        if (confirm(ConfirmMessageMany) === true) {
            return true;
        }
    }

    // Still here?
    return false;
}

// Verifies one record selected
function isCopyOK() {

    var CheckCount = checkBoxCount();
    if (CheckCount === 1) {
        return true;
    }
    else if (CheckCount === 0) {
        alert('You must select a row to copy.');
        return false;
    }
    else if (CheckCount > 1) {
        alert('Please select only one row to copy.');
        return false;
    }
}

function isExportOK() {

    if (confirm('Export and dowload the list?') !== true) {
        return false;
    }

    // Still here?
    return true;
}

// Verifies the user wants to purge the site of all records
function isPurgeOK() {

    if (confirm('Are you sure you want to remove ALL THE USERS from the site?') !== true) {
        return false;
    }

    if (confirm('This cannot be undone.  Are you SURE you want to remove ALL THE USERS from the site?') !== true) {
        return false;
    }

    if (confirm('Last chance!  ARE YOU SURE you want to DELETE ALL USERS FROM THIS SITE?') !== true) {
        return false;
    }

    // Still here?
    return true;
}

function selectAll() {

    // Select all the check boxes on the form
    var Elements = document.getElementsByTagName('input');
    var CheckedCount = 0;

    // Loop through all of the elements
    for (var i = 0; i < Elements.length; i++) {

        var Element = Elements[i];
        var Attr = Element.getAttribute('type');

        // Is this a check box?
        if (Attr === 'checkbox') {
        
            // Does it have the right name?
            if (Element.name.indexOf('chkSelected') > 0) {
                Element.checked = true;
            }
        }
    }
    
    // Still here?
    return true;
}

// xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
// Utility Functions
// xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

function $(id) {
    return document.getElementById(id);
}

function getCookieVal(offset) {

    // Returns the portion after the equals sign, before the semicolon
    var endstr = document.cookie.indexOf(';', offset);
    
    // Did we get a value for endstr?
    if (endstr === -1) { 
        endstr = document.cookie.length;
    }
    
    return unescape(document.cookie.substring(offset, endstr));
}

function getCookie(cookieName) {
    // How long is the cookie name?
    var arg = cookieName + '=';
    var argLength = arg.length;
    
    // How long is the entire cookie?
    var cookieLength = document.cookie.length;
    
    // Try to find the cookie in the cookie string
    var i = 0;
    while (i < cookieLength) {
    
        // Offset the j counter
        var j = i + argLength;
        
        // Is this substring the name we are looking for?
        if (document.cookie.substring(i, j) === arg) {
            return getCookieVal(j);
        }
        
        i++;
        if (i === 0) {
            break;
        }
    } 
    
    // Still here?
    return null;
}

function setCookie(c_name, value, expiredays) {
    
    if(value === true){
        saveValue = '1';
    }
    else if (value === false) {
        saveValue = '0';
    }
    else {
        saveValue = value;
    }
    
    var exdate=new Date();
    
    exdate.setDate(exdate.getDate()+expiredays);
    document.cookie=c_name+ '=' +escape(saveValue)+
    ((expiredays === null) ? '' : ';expires='+exdate.toGMTString());
}

function extractNumber(value) {
    var n = parseInt(value, 10);
    return n === null || isNaN(n) ? 0 : n;
}

function getLeftPos(inputObj) {

    // Returns the left position
    var returnValue = inputObj.offsetLeft;
    
    try {
    
        // Loop through the input objects until the top container (HTML) is reached
        while ((inputObj = inputObj.offsetParent) !== null) {
            if (inputObj.tagName !== 'HTML') {
                returnValue += inputObj.offsetLeft;
            }
        }
    }
    catch (e) {
        alert('Error occurred in getLeftPos()');
    }
    return returnValue;
}

function getTopPos(inputObj) {
    
    // Returns the top position
    var returnValue = inputObj.offsetTop;
    
    // Loop through the input objects until the top container (HTML) is reached
    try {
        while ((inputObj = inputObj.offsetParent) !== null) {
            if (inputObj.tagName !== 'HTML') {
                returnValue += inputObj.offsetTop;
            }
        }
    }
    catch (e) {
        alert('Error occurred in getTopPos()');
    }
    return returnValue;
}

function hideMenus() {

    // Retrieve and store each menu
    var tbarMain_pnlArticles = $('tbarMain_pnlArticles');
    var tbarMain_pnlBusinesses = $('tbarMain_pnlBusinesses');
    var tbarMain_pnlEvents = $('tbarMain_pnlEvents');
    var tbarMain_pnlTasks = $('tbarMain_pnlTasks');
    var tbarMain_pnlAdministration = $('tbarMain_pnlAdministration');
    var tbarMain_pnlSuperUser = $('tbarMain_pnlSuperUser');
    var tbarMain_pnlProfile = $('tbarMain_pnlProfile');
    var pnlColumns = $('pnlColumns');
    var pnlElements = $('pnlElements');
    var pnlRSS = $('pnlRSS');
    var pnlThemes = $('pnlThemes');
    var pnlSectionMenu = $('pnlSectionMenu');
    var pnlPageMenu = $('pnlPageMenu');
    var pnlTasks = $('pnlTasks');
    
    // If the menu can be retrieved, hide it.
    if (pnlColumns !== null) {
        $('pnlColumns').style.display = 'none';
    }
    if (tbarMain_pnlArticles !== null) {
        $('tbarMain_pnlArticles').style.display = 'none';
    }
    if (tbarMain_pnlBusinesses !== null) {
        $('tbarMain_pnlBusinesses').style.display = 'none';
    }
    if (tbarMain_pnlEvents !== null) {
        $('tbarMain_pnlEvents').style.display = 'none';
    }
    if (tbarMain_pnlTasks !== null) {
        $('tbarMain_pnlTasks').style.display = 'none';
    }
    if (tbarMain_pnlAdministration !== null) {
        $('tbarMain_pnlAdministration').style.display = 'none';
    }
    if (tbarMain_pnlSuperUser !== null) {
        $('tbarMain_pnlSuperUser').style.display = 'none';
    }
    if (tbarMain_pnlProfile !== null) {
        $('tbarMain_pnlProfile').style.display = 'none';
    }
    if (pnlElements !== null) {
        $('pnlElements').style.display = 'none';
    }
    if (pnlRSS !== null) {
        $('pnlRSS').style.display = 'none';
    }
    if (pnlSectionMenu !== null) {
        $('pnlSectionMenu').style.display = 'none';
    }
    if (pnlPageMenu !== null) {
        $('pnlPageMenu').style.display = 'none';
    }
    if (pnlThemes !== null) {
        $('pnlThemes').style.display = 'none';
    }
    // (UsersBrowse.aspx)
    if (pnlTasks !== null) {
        $('pnlTasks').style.display = 'none';
    }
    return;
}

// Menu Functions
function moveMenu(WithScroll, MenuToMove, RelativeTo, LeftOffset, TopOffset) {

    // Get the menu control and the reference control
    var Menu = $(MenuToMove);
    var ReferenceControl = $(RelativeTo);

    // document.body.scrollTop does not work in IE
    var scrollTop = 0;
    var scrollLeft = 0;

    if (WithScroll === true) {
        scrollTop = document.body.scrollTop ? document.body.scrollTop :
        document.documentElement.scrollTop;
        scrollLeft = document.body.scrollLeft ? document.body.scrollLeft :
        document.documentElement.scrollLeft;
    }

    // Get the position of the reference control
    var LeftPos = getLeftPos(ReferenceControl) + scrollLeft;
    var TopPos = getTopPos(ReferenceControl) + scrollTop;

    // Add the offsets
    var NewLeftPos = LeftPos + LeftOffset;
    var NewTopPos = TopPos + TopOffset;

    // Hide, move, and display
    Menu.style.display = 'none';
    Menu.style.left = NewLeftPos + 'px';
    Menu.style.top = NewTopPos + 'px';
    Menu.style.display = 'block';
    
    return false;
}

function deleteSite(UserAction) {
    if (confirm('Are you sure you want to delete this site?')) {
        if (confirm('Are you REALLY sure you want to delete this site?  Cannot be undone.')) {
            if (Page.MouseTarget !== null) {

                // Refresh the page
                refreshPage(UserAction, '');
            }
        }
    }
}

function navigateToPage(target) {

    // Get the page ID from the attribute
    var PageID = target.getAttribute('PageBookmarkID');

    // Create the location with the PageID
    var NewLocation = 'Default.aspx?PageBookmarkID=' + PageID;

    //document.Default.Submit();
    window.location = (NewLocation);
}


function processMenuFunction(UserAction, target) {

    if (UserAction === 0) {
        return;
    }

    switch (UserAction) {
    
    case gjbMenu.e.UserAction.NavigateToPage:
        navigateToPage(target);
        break;
    
    case gjbMenu.e.UserAction.SelectArticles:
        moveMenu(false, 'tbarMain_pnlArticles', 'tbarMain_lblArticles', 0, 20);
        break;
        
    case gjbMenu.e.UserAction.AddArticle:
        window.location = ('frmArticlesNew.aspx?Caller=default.aspx');
        break;
        
    case gjbMenu.e.UserAction.BrowseAllArticles:
        window.location = ('frmArticlesBrowse.aspx');
        break;
        
    case gjbMenu.e.UserAction.SelectEvents:
        moveMenu(false, 'tbarMain_pnlEvents', 'tbarMain_lblEvents', 0, 20);
        break;
        
    case gjbMenu.e.UserAction.BrowseAllEvents:
        window.location = ('frmEventsBrowse.aspx');
        break;
        
    case gjbMenu.e.UserAction.AddEvent:
        window.location = ('frmEventsNew.aspx?Caller=default.aspx');
        break;
        
    case gjbMenu.e.UserAction.SelectBusinesses:
        moveMenu(false, 'tbarMain_pnlBusinesses', 'tbarMain_lblBusinesses', 0, 20);
        break;
        
    case gjbMenu.e.UserAction.AddBusiness:
        window.location = ('frmBusinessesNew.aspx?Caller=default.aspx');
        break;
        
    case gjbMenu.e.UserAction.BrowseAllBusinesses:
        window.location = ('frmBusinessesBrowse.aspx');
        break;
        
    case gjbMenu.e.UserAction.SelectTasks:
        moveMenu(false, 'tbarMain_pnlTasks', 'tbarMain_lblTasks', 0, 20);
        break;
        
    case gjbMenu.e.UserAction.AddTask:
        window.location = ('frmTasksNew.aspx?caller=default.aspx');
        break;
        
    case gjbMenu.e.UserAction.BrowseAllTasks:
        window.location = ('frmTasksBrowse.aspx');
        break;
        
    case gjbMenu.e.UserAction.SelectAdministration:
        moveMenu(false, 'tbarMain_pnlAdministration', 'tbarMain_lblAdministration', 0, 20);
        break;
        
    case gjbMenu.e.UserAction.EditSiteProfile:
        window.location = 'frmSiteEdit.aspx'; 
        break;
        
    case gjbMenu.e.UserAction.DeleteSite:
        deleteSite(UserAction);
        break;
        
    case gjbMenu.e.UserAction.SelectSuperUser:
        moveMenu(false, 'tbarMain_pnlSuperUser', 'tbarMain_lblSuperUser', 0, 20);
        break;
        
    case gjbMenu.e.UserAction.DatabaseMaintenance:
        window.location = ('frmDb.aspx');
        break;
        
    case gjbMenu.e.UserAction.SiteMaintenance:
        window.location = ('frmSiteMaintenance.aspx');
        break;
        
    case gjbMenu.e.UserAction.ImportPostalCodes:
        window.location = ('frmPostalCodesImport.aspx');
        break;
        
    case gjbMenu.e.UserAction.SelectProfile:
        moveMenu(false,'tbarMain_pnlProfile', 'tbarMain_lbWelcome', 0, 20);
        break;
        
    case gjbMenu.e.UserAction.ChangeLoginName:
        window.location = ('frmUsersChangeLoginName.aspx');
        break;

    case gjbMenu.e.UserAction.ChangePassword:
        window.location = ('frmUsersChangePassword.aspx');
        break;

    case gjbMenu.e.UserAction.ChangeSecurityQuestion:
        window.location = ('frmUsersChangeQuestion.aspx');
        break;

    case gjbMenu.e.UserAction.ChangeProfile:
        window.location = ('frmUsersChangeProfile.aspx');
        break;
        
    }
}
// [ End Into jsDraft.js ] //
// xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
// Global variables 
// xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

/*global document, prompt, confirm, PageMethods, Sys, alert, unescape, navigator, setTimeout, window */

var gjb = {
    e : {
        DragGroup : {
            Section : 1,
            SectionNew : 2,
            ContentBox : 4,
            ContentColumn : 5,
            Page : 7,
            PageNew : 8,
            ContentColumnContainer : 16,
            ContentColumnTop : 17,
            ContentColumnDiv : 18
            
        },
        ControlType: {
            TextBox : 1,
            Editor : 2,
            ArticleList : 3,
            RssYahoo : 4,
            Column : 5,
            Advertisement : 6,
            Redirect : 7,
            RssSimple : 8,
            EventList : 9,
            Label : 10,
            PDF : 11,
            Link : 12,
            LabelChild : 13,
            ContentTop : 14,
            UserList : 15,
            Unused16 : 16,
            Section : 17,
            Page : 18,
            SectionDragHandle : 19,
            PageDragHandle : 20,
            TaskList : 21,
            Unused22 : 22
        },
        ControlCategory: {
            Unused1: 1,
            Unused2: 2,
            Column: 3,
            ColumnControl: 4,
            Sections: 5,
            Pages: 6
        },
        RefreshOption: {
            None: 0,
            Page: 1,
            Content: 2,
            Alert: 3,
            Control: 4
        },
        
        UserAction: {
            Nothing : -1,
            SelectColumns : 1,
            AddSection : 2,
            AddPage : 3,
            AddFavorite: 4,
            AddSite : 5,
            DeleteSite : 6,
            DeleteSection : 7,
            DeletePage : 8,
            DeleteControl : 9,
            SelectTwoColumn : 10,
            SelectThreeColumn : 11,
            SelectSuperUser : 12,
            SelectTasks : 13,
            FinishLater : 14,
            DontSave : 15,
            DeleteFavorite : 16,
            NavigateToPage : 17,
            SelectSearch : 18,
            SiteMaintenance : 19,
            SelectTools : 20,
            AddControl : 21,
            AddTask : 22,
            BrowseAllTasks : 23,
            TaskListEdit : 24,
            TaskListClose : 25,
            UserListEdit : 26,
            UserListClose : 27,
            ChangeTheme : 28,
            RenameSection : 29,
            PublishDraft : 30,
            RssAddTo : 31,
            RssSubtractFrom : 32,
            EditorToggleToolbar : 33,
            RenamePage : 34,
            ImportDraft : 35,
            SetPropertyFromDropDown: 36,
            DatabaseMaintenance: 37,
            ResetEditorDirectory : 38,
            Unused39 : 39,
            Unused40 : 40,
            SelectArticles : 41,
            BrowseAllArticles: 42,
            EditorCancel : 43,
            EditorSelectPreview: 44,
            EditorSelectDesign: 45,
            AddArticle: 46,
            SelectEvents: 47,
            SelectRSS: 48,
            SelectThemes: 49,
            BrowseAllEvents: 50,
            AddEvent: 51,
            SelectBusinesses : 52,
            SelectProfile : 53,
            ShowSectionMenu : 54,
            EditorToggleSummary: 55,
            BrowseUsers: 56,
            BrowseAllBusinesses : 57,
            AddBusiness: 58,
            BrowseArticles: 59, 
            ArticleListEdit: 60,
            ArticleListClose: 61,
            ShowTaskMenu: 62,
            ChangeLoginName : 63,
            ChangePassword : 64,
            ChangeSecurityQuestion : 65,
            EventListEdit: 66, 
            EventListClose: 67,
            SelectEventListFilter: 68,
            EditSiteProfile: 68,
            ImportPostalCodes : 69,
            SelectAdministration : 70,
            Unused71 : 71,
            Unused72 : 72,
            Unused73 : 73,
            ToggleHiddenPageLabel : 74,
            ToggleHiddenPageInput : 75,
            Unused76 : 76,
            Unused77 : 77,
            Unused78 : 78,
            Unused79 : 79,
            ChangeProfile: 80, 
            NavigateToSubdomain : 81,
            ShowPageMenu : 82
        }
    },
    Global : {
        DragGroup : 0,
        SelectedID : ''
    }
};

// var OldCursor = '';
var DraggedDivRef;
var IsCancelled = false;
var IsMove = false;
var SavedRefID = '';
var SavedControlID = '';
var SaveRequired = false;
var IsOpera = navigator.appVersion.indexOf('Opera') >= 0 ? true:false;
var OldZIndex = 0;
var DragRectangle;
var v_holdY = -1;
var v_elWidth = 0;
var CurDestinationObj;
var DestinationParent;
var instruction = '';


// xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
// Utility Functions (more in jsMenus.js)
// xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
function showStatus(StatusMessage) {
   $('lblStatus').innerHTML = StatusMessage;
}

function showMessage(Message) {
    alert(Message);
}

function strToBool(StringValue) {
    if (StringValue.toUpperCase() === 'TRUE') {
        return true;
    }
    else {
        return false;
    }
}

function getPx(strInput) {

    // Return '0px' if length is 0
    if (strInput.length === 0) {
        return '0px';
    }
    
    // Is the length of the string and the value the same?
    if (strInput.length === extractNumber(strInput).toString.length) {
        return strInput + 'px';
    }
    
    // Still here?
    return strInput;
}

// xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
// Refresh Functions
// xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
function refreshComplete(sender, args) {
}

function refreshContent() {

    // Refresh the CONTENT ONLY

    // Create a PageRequestManager object
    var prm = Sys.WebForms.PageRequestManager.getInstance();

    // Perform a postback on the hidden button in the Content
    prm._doPostBack('lnkrefreshContent', '');
}

function refreshControl(ControlID) {

    // Refresh the individual control only

    // Create a PageRequestManager object
    var prm = Sys.WebForms.PageRequestManager.getInstance();

    // Get the ID of the link to click
    var UpdateID = Page.Controls(ControlID).UpdateID;

    // Perform a postback on the hidden button in the Content
    prm._doPostBack(UpdateID, '');
}

function refreshPage(Action, Tag) {
    // Hide the status
    showStatus('');

    // Create a PageRequestManager object
    var prm = Sys.WebForms.PageRequestManager.getInstance();

    // Create the serialized string (Action|Tag) to be sent back
    var rtnArgument = Action + '|' + Tag;

    // Perform a postback on the hidden button
    prm._doPostBack('lnkrefreshPage', rtnArgument);
}

// xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
// Page Methods and Page Object
// xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
function OnSuccess(Result) {
    showStatus('');

    // If save was successful, we should get a 1 character response string (refresh option)
    if (Result.length === 1) {

        var prm;

        // Refresh the page part(s).  Result comes back as a string.
        switch (extractNumber(Result)) {

        case gjb.e.RefreshOption.None:
            break;

        case gjb.e.RefreshOption.Page:
            refreshPage('', '');
            break;

        case gjb.e.RefreshOption.Content:
            refreshContent();
            break;

        case gjb.e.RefreshOption.Alert:
            alert('Server update successful.');
            break;

        case gjb.e.RefreshOption.Control:
            refreshControl(SavedControlID);
        }
    }
    else {
        // Save error
        alert('Error saving data: ' + Result);
    }
}

function OnFailed() {
    alert('Saving Page Failed');
}

function nU(TestString) {
    if (TestString === undefined || TestString === 'undefined') {
        return '';
    }
    else {
        return TestString;
    }
}

function readControlProperties(Control, HTMLElement, ColumnIndex) {

    // Exit if no frame element
    if (HTMLElement === null) {
        return;
    }

    // Frame Properties
    Control.ArticleID = HTMLElement.getAttribute('ArticleID');
    Control.ArticleUseSummary = HTMLElement.getAttribute('ArticleUseSummary') === 'true' ? true : false;
    Control.ArticleUseImage = HTMLElement.getAttribute('ArticleUseImage') === 'true' ? true : false;
    Control.ArticleImageScale = extractNumber(HTMLElement.getAttribute('ArticleImageScale'));
    Control.ArticleUseComments = HTMLElement.getAttribute('ArticleUseComments') === 'true' ? true : false;
    Control.ArticleUseTopStory = HTMLElement.getAttribute('ArticleUseTopStory') === 'true' ? true : false;
    
    Control.ControlID = HTMLElement.getAttribute('ControlID');

    Control.ColumnIndex = ColumnIndex;
    Control.FilterID = HTMLElement.getAttribute('FilterID');
    Control.IsFloating = HTMLElement.getAttribute('IsFloating') === 'true' ? true : false;
    Control.Last = false;
    Control.Obj = HTMLElement;
    Control.Parent = HTMLElement.parentNode;
    Control.UpdateID = HTMLElement.getAttribute('UpdateID');

    // Frame Coordinates
    // Control.Left = getPx(HTMLElement.style.left); 
    // Control.Top = getPx(HTMLElement.style.top); 
    // Control.Height = getPx(HTMLElement.style.height); 
    Control.Width = getPx(HTMLElement.style.width);

    Control.AbsoluteX = getLeftPos(HTMLElement);
    Control.AbsoluteY = getTopPos(HTMLElement);
    Control.OffsetHeight = HTMLElement.offsetHeight;
    Control.OffsetWidth = HTMLElement.offsetWidth;
    
    // Ordinal
    Control.Ordinal = extractNumber(HTMLElement.getAttribute('Ordinal'));

    // Frame Type and Subtype
    Control.ControlType = extractNumber(HTMLElement.getAttribute('ControlType'));

    
    if (Control.ControlType === null) {
        Control.ControlType = 1;
    }
    Control.ControlSubType = HTMLElement.getAttribute('olpSubType');

    // FrameBackgroundColor, Image, Repeat
    Control.FrameBackgroundColor = nU(HTMLElement.style.backgroundColor);

    // LabelBox Properties
    var LabelBoxElement = $(HTMLElement.getAttribute('LabelBoxID'));

    // Label Properties
    var LabelElement = $(HTMLElement.getAttribute('LabelID'));
    if (LabelElement !== null) {
        Control.Text = LabelElement.innerHTML;
    }
    else {
        Control.Text = '';
    }
    
    // Control specific properties
    Control.Rows = 0;
    switch (Control.ControlType) {

    case gjb.e.ControlType.RssSimple:
        Control.Rows = extractNumber(HTMLElement.getAttribute('Rows'));
        break;

    case gjb.e.ControlType.ArticleList:
        Control.Rows = extractNumber(HTMLElement.getAttribute('Rows'));
        break;
        
    case gjb.e.ControlType.EventList:
        Control.Rows = extractNumber(HTMLElement.getAttribute('Rows'));
        break;
    }
    
    // Store the original text for comparison upon export
    Control.OriginalText = Control.Text;

}

function setLabelText(Text, Control) {

    if (Text !== Control.Text) {
        try {
            $(Control.Obj.getAttribute('LabelID')).innerHTML = Text;
            Control.Text = Text;
            SaveRequired = true;
        }
        catch (e) {
            showMessage('Invalid Text property');
            return false;
        }
    }

}

function strBool(BooleanValue) {
    if (BooleanValue) {
        return 'true';
    }
    else {
        return 'false';
    }
}

function addControlMethods(Control) {

    // setArticleID
    Control.setArticleID = function(ArticleID) {
        if (ArticleID !== Control.ArticleID) {
            try {
                Control.Obj.setAttribute('ArticleID', ArticleID);
                Control.ArticleID = ArticleID;
                SaveRequired = true;
            }
            catch (e) {
                showMessage('Invalid ArticleID property');
                return false;
            }
        }
        return true;
    };

    // setFilterID
    Control.setFilterID = function(FilterID) {
        if (FilterID !== Control.FilterID) {
            try {
                Control.Obj.setAttribute('FilterID', FilterID);
                Control.FilterID = FilterID;
                SaveRequired = true;
            }
            catch (e) {
                showMessage('Invalid FilterID property');
                return false;
            }
        }
        return true;
    };

    // setArticleUseSummary
    Control.setArticleUseSummary = function(ArticleUseSummary) {
        if (ArticleUseSummary !== Control.ArticleUseSummary) {
            try {
                Control.Obj.setAttribute('ArticleUseSummary', strBool(ArticleUseSummary));
                Control.ArticleUseSummary = ArticleUseSummary;
                SaveRequired = true;
            }
            catch (e) {
                showMessage('Invalid ArticleUseSummary property');
                return false;
            }
        }
        return true;
    };

    // setArticleUseImage
    Control.setArticleUseImage = function(ArticleUseImage) {
        if (ArticleUseImage !== Control.ArticleUseImage) {
            try {
                Control.Obj.setAttribute('ArticleUseImage', strBool(ArticleUseImage));
                Control.ArticleUseImage = ArticleUseImage;
                SaveRequired = true;
            }
            catch (e) {
                showMessage('Invalid ArticleUseImage property');
                return false;
            }
        }
        return true;
    };

    // setArticleImageScale
    Control.setArticleImageScale = function(ArticleImageScale) {
        if (ArticleImageScale !== Control.ArticleImageScale) {
            try {
                Control.Obj.setAttribute('ArticleImageScale', ArticleImageScale);
                Control.ArticleImageScale = ArticleImageScale;
                SaveRequired = true;
            }
            catch (e) {
                showMessage('Invalid ArticleImageScale property');
                return false;
            }
        }
        return true;
    };

    // setArticleUseComments
    Control.setArticleUseComments = function(ArticleUseComments) {
        if (ArticleUseComments !== Control.ArticleUseComments) {
            try {
                Control.Obj.setAttribute('ArticleUseComments', strBool(ArticleUseComments));
                Control.ArticleUseComments = ArticleUseComments;
                SaveRequired = true;
            }
            catch (e) {
                showMessage('Invalid ArticleUseComments property');
                return false;
            }
        }
        return true;
    };

    // setArticleUseTopStory
    Control.setArticleUseTopStory = function(ArticleUseTopStory) {
        if (ArticleUseTopStory !== Control.ArticleUseTopStory) {
            try {
                Control.Obj.setAttribute('ArticleUseTopStory', strBool(ArticleUseTopStory));
                Control.ArticleUseTopStory = ArticleUseTopStory;
                SaveRequired = true;
            }
            catch (e) {
                showMessage('Invalid ArticleUseTopStory property');
                return false;
            }
        }
        return true;
    };
    
    // setOrdinal
    Control.setOrdinal = function (Ordinal) {
        if (Ordinal !== Control.Ordinal) {
            try {
                Control.Obj.setAttribute('Ordinal', Ordinal);
                Control.Ordinal = Ordinal;
                SaveRequired = true;
            }
            catch (e) {
                showMessage('Invalid Ordinal property');
                return false;
            }
        }
        return true;
    };


    // setRows
    Control.setRows = function (Rows) {
        if (Rows !== Control.Rows) {
            try {
                Control.Obj.setAttribute('Rows', Rows);
                Control.Rows = Rows;
                SaveRequired = true;
            }
            catch (e) {
                showMessage('Invalid Rows property');
                return false;
            }
        }
        return true;
    };


    // setText
    Control.setText = function(Text) {

        switch (Control.ControlType) {
            case gjb.e.ControlType.Label:
                if (Text !== Control.Text) {
                    try {
                        $(Control.Obj.getAttribute('LabelID')).innerHTML = Text;
                        Control.Text = Text;
                        SaveRequired = true;
                    }
                    catch (e) {
                        showMessage('Invalid Text property');
                        return false;
                    }
                }
                break;
                
            case gjb.e.ControlType.Editor:
                return setLabelText(Text, Control);

            case gjb.e.ControlType.ArticleList:
                return setLabelText(Text, Control);

            case gjb.e.ControlType.EventList:
                return setLabelText(Text, Control);
                
            case gjb.e.ControlType.TaskList:
                return setLabelText(Text, Control);
                
            case gjb.e.ControlType.UserList:
                return setLabelText(Text, Control);

                
            case gjb.e.ControlType.Section:
                if (Text !== Control.Text) {
                    try {
                        $(Control.Obj.getAttribute('LabelID')).innerHTML = Text;
                        Control.Text = Text;

                        // Call the web service and update the Section
                        PageMethods.PM_UpdateSectionName(Control.Obj.id, Text, gjb.e.RefreshOption.None, OnSuccess, OnFailed);
                    }
                    catch (f) {
                        showMessage('Invalid Text');
                        return false;
                    }
                }
                break;
                
            case gjb.e.ControlType.Page:
                if (Text !== Control.Text) {
                    try {
                        $(Control.Obj.getAttribute('LabelID')).innerHTML = Text;
                        Control.Text = Text;

                        // Call the web service and update the Section
                        PageMethods.PM_UpdatePageName(Control.Obj.id, Text, gjb.e.RefreshOption.None, OnSuccess, OnFailed);
                    }
                    catch (g) {
                        showMessage('Invalid Text');
                        return false;
                    }
                }
                break;
        }

        return true;
    };
}

function readSections(ControlCategory) {

    // Reads the Sections
    var Controls = [];
    var Control;

    // Get the Sections container
    var SectionsDiv = $('pnlSections');

    if (SectionsDiv === null) {
        return;
    }

    // Go through the div and get all of the divs within it
    var Sections = SectionsDiv.getElementsByTagName('div');

    // Go through each div... see if the control type is a section
    for (var i = 0; i < Sections.length; i++) {

        var SectionDiv = Sections[i];
        
        // Get the IsDragColumn attribute
        var attr = Sections[i].getAttribute('ControlType');

        // Retrieve the attribute differently if Opera
        if (IsOpera) {
            attr = Sections[i].ControlType;
        }
        
        // Is this the Section container?
        if (attr == gjb.e.ControlType.Section) {
        
            var ControlCount = Controls.length;

            // Add a new array (control) item
            Controls[ControlCount] = [];

            // Access the sub-array just created
            Control = Controls[ControlCount];

            // Read the properties from the child control into the control object
            readControlProperties(Control, SectionDiv, i + 1);
            
            // Set the ControlCategory
            Control.ControlCategory = ControlCategory;

            // Add the control's methods
            addControlMethods(Control);
        }
    }
    return Controls;
}

function readPages(ControlCategory) {

    // Reads the Pages
    var Controls = [];
    var Control;

    // Get the Page container
    var PagesDiv = $('pnlPages');

    if (PagesDiv === null) {
        return;
    }

    // Go through the div and get all of the divs within it
    var Pages = PagesDiv.getElementsByTagName('div');

    // Go through each div... see if the control type is a Page
    for (var i = 0; i < Pages.length; i++) {

        var PageDiv = Pages[i];
        
        // Get the IsDragColumn attribute
        var attr = Pages[i].getAttribute('ControlType');

        // Retrieve the attribute differently if Opera
        if (IsOpera) {
            attr = Pages[i].ControlType;
        }
        
        // Is this the Page container?
        if (attr == gjb.e.ControlType.Page) {
        
            var ControlCount = Controls.length;

            // Add a new array (control) item
            Controls[ControlCount] = [];

            // Access the sub-array just created
            Control = Controls[ControlCount];

            // Read the properties from the child control into the control object
            readControlProperties(Control, PageDiv, i + 1);
            
            // Set the ControlCategory
            Control.ControlCategory = ControlCategory;

            // Add the control's methods
            addControlMethods(Control);
        }
    }
    return Controls;
}


function readColumns() {

    // Returns an array of all columns
    var Columns = [];
    var Column;

    // Get all of the DIV elements
    var Elements = document.getElementsByTagName('div');

    // Loop through all of the elements
    for (var i = 0; i < Elements.length; i++) {

        // Get the IsDragColumn attribute
        var attr = Elements[i].getAttribute('IsDragColumn');

        // Retrieve the elements differently if Opera
        if (IsOpera) {
            attr = Elements[i].IsDragColumn;
        }

        // Is this a drag column?
        if (attr === 'true') {

            // Get the current length of the array (index)
            var ColumnCount = Columns.length;

            // Add a new array item
            Columns[ColumnCount] = [];

            // Access the sub-array just created
            Column = Columns[ColumnCount];

            // Set the properties
            readControlProperties(Column, Elements[i], ColumnCount + 1);

            // Hard code the control type (normally read from the frame) and category
            Column.ControlType = gjb.e.ControlType.Column;
            Column.ControlCategory = gjb.e.ControlCategory.Column;

            // Add methods
            addControlMethods(Column);

            // Special: Height. Does this column have any children?
            // Column.Height = Elements[i].offsetHeight - 0;   
            // var Parent = Elements[i];
            // var CalcHeight = 0;
            // var Child;

            // for (var j = 0; j < Parent.childNodes.length; j++) {
            //     Child = Parent.childNodes[j];
            //     CalcHeight += Child.offsetHeight;
            // }

            // If we got a calculated height, store it.
            // if (CalcHeight !== 0) {
            //    Column.Height = CalcHeight;
            // }

        } // if 
    } // for
    return Columns;
}
function readColumnControls(Columns) {

    var Controls = [];
    var Control;
    var Element;
    var DragGroup;
    var Column;

    // Loop through each column
    for (var i = 0; i < Columns.length; i++) {

        // Get the column HTML object from the column object
        Column = Columns[i].Obj;

        // Loop through the children of the column object
        for (var j = 0; j < Column.childNodes.length; j++) {

            // Get the child node
            Element = Column.childNodes[j];

            try {
                DragGroup = extractNumber(Element.getAttribute('DragGroup'));

                // Is this a content box?
                if (DragGroup === gjb.e.DragGroup.ContentBox) {

                    // Yes.  Store the control properties
                    var ControlCount = Controls.length;

                    // Add a new array item
                    Controls[ControlCount] = [];

                    // Access the sub-array just created
                    Control = Controls[ControlCount];

                    // Read the properties from the child control into the control object
                    readControlProperties(Control, Element, i + 1);

                    // Set the category
                    Control.ControlCategory = gjb.e.ControlCategory.ColumnControl;
                    
                    // Add the control's methods
                    addControlMethods(Control);
                }
            }
            catch (e) {
                // alert(Control.toString)
            }
        }
    }
    return Controls;
}

function isDraft() {

    var hfIsDraft = $('hfIsDraft');
    var IsDraft = false;
    if (hfIsDraft !== null) {
        if (parseInt(hfIsDraft.value, 10) === 1) {
            IsDraft = true;
        }
        else {
            IsDraft = false;
        }
    }
    return IsDraft;  // parseInt(getCookie('ck_IsDraft'), 10) === 1;
}

function getControlTypeName(ControlType) {

    var ControlTypeName;
    ControlTypeName = 'Unknown';

    switch (ControlType) {
        case gjb.e.ControlType.RssSimple:
            ControlTypeName = 'RSS Feed';
            break;

        case gjb.e.ControlType.Editor:
            ControlTypeName = 'Article';
            break;

        case gjb.e.ControlType.ArticleList:
            ControlTypeName = 'Article List';
            break;

        case gjb.e.ControlType.EventList:
            ControlTypeName = 'Event List';
            break;

        case gjb.e.ControlType.Section:
            ControlTypeName = 'Section';
            break;
            
        case gjb.e.ControlType.Page:
            ControlTypeName = 'Page';
            break;
    }

    return ControlTypeName;
}

function getControlChain(Control, Delimiter, UseOffsetWidth) {

    var ContentChain = '';
    var UseWidth;
    var UseStyle;
    
    if (UseOffsetWidth === true) {
        UseWidth = Control.OffsetWidth;
    }
    else {    
        UseWidth = Control.Width;
    }
    
    var IsTextDirty = 0;
    if (Control.Text !== Control.OriginalText) {
        IsTextDirty = 1;
    }
    
    // Concatenate the properties, separate with the delimiter
    // Property List
    ContentChain += Control.ControlType + Delimiter + 
                    Control.ControlID + Delimiter + 
                    Control.ControlSubType + Delimiter + 
                    Control.ColumnIndex + Delimiter + 
                    UseWidth + Delimiter + 
                    Control.IsFloating + Delimiter +
                    Control.Rows + Delimiter +
                    Control.Text + Delimiter +
                    Control.ArticleID + Delimiter +
                    IsTextDirty + Delimiter + 
                    Control.ArticleUseSummary + Delimiter +
                    Control.ArticleUseImage + Delimiter +
                    Control.ArticleImageScale + Delimiter +
                    Control.ArticleUseComments + Delimiter +
                    Control.FilterID + Delimiter + 
                    Control.ArticleUseTopStory +
                    '~';
    return ContentChain;
}

function serializeColumns(Columns, Delimiter) {

    // Initialize the ContentChain
    var ContentChain = '';

    // Loop through the columns and concatenate the values
    for (var i = 0; i < Columns.length; i++) {

        // Get teach column
        var Column = Columns[i];
        
        // Concatenate the properties, separate with the delimiter
        ContentChain += getControlChain(Column, Delimiter, true);
    }
    return ContentChain;
}

function serializeControls(Controls, Delimiter) {

    // Initialize the ContentChain
    var ContentChain = '';

    // Loop through the columns and concatenate the values
    for (var i = 0; i < Controls.length; i++) {
    
        var Control = Controls[i];
    
        // Concatenate the properties, separate with the delimiter
        ContentChain += getControlChain(Control, Delimiter, false); 
    }
    return ContentChain;
}

function getFloatingColumnIndex(Columns) {

    // Assume no floating column.
    // This is 1-bound, NOT zero bound
    var FloatingColumnIndex = -1;

    // Loop through the columns and concatenate the values
    for (var i = 0; i < Columns.length; i++) {

        var Column = Columns[i];
        
        if (Column.IsFloating === true) {
            FloatingColumnIndex = i + 1;
            break;
        } 
    }
    return FloatingColumnIndex;
}

function webService_SavePage(ContentChain, RefreshOption) {
    PageMethods.PM_SavePage(ContentChain, RefreshOption, OnSuccess, OnFailed);
}

var Page = {
    Delimiter: '|',
    MouseDownX: 0,
    MouseDownY: 0,
    
    Advertisement: function() {
    
        // Loop through the COLUMN CONTROLS.  If a control of type advertisement is found, return it.
        for (var k = 0; k < this.ColumnControls.length; k++) {
            var ColumnControl = this.ColumnControls[k];
            if (ColumnControl.ControlType === gjb.e.ControlType.Advertisement) {
                return ColumnControl;
            }
        }
        // Still here?
        return null;
    },

    Read: function() {
        this.Sections = readSections(gjb.e.ControlCategory.Sections);
        this.Pages = readPages(gjb.e.ControlCategory.Pages);
        this.Columns = readColumns();
        this.ColumnControls = readColumnControls(this.Columns);
        this.FloatingColumnIndex = getFloatingColumnIndex(this.Columns);
    },
    RepositionColumnControls: function() {

        // Re-read the column controls and the columns
        this.ColumnControls = readColumnControls(this.Columns);

    },
    RepositionSections: function() {

        // Re-read the sections
        this.Sections = readSections(gjb.e.ControlCategory.Sections);

    },
    RepositionPages: function() {

        // Re-read the Pages
        this.Pages = readPages(gjb.e.ControlCategory.Pages);

    },
    Save: function(RefreshOption) {

        if (SaveRequired === true) {

            // Hide the status
            showStatus('Saving changes...');

            // Serialize the control data into a string
            var ContentChain = this.ToString();
            webService_SavePage(ContentChain, RefreshOption);

            // Save not required
            SaveRequired = false;
        }
    },
    ToString: function() {
        return serializeColumns(this.Columns, this.Delimiter) +
               serializeControls(this.ColumnControls, this.Delimiter);
    },
    
    ColumnControls: this.ColumnControls,
    
    ColumnIndex: -1,

    ControlCount: function() {
        return this.Columns.length + this.ColumnControls.length + this.Sections.length + this.Pages.length;
    },
    
    ControlByIndex: function(Index) {
        if (Index < this.Sections.length) {
            return this.Sections[Index];
        }
        else if (Index < this.Sections.length + this.Pages.length) {
            return this.Pages[Index - this.Sections.length];
        }
        else if (Index < this.Sections.length + this.Pages.length + this.Columns.length) {
            return this.Columns[Index - this.Sections.length - this.Pages.length];
        }
        else if (Index < this.Sections.length + this.Pages.length + this.Columns.length + this.ColumnControls.length) {
            return this.ColumnControls[Index - this.Sections.length - this.Pages.length - this.Columns.length];
        }
        else {
            return null;
        }
    },

    Controls: function(SearchID) {

        // Return null if no SearchID
        if (SearchID.length === 0) {
            return null;
        }

        // Loop through the COLUMNS
        for (var j = 0; j < this.Columns.length; j++) {
            var Column = this.Columns[j];
            if (Column.Obj.id === SearchID || Column.ControlID === SearchID) {
                return Column;
            }
        }

        // Loop through the COLUMN CONTROLS.  If a matching ID is found, return it.
        for (var k = 0; k < this.ColumnControls.length; k++) {
            var ColumnControl = this.ColumnControls[k];
            if (ColumnControl.Obj.id === SearchID || ColumnControl.ControlID === SearchID) {
                return ColumnControl;
            }
        }
        
        // Loop through the SECTIONS.  If a matching ID is found, return it.
        for (var m = 0; m < this.Sections.length; m++) {
            var Section = this.Sections[m];
            if (Section.Obj.id === SearchID || Section.ControlID === SearchID) {
                return Section;
            }
        }
        
        // Loop through the PAGES.  If a matching ID is found, return it.
        for (var n = 0; n < this.Pages.length; n++) {
            var Page = this.Pages[n];
            if (Page.Obj.id === SearchID || Page.ControlID === SearchID) {
                return Page;
            }
        }


        // Still here?  Control not found
        return null;
    },

    SetMouseTarget: function(Target) {

        // Switch the target if this is a label (inside an outside frame)
        if (extractNumber(Target.getAttribute('ControlType')) === gjb.e.ControlType.LabelChild ||
            extractNumber(Target.getAttribute('ControlType')) === gjb.e.ControlType.ContentTop ||
            extractNumber(Target.getAttribute('ControlType')) === gjb.e.ControlType.SectionDragHandle ||
            extractNumber(Target.getAttribute('ControlType')) === gjb.e.ControlType.PageDragHandle) {

            // Use the parent element as the mouse target
            this.MouseTarget = $(Target.getAttribute('ParentID'));
            
            // Store the DragHandle
            this.DragHandle = Target;
        }
        else {
            // Use the element itself
            this.MouseTarget = Target;
        }

        // Set the User Action, DragGoup, and ControlType
        this.MouseTarget.UserAction = extractNumber(this.MouseTarget.getAttribute('UserAction'));
        this.MouseTarget.DragGroup = extractNumber(this.MouseTarget.getAttribute('DragGroup'));
        this.MouseTarget.ControlType = extractNumber(this.MouseTarget.getAttribute('ControlType'));
        
        // Show status
        // showStatus('Mouse down on ' + getControlTypeName(this.MouseTarget.ControlType));

        // If this is a draggable item, get the left and top position
        if (this.MouseTarget.DragGroup === gjb.e.DragGroup.ContentBox || 
            this.MouseTarget.DragGroup === gjb.e.DragGroup.Section ||
            this.MouseTarget.DragGroup === gjb.e.DragGroup.Page) {
            
            this.MouseTarget.AbsoluteX = getLeftPos(this.MouseTarget) / 1;
            this.MouseTarget.AbsoluteY = getTopPos(this.MouseTarget) / 1;
        }
        
        // Did we get a recognizable UserAction, ControlType, etc?
        if (this.MouseTarget.UserAction !== 0 || this.MouseTarget.DragGroup !== 0 || this.MouseTarget.ControlType !== 0) {
            // Recognizable Target
            return true;
        } 
        else {
            // Not recognizable target
            return false;
        }
    }
    
    // No comma after last one
};

// xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
// Drag and Drop
// xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
function reorderSections() {

    var Sections = readSections(gjb.e.ControlCategory.Sections);
    var Section;
    var SectionIDs = '';
    
    for (var i = 0; i < Sections.length; i++) {
    
        // Get each section
        Section = Sections[i];
    
        // Set its ordinal
        Section.setOrdinal([i + 1]);
        
        // Concatenate the string
        if (i!== (Sections.length - 1)) {
            // Not the last one
            SectionIDs = SectionIDs + Section.Obj.id + '|';
        }
        else {
            // Last one
            SectionIDs = SectionIDs + Section.Obj.id;
        }
    }
    
    // Save the Ordinals
    PageMethods.PM_UpdateSectionOrdinals(SectionIDs, gjb.e.RefreshOption.None, OnSuccess, OnFailed);
}

function reorderPages() {

    var Pages = readPages(gjb.e.ControlCategory.Pages);
    var ThisPage;
    var PageIDs = '';
    
    for (var i = 0; i < Pages.length; i++) {
    
        // Get each section
        ThisPage = Pages[i];
    
        // Set its ordinal
        ThisPage.setOrdinal([i + 1]);
        
        // Concatenate the string
        if (i!== (Pages.length - 1)) {
            // Not the last one
            PageIDs = PageIDs + ThisPage.Obj.id + '|';
        }
        else {
            // Last one
            PageIDs = PageIDs + ThisPage.Obj.id;
        }
    }
    
    // Save the Ordinals
    PageMethods.PM_UpdatePageOrdinals(PageIDs, gjb.e.RefreshOption.None, OnSuccess, OnFailed);    
}

function getLastChildElement(MatchDragGroup, ParentNode, StopAtFirstElement) {

    // Returns the last child of a parent object with matching DragGroup.  
    var LastChildElement = null;
    var TestChild;
    var ChildCount;
    var DragGroup = 0;
    var Children;
    
    // Do we have any child nodes?
    if (ParentNode.childNodes.length > 0) {
    
        // Yes.  Get the count of the children
        ChildCount = ParentNode.childNodes.length;
        Children = ParentNode.childNodes;
        
        // Loop through the child nodes
        for (var i = 0; i < ChildCount; i++) {
        
            TestChild = Children[i];
            try {
                
                // This may fail if not IE because of text nodes
                DragGroup = extractNumber(TestChild.getAttribute('DragGroup'));
                
                // If we're still here, it didn't fail.  Test for match
                if (DragGroup === MatchDragGroup) {
                    LastChildElement = TestChild;
                    
                    // Exit at first element?
                    if (StopAtFirstElement === true) {
                        return LastChildElement;
                    }
                }
                
            }
            catch (e) {
            }
        }
        // Return the last child
        return LastChildElement;
    }
    else {
        // No children
        return null;
    }
}


function getContentRectangleInstructions(MouseMoveX, MouseMoveY) {        

    // Called during mouse move for CONTENTS objects
    var refNorthLeft = 0;
	var refNorthRight = 0;
	var refNorthTop = 0;
	var refNorthBottom = 0;
	
	var refSouthLeft = 0;
	var refSouthRight = 0;
	var refSouthTop = 0;
	var refSouthBottom = 0;
	
    var ChildElement = null;
    var Column = null;
    var LastChildElement = null;
    
    var IsOverlap = false;
    
    // Step 1: Determine up or down direction
    // ======================================
    var UpDown = 'up';
    
    // Is the current mouse Y position greater than the stored position?
    if (MouseMoveY >= v_holdY) {
        UpDown = 'down';
    }
    
    // Store the new mouse move Y to the stored position for comparison when coming through again
    v_holdY = MouseMoveY;
    
	// Step 2: Determine which ContentBox represents the MouseTarget
	// =============================================================
	for (var i = 0; i < Page.ColumnControls.length; i++) {
	
	    // Get the individual control
	    ChildElement = Page.ColumnControls[i];
		
	    // Is this the dragged object?
        if (ChildElement.Obj === Page.MouseTarget) {
            break;
        }
    }
    
    // Step 3: Use the cursor position as 'where we are'
    // =================================================    
    var scrollTop = document.body.scrollTop ? document.body.scrollTop :
        document.documentElement.scrollTop;
    var scrollLeft = document.body.scrollLeft ? document.body.scrollLeft :
        document.documentElement.scrollLeft;
    
    dragXCenter = MouseMoveX + scrollLeft;
    dragYCenter = MouseMoveY + scrollTop;
    
    // Are we over the drag rectangle? (do nothing)
	var refRectangleLeft =  getLeftPos(DragRectangle);
	var refRectangleRight = refRectangleLeft + DragRectangle.offsetWidth;
	var refRectangleTop = getTopPos(DragRectangle);
	var refRectangleBottom = refRectangleTop + DragRectangle.offsetHeight;
	
	// Check for DragRectangle overlap
    if ((dragXCenter >= refRectangleLeft) && (dragXCenter <= refRectangleRight) && (dragYCenter >= refRectangleTop) && (dragYCenter <= refRectangleBottom)) {
        return ['noaction', null, 'no action -- over drag rectangle'];
    }
    
	// Step 4: Loop: Get the overlapping object
	// ========================================
	for (var j = 0; j < Page.ColumnControls.length; j++) {
	
	    // Get the Control
		ChildElement = Page.ColumnControls[j];
		
		// Skip to the next ChildElement if this is the one we're dragging
		if (ChildElement.Obj === Page.MouseTarget) {
		    continue;
		}
		
		refNorthLeft =  ChildElement.AbsoluteX;
		refNorthRight = ChildElement.AbsoluteX + ChildElement.OffsetWidth;
		refNorthTop = ChildElement.AbsoluteY;
		refNorthBottom = ChildElement.AbsoluteY + ChildElement.OffsetHeight/2;
		
		refSouthLeft =  ChildElement.AbsoluteX;
		refSouthRight = ChildElement.AbsoluteX + ChildElement.OffsetWidth;
		refSouthTop = ChildElement.AbsoluteY + ChildElement.OffsetHeight/2;
		refSouthBottom = ChildElement.AbsoluteY + ChildElement.OffsetHeight;
	    
	    // Assume no overlap
	    IsOverlap = false;
	    IsNorthOverlap = false;
	    IsSouthOverlap = false;
	    
	    // Check for 'North' overlap
	    if ((dragXCenter >= refNorthLeft) && (dragXCenter <= refNorthRight) && (dragYCenter >= refNorthTop) && (dragYCenter <= refNorthBottom)) {
	        IsOverlap = true;
	        IsNorthOverlap = true;
	        break;
	    }
	    
	    // Check for 'South' overlap
	    if ((dragXCenter >= refSouthLeft) && (dragXCenter <= refSouthRight) && (dragYCenter >= refSouthTop) && (dragYCenter <= refSouthBottom)) {
	        IsOverlap = true;
	        IsSouthOverlap = true;
	        break;
	    }
	}
	
    // Step 5:  Did we get an overlap?
    // ===============================
    var MatchDragGroup = extractNumber(ChildElement.Obj.getAttribute('DragGroup'));
    if (IsOverlap) {	    
    
    
        // Is this on the 'North' side?  
        if (IsNorthOverlap) {
            // Yes.  Insert drag rectangle above the overlapped element
            return ['object', Page.ColumnControls[j], 'North Side:' + dragYCenter];
        }
        
        // Is this on the 'South' side and the overlapped element is NOT the last element?
        LastChildElement = getLastChildElement(MatchDragGroup, ChildElement.Parent, false);
        var IsLastChildElement = (LastChildElement.id === ChildElement.Obj.id);
    
        // Not the last child element, south side.  Insert before next element.
        if (IsSouthOverlap && ! IsLastChildElement){
            return ['object', Page.ColumnControls[j + 1], 'South Side, Not Last:' + dragYCenter];
        }
        
        // Is this the 'South' side and the overlapped element IS the last element?
        if (IsSouthOverlap && IsLastChildElement){
            return ['append', ChildElement.Parent, 'South Side, Last Element:' + dragYCenter];
        }
	}
	else {
	
	    // Step 6: No overlap.  See if we're below the bottom of one of the columns
	    // ========================================================================
	    var ColIndex;
	    var DragCell;
        for (var k = 0;k < Page.Columns.length; k++) {
        
            Column = Page.Columns[k];
            
            ColIndex = k + 1;
            DragCell = $(ColIndex + '_dragCell');
            
            refLeft =  getLeftPos(DragCell);
	        refRight = refLeft + DragCell.offsetWidth;
	        refTop = getTopPos(DragCell);
	        refBottom = refTop + DragCell.offsetHeight;
		        
	        // Within the column (bottom not checked)?
            if ((dragXCenter >= refLeft) && (dragXCenter <= refRight) && 
                (dragYCenter >= refTop)) {
                return ['append', Column.Obj, 'append 2 -- no overlap, below top of column ']; 
            }
	    }
	    return ['noaction', null, 'no action -- at end'];
	}
}
function getSectionRectangleInstructions(MouseMoveX, MouseMoveY) {        

    // Called during mouse move for SECTION objects
    var refLeft = 0;
    var refTop = 0;
    var refBottom = 0;
    var refRight = 0;
    var Section = null;
    var LastChildElement = null;
    
    var IsOverlap = false;
    
    // Step 1: Determine up or down direction
    // ======================================
    var UpDown = 'up';
    
    // Is the current mouse Y position greater than the stored position?
    if (MouseMoveY >= v_holdY) {
        UpDown = 'down';
    }
    
    // Store the new mouse move Y to the stored position for comparison when coming through again
    v_holdY = MouseMoveY;
    
	// Step 2: Determine which Section represents the MouseTarget (being dragged)
	// ===========================================================================
	for (var i = 0; i < Page.Sections.length; i++) {
	
	    // Get the individual section
	    Section = Page.Sections[i];
		
	    // Is this the dragged object?
        if (Section.Obj === Page.MouseTarget) {
            break;
        }
    }
    
    // Step 3: Use the cursor position as 'where we are'
    // =================================================
    var scrollTop = document.body.scrollTop ? document.body.scrollTop :
        document.documentElement.scrollTop;
    var scrollLeft = document.body.scrollLeft ? document.body.scrollLeft :
        document.documentElement.scrollLeft;
    
    dragXCenter = MouseMoveX + scrollLeft;
    dragYCenter = MouseMoveY + scrollTop;
    
	// Step 4: Loop: Get the overlapping object
	// ========================================
	for (var j = 0; j < Page.Sections.length; j++) {
	
	    // Get the Control
		Section = Page.Sections[j];
		
		// Skip to the next Section if this is the one we're dragging
		if (Section.Obj === Page.MouseTarget) {
		    continue;
		}	
		
		// Get the absolute left, right, top, and bottom
		refLeft =  Section.AbsoluteX;
		refRight = Section.AbsoluteX + Section.OffsetWidth;
		refTop = Section.AbsoluteY;
		refBottom = Section.AbsoluteY + Section.OffsetHeight;
	    
	    // Assume no overlap
	    IsOverlap = false;
	    
	    // When this 'overlaps', forces insertion of rectangle box.  Consider height only
	    if ((dragYCenter >= refTop) && (dragYCenter <= refBottom)) {
	        IsOverlap = true;
	        break;
	    }
	}
	
    // Step 5:  Did we get an overlap?
    // ===============================
    var MatchDragGroup = extractNumber(Section.Obj.getAttribute('DragGroup'));
    if (IsOverlap) {	    
    
        // Get the last child the parent node
        LastChildElement = getLastChildElement(MatchDragGroup, Section.Parent, false);
    
	    // Are we moving down on the last sibling?
	    if (UpDown === 'down' && ((LastChildElement.id === Section.Obj.id) ||  
	      (LastChildElement.id === DragRectangle.id))) {

	        return ['append', Section.Parent, 'first append'];
	    }
	    else {
	        // Are we moving down on the first sibling?
	        if ((DragRectangle.parentNode !== Section.Obj.parentNode) && 
	             UpDown === 'down' && 
	             Section.Parent.firstChild === Section.Obj) {
	             
	            // Insert before this sibling
	            return ['object', Page.Sections[j], 'object 1'];
	            
	        }
	        else {
	            // Are we moving down?
	            if (UpDown === 'down') {
	                return ['object', Page.Sections[j + 1], 'object 2'];
	            }
	        }
	    }
	    
	    // Are we moving up?
	    if (UpDown === 'up') {
	        return ['object', Page.Sections[j], 'object 3'];
	    }
	}
	else {
	
	    return ['noaction', null, 'no action -- at end'];	
	}
}

function getPageRectangleInstructions(MouseMoveX, MouseMoveY) {        

    // Called during mouse move for PAGE objects
    var refLeft = 0;
    var refTop = 0;
    var refBottom = 0;
    var refRight = 0;
    
    var refWestLeft = 0;
    var refWestTop = 0;
    var refWestBottom = 0;
    var refWestRight = 0;
    
    var refEastLeft = 0;
    var refEastTop = 0;
    var refEastBottom = 0;
    var refEastRight = 0;
    
    var ChildElement = null;
    var LastChildElement = null;
    
    var OverlappedText = '';
    
    var IsOverlap = false;
    var IsWestOverlap = false;
    var IsEastOverlap = false;
    
	// Step 1: Determine which Section represents the MouseTarget (being dragged)
	// ===========================================================================
	for (var i = 0; i < Page.Pages.length; i++) {
	
	    // Get the individual Page
	    ChildElement = Page.Pages[i];
		
	    // Is this the dragged object?
        if (ChildElement.Obj === Page.MouseTarget) {
            break;
        }
    }
    
    // Step 2: Use the cursor position as 'where we are'
    // =================================================
    var scrollTop = document.body.scrollTop ? document.body.scrollTop :
        document.documentElement.scrollTop;
    var scrollLeft = document.body.scrollLeft ? document.body.scrollLeft :
        document.documentElement.scrollLeft;
    
    dragXCenter = MouseMoveX + scrollLeft;
    dragYCenter = MouseMoveY + scrollTop;
    
	// Step 3: Loop: Get the overlapping object
	// ========================================
	for (var j = 0; j < Page.Pages.length; j++) {
	
	    // Get the Control
		ChildElement = Page.Pages[j];
		
		// Skip to the next ChildElement if this is the one we're dragging
		if (ChildElement.Obj === Page.MouseTarget) {
		    continue;
		}	
		
		refWestLeft =  ChildElement.AbsoluteX;
		refWestRight = ChildElement.AbsoluteX + ChildElement.OffsetWidth / 2;
		refWestTop = ChildElement.AbsoluteY;
		refWestBottom = ChildElement.AbsoluteY + ChildElement.OffsetHeight;
		
		refEastLeft =  ChildElement.AbsoluteX  + ChildElement.OffsetWidth / 2;
		refEastRight = ChildElement.AbsoluteX + ChildElement.OffsetWidth;
		refEastTop = ChildElement.AbsoluteY;
		refEastBottom = ChildElement.AbsoluteY + ChildElement.OffsetHeight;
	    
	    // Assume no overlap
	    IsOverlap = false;
	    IsWestOverlap = false;
	    IsEastOverlap = false;
	    
	    // Check for 'West' overlap
	    if ((dragXCenter >= refWestLeft) && (dragXCenter <= refWestRight) && (dragYCenter >= refWestTop) && (dragYCenter <= refWestBottom)) {
	        OverlappedText = ChildElement.Text;
	        IsOverlap = true;
	        IsWestOverlap = true;
	        break;
	    }
	    
	    // Check for 'East' overlap
	    if ((dragXCenter >= refEastLeft) && (dragXCenter <= refEastRight) && (dragYCenter >= refEastTop) && (dragYCenter <= refEastBottom)) {
	        OverlappedText = ChildElement.Text;
	        IsOverlap = true;
	        IsEastOverlap = true;
	        break;
	    }
	}
	
    // Step 4:  Did we get an overlap?
    // ===============================
    var MatchDragGroup = extractNumber(ChildElement.Obj.getAttribute('DragGroup'));
    if (IsOverlap) {	    
    
        // Is this on the 'West' side?
        if (IsWestOverlap) {
            // Yes.  Insert drag rectangle before the overlapped element
            return ['object', Page.Pages[j], 'West Side:' + OverlappedText];
        }
        
        // Is this on the 'East' side and the overlapped element is NOT the last element?
        LastChildElement = getLastChildElement(MatchDragGroup, ChildElement.Parent, false);
        var IsLastChildElement = (LastChildElement.id === ChildElement.Obj.id);
    
        if (IsEastOverlap && ! IsLastChildElement){
            return ['object', Page.Pages[j + 1], 'East Side, Not Last:' + OverlappedText];
        }
        
        // Is this the 'East' side and the overlapped element IS the last element?
        if (IsEastOverlap && IsLastChildElement){
            return ['append', ChildElement.Parent, 'East Side, Last Element'];
        }
	}
	else {
	    return ['noaction', null, 'no action -- at end'];	
	}
}

function getWindowHeight() {
    var theHeight;
    
    if (window.innerHeight) {
        theHeight=window.innerHeight;
    }
    else if (document.documentElement && document.documentElement.clientHeight) {
        theHeight=document.documentElement.clientHeight;
    }
        else if (document.body) {
        theHeight=document.body.clientHeight;
    }
    else {
        theHeight = -1;
    }
    
    return theHeight;
}

var cancelScrolling = true;
function startScrollingDown() {

    var scrollAmount = 5;

    if (cancelScrolling) {
        return;
    }    
    
    // Scroll the window
    window.scrollBy(0, scrollAmount); 
    
    // Repeat
    setTimeout('startScrollingDown()', 100);
}

function stopScrolling() {
    cancelScrolling = true;
    return;
}

// xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
// Mouse Move
// xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
function OnMouseMove(e) {

    // This handler is set in onMoveNotCancelled()
    // IE may not pass the event object
    if (e === null || e === undefined) {
        e = window.event;
    }
    
    // Rename the e.clientX and Y to more meaningful names
    var MouseMoveX = e.clientX;
    var MouseMoveY = e.clientY;
    var newLeft = 0;
    var newTop = 0;
    var Instructions_; 
	var instructionObj;
	var help;
	var NewDestinationObj;
	var LastChildElement;
    
    if (Page.MouseTarget.DragGroup === gjb.e.DragGroup.ContentBox) {
        // This is the actual 'drag code'
        if (IsMove) {
        
            // Move the mouse target
            newLeft = (Page.MouseTarget.AbsoluteX - Page.MouseDownX + MouseMoveX);
            newTop = (Page.MouseTarget.AbsoluteY - Page.MouseDownY + MouseMoveY);
                     
            var windowHeight = getWindowHeight();
            
            // Are we near the bottom of the page?
            if (MouseMoveY >= windowHeight - 100) {
               
               // newTop = newTop + 5;
                cancelScrolling = false;
                startScrollingDown();            
            }
            else {
                stopScrolling();
            }

            // Move the mouse target            
            Page.MouseTarget.style.left = newLeft + 'px';
            Page.MouseTarget.style.top = newTop + 'px';
               
             
            // Move the drag rectangle
	        Instructions_ = getContentRectangleInstructions(MouseMoveX, MouseMoveY);
	        instruction = Instructions_[0];
	        instructionObj = Instructions_[1];
	        help = Instructions_[2];
	        
	        // What Instructions did we get?
	        if (instruction === 'object') {
	        
	            // 'object'.  Put the dragged object before it.
		        NewDestinationObj = instructionObj;
		        
		        // Is this not the object we're currently replacing?
		        if (CurDestinationObj !== NewDestinationObj) {
		        
			        CurDestinationObj = NewDestinationObj;
			        
			        // Set the drag rectangle's new width
			        DragRectangle.style.width = NewDestinationObj.Obj.clientWidth - 4 + 'px';
			        
			        // Insert the drag rectangle
			        NewDestinationObj.Obj.parentNode.insertBefore(DragRectangle, NewDestinationObj.Obj);
			     
			        // Reset tops and lefts
			        Page.RepositionColumnControls();
		        }
	        }
	        
            if (instruction === 'append') {
	            DestinationParent = instructionObj;
	            
	            // Set the drag rectangle's new width
	            DragRectangle.style.width = DestinationParent.clientWidth - 4 + 'px';
	            
	            // Append the drag rectangle to the appropriate parent
	            DestinationParent.appendChild(DragRectangle);
	            
	            // Reset tops and lefts
		        Page.RepositionColumnControls();
	        }	
	        
            // Show the help information
            // showStatus('Moving to (' + Page.MouseTarget.style.left + ', ' + Page.MouseTarget.style.top + ')');
        }
    }
    
    else if (Page.MouseTarget.DragGroup === gjb.e.DragGroup.Section) {
        
        // This is the actual 'drag code'
        if (IsMove) {

            // Left position doesn't change        
            newLeft = Page.MouseTarget.AbsoluteX; 
            newTop = (Page.MouseTarget.AbsoluteY - Page.MouseDownY + MouseMoveY);
         
            // Perform the actual move
            Page.MouseTarget.style.left = newLeft + 'px';
            Page.MouseTarget.style.top = newTop + 'px';

            // Get what we're supposed to do
	        Instructions_ = getSectionRectangleInstructions(MouseMoveX, MouseMoveY);
	        instruction = Instructions_[0];
	        instructionObj = Instructions_[1];
	        help = Instructions_[2];
	        
	        // showStatus( instruction)
	        
	        // What Instructions did we get?
	        if (instruction === 'object') {
	        
	            // 'object'.  Put the dragged object before it.
		        NewDestinationObj = instructionObj;
		        
                // Is this not the object we're currently replacing?
		        if (CurDestinationObj !== NewDestinationObj) {
		        
			        CurDestinationObj = NewDestinationObj;
			        
			        // Set the drag rectangle's new width
			        DragRectangle.style.width = NewDestinationObj.Obj.clientWidth - 4 + 'px';
			        
                    // Insert the drag rectangle
                    NewDestinationObj.Obj.parentNode.insertBefore(DragRectangle, NewDestinationObj.Obj);
			     
			        // Reset tops and lefts
			        Page.RepositionSections();
		        }
	        }

	        if (instruction === 'append') {
	            DestinationParent = instructionObj;
	            
	            // Get the last child the parent node
                LastChildElement = getLastChildElement(gjb.e.DragGroup.SectionNew, DestinationParent, false);
	            
	            // Set the drag rectangle's new width
	            DragRectangle.style.width = DestinationParent.clientWidth - 4 + 'px';
	            
	            // Append after the last object
                DestinationParent.insertBefore(DragRectangle, LastChildElement);

                // Reset tops and lefts
                Page.RepositionSections();
	        }	
        }
    }
    
    else if (Page.MouseTarget.DragGroup === gjb.e.DragGroup.Page) {
    
        // This is the actual 'drag code'
        if (IsMove) {

            // Both Left and Top position change
            newLeft = (Page.MouseTarget.AbsoluteX - Page.MouseDownX + MouseMoveX); 
            newTop = (Page.MouseTarget.AbsoluteY - Page.MouseDownY + MouseMoveY);
         
            // Perform the actual move
            Page.MouseTarget.style.left = newLeft + 'px';
            Page.MouseTarget.style.top = newTop + 'px';
            
            // Get what we're supposed to do
	        Instructions_ = getPageRectangleInstructions(MouseMoveX, MouseMoveY);
	        instruction = Instructions_[0];
	        instructionObj = Instructions_[1];
	        help = Instructions_[2];
	        
	        // What Instructions did we get?
	        if (instruction === 'object') {
	        
	            // 'object'.  Put the dragged object before it.
		        NewDestinationObj = instructionObj;
		        
                // Is this not the object we're currently replacing?
                if (CurDestinationObj !== NewDestinationObj) {
		        
			        CurDestinationObj = NewDestinationObj;
			        
			        // Insert the drag rectangle
			        NewDestinationObj.Obj.parentNode.insertBefore(DragRectangle, NewDestinationObj.Obj);
			     
			        // Reset tops and lefts
			        Page.RepositionPages();
		        }
	        }

	        if (instruction === 'append') {
	        
	            DestinationParent = instructionObj;
	        
	            // Get the '[New]' element last child the parent node
                LastChildElement = getLastChildElement(gjb.e.DragGroup.PageNew, DestinationParent, false);
	            
	            // Set the drag rectangle's new width
	            // DragRectangle.style.width = DestinationParent.clientWidth - 4 + 'px';
	            
	            // Append after the last object ('[New]')
                DestinationParent.insertBefore(DragRectangle, LastChildElement);

                // Reset tops and lefts
		        Page.RepositionPages();
	        }	
        }
    }
    
    else if (Page.MouseTarget.DragGroup === gjb.e.DragGroup.ContentColumn) {

        // Get the column associated with the drag
        var colIdx = extractNumber(Page.MouseTarget.id);

        // Get the floating column index
        var idxFloating = Page.FloatingColumnIndex;
        var dragCell;
        var newWidth;
        var Column;
        
        // Are we to the 'left' of the floating index?
        var idxAdjust;
        if (colIdx < idxFloating) {
            idxAdjust = colIdx;
            dragCell = $(idxAdjust + '_dragCell');
            newWidth = Math.max(v_elWidth + MouseMoveX - Page.MouseDownX, 10);
            // Note:  this set the 'width', NOT 'style.width'
            dragCell.width = newWidth + 'px';
            
        }
        else {
            idxAdjust = colIdx + 1;
            dragCell = $(idxAdjust + '_dragCell');
            newWidth = Math.max(v_elWidth + Page.MouseDownX - MouseMoveX, 10);
            dragCell.width = newWidth + 'px';
        }
    }
}

// xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
// Mouse Move Not Cancelled
// xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
function onMoveNotCancelled(MouseDownButton, WindowEvent) {

    // Could be cancelled in 'mouse up'
    if (IsCancelled === true) {
        return false;
    }

    // This is after the time.  Not a click, it's a move
    IsMove = true;
    
    // In IE, left click is 1, Firefox is 0
    if ((MouseDownButton === 1 && WindowEvent !== null || MouseDownButton === 0) && 
         Page.MouseTarget.DragGroup !== 0) {

        if (Page.MouseTarget.DragGroup === gjb.e.DragGroup.ContentBox) {
        
            // Change the class name of the DragRectangle
            DragRectangle.className = 'DragRectangleContent';
        
            // Set the height and width of the drag rectangle
            DragRectangle.style.height = Page.MouseTarget.clientHeight + 2 + 'px';
            DragRectangle.style.width = Page.MouseTarget.clientWidth - 4 + 'px';
            
            v_holdY = -1;
	    
            // Show the drag rectangle		    
            DragRectangle.style.display = 'block'; 
	    
	        // Append the rectangle to the correct parent
            Page.MouseTarget.parentNode.appendChild(DragRectangle);
	  
            // Place the rectangle immediately before the object being dragged to 'hold' it's place
            Page.MouseTarget.parentNode.insertBefore(DragRectangle, Page.MouseTarget);
            
            // Change the drag element's position to 'absolute' to remove from the flow 
            Page.MouseTarget.style.position = 'absolute';
            
            // And reposition it to its absolute position
            Page.MouseTarget.style.left = Page.MouseTarget.AbsoluteX + 'px';
            Page.MouseTarget.style.top = Page.MouseTarget.AbsoluteY + 'px';
            
            // Set the width of the drag element to width of parent column - margins
	        Page.MouseTarget.style.width = parseInt(Page.MouseTarget.parentNode.offsetWidth, 10) + 'px';
            // Page.MouseTarget.style.zIndex = 10000;
        }
        
        else if (Page.MouseTarget.DragGroup === gjb.e.DragGroup.Section) {
        
            // Change the class name of the DragRectangle
            DragRectangle.className = 'DragRectangleSections';
        
            // Set the height and width of the drag rectangle (frame is padded by 5 in style sheet)
            DragRectangle.style.height = Page.MouseTarget.clientHeight - 9 + 'px';
            DragRectangle.style.width = Page.MouseTarget.clientWidth  - 4 + 'px';
            
            v_holdY = -1;
	    
            // Show the drag rectangle		    
            DragRectangle.style.display = 'block'; 
	    
            // Append the rectangle to the correct parent
            Page.MouseTarget.parentNode.appendChild(DragRectangle);
	  
            // Place the rectangle immediately before the object being dragged to 'hold' it's place
            Page.MouseTarget.parentNode.insertBefore(DragRectangle, Page.MouseTarget);

            // Change the drag handle to the clenched fist (doesn't work)
            // document.body.style.cursor = 'url(Images/Fist.cur)';
            
            // Change the drag element's position to 'absolute' to remove from the flow 
            Page.MouseTarget.style.position = 'absolute';
            
            // And reposition it to its absolute position (Y Value only)
            Page.MouseTarget.style.left = Page.MouseTarget.AbsoluteX + 'px';
            Page.MouseTarget.style.top = Page.MouseTarget.AbsoluteY + 'px';
            
            //Page.MouseTarget.style.zIndex = 10000;
        }
        else if (Page.MouseTarget.DragGroup === gjb.e.DragGroup.Page) {
        
            // Change the class name of the DragRectangle
            DragRectangle.className = 'DragRectanglePages';
        
            // Set the height and width of the drag rectangle 
            DragRectangle.style.height = Page.MouseTarget.clientHeight - 2 + 'px';
            DragRectangle.style.width = Page.MouseTarget.clientWidth  - 2 + 'px';
            
            v_holdY = -1;
	    
            // Show the drag rectangle		    
            DragRectangle.style.display = 'block'; 
	    
            // Append the rectangle to the correct parent
            Page.MouseTarget.parentNode.appendChild(DragRectangle);
	  
            // Place the rectangle immediately before the object being dragged to 'hold' it's place
            Page.MouseTarget.parentNode.insertBefore(DragRectangle, Page.MouseTarget);

            // Change the drag element's position to 'absolute' to remove from the flow 
            Page.MouseTarget.style.position = 'absolute';
            
            // And reposition it to its absolute position (Y Value only)
            Page.MouseTarget.style.left = Page.MouseTarget.AbsoluteX + 'px';
            Page.MouseTarget.style.top = Page.MouseTarget.AbsoluteY + 'px';
            
            //Page.MouseTarget.style.zIndex = 10000;
        }
        
        else if (Page.MouseTarget.DragGroup === gjb.e.DragGroup.ContentColumn) {

            // Store the original width            
            var colIdx = extractNumber(Page.MouseTarget.id);
            var idxFloating = Page.FloatingColumnIndex;
            var idxAdjust;
            var dragCell;
            
            if (colIdx < idxFloating) {
                idxAdjust = colIdx;
                dragCell = $(idxAdjust + '_dragCell');
                v_elWidth = dragCell.clientWidth;
            }
            else {
                idxAdjust = colIdx + 1;
                dragCell = $(idxAdjust + '_dragCell');
                v_elWidth = dragCell.clientWidth;
            }
            
            
            // Set the background color the the dragged column
            Page.MouseTarget.className = 'colSliderDragged';
            
            // Pull down the slider image from the server and set it.  Pay delay price here, not on load
            Page.MouseTarget.style.backgroundImage = 'url(Images/SliderBar.gif)';
        }
        
        // Set the OnMouseMove event of the document
        document.onmousemove = OnMouseMove;
        
        // Cancel out any text selections
        document.body.focus();
        
        // Prevent IE from trying to drag image
        Page.MouseTarget.ondragstart = function () {
            return false; 
        };
    }
}

function isFalse() {
    return false;
}
function isTrue() {
    return true;
}

function disableTextSelection() {
    document.onselectstart = isFalse;
    document.onmousedown = isFalse;
    document.body.onmousedown = isFalse;
}

function enableTextSelection(){
    document.onselectstart = isTrue;
    document.body.onmousedown = isTrue;
    document.onmousedown = OnMouseDown;
}

function floatColumn(ColumnIndex) {

    var j;
    var DragCell;
    var NewWidth;

    // Set the floating flag for all columns to 'false'
    for (var i = 0 ; i < Page.Columns.length; i++) {
    
        var Column = Page.Columns[i];
        
        // Set the widths of all HTML table cells to the offsetWidth - 4 (borders x 2)
        j = i + 1;
        DragCell = $(j + '_dragCell');

        // Ensure that width is at least 10 pixels.
        NewWidth = Math.max(extractNumber(DragCell.offsetWidth) - 4, 10);
        
        DragCell.width = NewWidth + 'px';
        
        // Set the HTML object
        Column.Obj.setAttribute('IsFloating', 'false');
        
        // Set the COLUMN object
        Column.IsFloating = false;
    }
    
    // Float the current HTML table cell by clearing the width
    DragCell = $(ColumnIndex + '_dragCell');
    DragCell.width = '';
    
    // Get the current column
    var FloatingColumn = Page.Columns[ColumnIndex - 1]; 
    
    // Set the HTML object
    FloatingColumn.Obj.setAttribute('IsFloating', 'true');
    
    // Set the COLUMN object
    FloatingColumn.IsFloating = true;
    
    // Update the FloatingColumnIndex
    Page.FloatingColumnIndex = ColumnIndex;
    
}

function selectTwoColumn() {

    // If it's already two column, then exit
    if ($('roTwoColumn').checked === true) {
        return;
    }
    
    var DefaultWidth = '';
    
    // Check the input control
    $('roTwoColumn').checked = true;
    $('roThreeColumn').checked = false;
    
    // Get the existing columns
    var LeftColumn = $('1_dragCell');
    var MiddleColumn = $('2_dragCell');
    var MiddleColumnContent = $('2_divDragColumn');
    var MiddleColumnSlider = $('2_CS');
    var RightColumn = $('3_dragCell');
    var RightColumnSlider = $('3_CS');
    
    // Get the first child of the middle column
    var FirstChild = getLastChildElement(gjb.e.DragGroup.ContentBox, MiddleColumnContent, true);
    
    // Get all the children of the right panel and append them to the middle panel.
    var ColumnControls = Page.ColumnControls;
    
    // Go through each column control.  Append it to the last column.
    for (var i = 0; i < ColumnControls.length; i++) {

        // Get the control and its ID
        var ColumnControl = ColumnControls[i];
        var ColumnControlID = ColumnControl.Obj.id;
        DragGroup = extractNumber($(ColumnControlID).getAttribute('DragGroup'));
        
        // Is this a content box in the third column?
        if (DragGroup === gjb.e.DragGroup.ContentBox && ColumnControl.ColumnIndex === 3) {
        
            // Did we get a first child?
            if (FirstChild !== null) {
              ///  FirstChild.parentNode.insertBefore(FirstChild,);
              MiddleColumnContent.insertBefore($(ColumnControlID), FirstChild);
            }
            else {
                // Append to the second column
                MiddleColumnContent.appendChild($(ColumnControlID));
            }
        }
    }
    
    var CombinedColumnWidth = 0;
    
    // Set the new width of the first column to be the width of the old first and second columns.
    var LeftColumnWidth = extractNumber(LeftColumn.offsetWidth);
    var MiddleColumnWidth = extractNumber(MiddleColumn.offsetWidth);
    CombinedColumnWidth = LeftColumnWidth + MiddleColumnWidth + 'px';
    
    // Change the class name of the middle (soon to be right) column slider to invisible
    MiddleColumnSlider.className = 'colLastColumn';
    
    // Delete the third column and its slider
    RightColumn.parentNode.removeChild(RightColumn);
    RightColumnSlider.parentNode.removeChild(RightColumnSlider);
    
    // Reset width after removal
    LeftColumn.width = CombinedColumnWidth;
        
    // Re-read the page
    Page.Read();
    
     // Float the first column
    floatColumn(1);
    
    // Save the page
    SaveRequired = true;
    Page.Save(gjb.e.RefreshOption.None);
    
}

function selectThreeColumn() {

    // If it's already two column, then exit
    if ($('roThreeColumn').checked === true) {
        return;
    }

    // Check the input control
    $('roTwoColumn').checked = false;
    $('roThreeColumn').checked = true;

    var DefaultWidth = '300px';
    var pnlIndex = 3;
    
    // Get the content row
    var m_ContentRow = $('rowContent');
    
    // Content Cell
    var cellHtmlContent = m_ContentRow.insertCell(); 
    
    // Slider
    var cellHtmlSlider = m_ContentRow.insertCell(); 
    
    // 1. Set alignment
    cellHtmlContent.vAlign = 'top';
    
    // 2. Set the width
    cellHtmlContent.width = DefaultWidth;
    
    // 3. Set the color, class, drag group and column index
    // cellHtmlContent.BgColor = colColor
    cellHtmlContent.className = 'dragHTMLContainer';
    cellHtmlContent.setAttribute('DragGroup', gjb.e.DragGroup.ContentColumnContainer);
    cellHtmlContent.setAttribute('ColumnIndex', pnlIndex);
    
    // Content Panel
    var pnlContent = document.createElement('div');
    
    // 4.  Set the ID, dragColumn attribute, controlType attribute, class, IsFloating
    pnlContent.id = pnlIndex + '_divDragColumn';

    pnlContent.setAttribute('ColumnIndex', pnlIndex);
    pnlContent.setAttribute('IsDragColumn', 'true');
    // pnlContent.setAttributes.Add('ControlID', ControlID);
    pnlContent.setAttribute('ControlType', gjb.e.ControlType.Column);
    pnlContent.setAttribute('DragGroup', gjb.e.DragGroup.ContentColumnDiv);
    pnlContent.className = 'dragColumn';

    // IsFloating assumed to be false
    pnlContent.setAttribute('IsFloating', 'false');
    
    // 5. Set the ID of the drag column/cell
    cellHtmlContent.id = pnlIndex + '_dragCell';
    
    // 6.  Set the slider ID
    cellHtmlSlider.id = pnlIndex +  '_CS';
    
    // 7. This last column's class has no 'cursor' style attribute (but does have width)
    cellHtmlSlider.className = 'colLastColumn';
    
    // 8. Add the content div to the column
    cellHtmlContent.appendChild(pnlContent);

    // Change the class name of the previous slider
    var cellPreviousSlider = $('2_CS');
    cellPreviousSlider.style.cursor = 'w-resize';
    cellPreviousSlider.className = 'colSlider';
    cellPreviousSlider.setAttribute('DragGroup', gjb.e.DragGroup.ContentColumn);
    
    // Move the ad from the second column to the first column
    var Advertisement = Page.Advertisement();
    
    // Did we get an ad?
    if (Advertisement !== null) {
    
        // Append it to the new column
        var elemAdvertisement = $(Advertisement.Obj.id);
        pnlContent.appendChild(elemAdvertisement);
    }
    
    // Re-read the page
    Page.Read();
    
    // Float the second column
    floatColumn(2);
    
    // Save the page
    SaveRequired = true;
    Page.Save(gjb.e.RefreshOption.None);
}

// xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
// Mouse Down
// xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
function OnMouseDown(e) {

    // showStatus('is draft : ' + isDraft());
    
    // IE may not pass the event object
    if (e === null || e === undefined) {
        e = window.event;
    }
    
    // For Firefox -- turn off the default click/drag behavior
    // if (e.preventDefault) {  e.preventDefault(); }
   
    // IE uses srcElement, others use target
    var target = (e.target === null || e.target === undefined) ? e.srcElement : e.target;
    var MouseDownButton = e.button;
    var WindowEvent = window.event;
    
    // Get the drag rectangle
    DragRectangle = $('rectangle');
    
    // Read the page.  Refreshing using UpdatePanel causes parentNodes to be lost,
    // so re-read the page here to ensure all is working before move, append, etc.
    // You'll see the problem in dragging navigation.
    Page.Read();
  
    // Set the target element on the page (which sets its DragGroup, etc.)
    if (Page.SetMouseTarget(target) === true && isDraft()) {
    
        // Disable text selection
       disableTextSelection();
        
    }
    
    // If this is a radio button menu, have to perform the action before hiding the menu
    if (Page.MouseTarget.UserAction === gjb.e.UserAction.SelectTwoColumn) {
        selectTwoColumn();
    }
    else if (Page.MouseTarget.UserAction === gjb.e.UserAction.SelectThreeColumn) {
        selectThreeColumn();
    }
    
    // Set up the menus
    hideMenus();
    
    // Set IsCancelled to false, call the delay
    IsCancelled = false;
    IsMove = false;
            
    // Get the mouse position on the screen
    Page.MouseDownX = e.clientX;
    Page.MouseDownY = e.clientY;

    // Any draggable item, except content and drag handles
    if (isDraft()) {
        if (Page.MouseTarget.DragGroup > 0) {
        
            // Don't include the 'new' handles
            if ((Page.MouseTarget.UserAction !== gjb.e.UserAction.AddSection) && 
                (Page.MouseTarget.UserAction !== gjb.e.UserAction.AddPage)) {
            
                // Create closure to pass parameter in setTimeout
                var Delay = function() {
                    onMoveNotCancelled(MouseDownButton, WindowEvent);
                    MouseDownButton = null;
                    WindowEvent = null;
                };
                var MyTimeout = setTimeout(Delay, 0);
            }
        }
    }
    
    // Process the menu action, if any
    var MenuAction = extractNumber(target.getAttribute('UserAction'));
    processMenuFunction(MenuAction, target);
    
    // Prevent text selection (not IE)
    return true;
}

function deleteSection(UserAction, DeleteID) {

    // Get the ParentID out of the DeleteSection menu.  
    var ParentID = Page.MouseTarget.getAttribute('ParentID');
    
    // Get the control associated with this ID
    var Section = Page.Controls(ParentID);
    var SectionTitle = Section.Text;
    
    // Can't delete the first section
    if (Section.Ordinal === 1) {
        alert('Cannot delete the first section.');
        return;
    }
    
    var ConfirmMsg = 'Are you sure you want to delete the section called [' + SectionTitle + ']?  All pages below this section will also be deleted.';
    DeleteID = Page.Controls(ParentID).Obj.id;
    
    // Make sure the user really wants to delete
    if (confirm(ConfirmMsg)) {

        if (Page.MouseTarget !== null) {
            // Reset the page and submit the form
            refreshPage(UserAction, DeleteID);
        }
    }
}

function deletePage(UserAction, DeleteID) {

    // Get the ParentID out of the DeletePage menu.  
    var ParentID = Page.MouseTarget.getAttribute('ParentID');
    
    // Get the control associated with this ID
    var ThisPage = Page.Controls(ParentID);
    var PageTitle = ThisPage.Text;
    
    // Can't delete the first section
    if (ThisPage.Ordinal === 1) {
        alert('Cannot delete the first page.');
        return;
    }
    
    var ConfirmMsg = 'Are you sure you want to delete the page called [' + PageTitle + ']?';
    DeleteID = Page.Controls(ParentID).Obj.id;
    
    // Make sure the user really wants to delete
    if (confirm(ConfirmMsg)) {

        if (Page.MouseTarget !== null) {
            // Reset the page and submit the form
            refreshPage(UserAction, DeleteID);
        }
    }
}

function deleteControl() {

    // Get the ControlID
    var ControlID = Page.MouseTarget.getAttribute('ControlID');
    
    var ThisControl = Page.Controls(ControlID);
    var ThisControlObj = Page.Controls(ControlID).Obj;
    
    // Get the parent node
    var ThisParentObj = ThisControlObj.parentNode;

    // Did we get a control to delete?
    if (ThisParentObj === null || ThisControlObj === null) {
        // Couldn't find control to delete
        return;
    }

    // Still here?  Confirm the delete
    var DeleteMsg = 'Delete [' + ThisControl.Text + '] ?';
    if (! confirm(DeleteMsg)) {
        return;
    }

    // Remove the child from the parent
    ThisParentObj.removeChild(ThisControlObj);
   
    // Re-Read the page
    Page.Read();
    
    // Mark for saving and save
    SaveRequired = true;
    Page.Save(gjb.e.RefreshOption.None);
    return;
}

function addSection(UserAction) {

    var MessageText = 'Enter the name of the section';
    var PromptText = 'Section Name';
    var UserResponse = prompt(MessageText, PromptText);

    // If we got a response, then save and submit form
    if (UserResponse !== null)
    {
        refreshPage(UserAction, UserResponse);
    }
}

function addSite() {
    // Send to the 'AddSite' page
    window.location = 'frmNewSite.aspx'; 
}

function editSiteProfile() {
    // Refresh the page with the user action
    window.location = 'frmSiteEdit.aspx'; 
}

function OnSuccessAddFavorite() {
}

function addFavorite() {
    PageMethods.PM_AddFavorite(OnSuccessAddFavorite);
}

function addPage(UserAction) {

    var MessageText = 'Enter the name of the page';
    var PromptText = 'Page Name';
    var UserResponse = prompt(MessageText, PromptText);

    // If we got a response, then save and submint form
    if (UserResponse !== null)
    {
        refreshPage(UserAction, UserResponse);
    }
}
   
function ChangeLocation(value) {
    // Called on the click event of the site or shortcut
    window.location = value;
}

function setActiveStyleSheet(title) {
    var i, a, main;
    for(i=0; (a = document.getElementsByTagName('link')[i]); i++) {
    
        if(a.getAttribute('rel').indexOf('style') != -1 && a.getAttribute('title')) {
            a.disabled = true;
        }
            
       if(a.getAttribute('title') == title) {
        a.disabled = false;
        }
    }
}


function changeTheme() {

    // Note: The Theme Display ID is stored in the id of the menu option
    var ThemeTitle = $(Page.MouseTarget.id).getAttribute('title');

    // Change to this style sheet
    setActiveStyleSheet(ThemeTitle);
    
    // Call the 'SaveTheme' page method.  Refresh page if successful
    PageMethods.PM_SaveTheme(Page.MouseTarget.id, gjb.e.RefreshOption.None, OnSuccess, OnFailed);
    
}

function dontSave() {
    if (confirm('Discard Changes?')) {
        
        // Use the page method to publish the draft
       PageMethods.PM_DontSave(gjb.e.RefreshOption.None, OnSuccess, OnFailed);
        
        // Set the IsDraft to false
        $('hfIsDraft').value = '0';
        
        // Get the page ID from the attribute
        var VersionID = Page.MouseTarget.getAttribute('VersionID');

        // Create the location with the VersionID
        var NewLocation = 'Default.aspx?VersionID=' + VersionID;
        window.location = (NewLocation);
        
    }
}

function finishLater() {
        
    // Set the IsDraft to false
    $('hfIsDraft').value = '0';
    
    // Get the page ID from the attribute
    var VersionID = Page.MouseTarget.getAttribute('VersionID');

    // Create the location with the VersionID
    var NewLocation = 'Default.aspx?VersionID=' + VersionID;
    window.location = (NewLocation);
        
}

function onSuccessDeleteFavorite() {

    // Get the current control. Make sure it's a favorite
    if (Page.MouseTarget !== null) {

        // Get the current site ID
        var SiteID = getCookie('OurLocalPaperSiteID');
        var FavoriteSiteID = '';

        // If this isn't null
        if (SiteID === null) {
            return;
        }

        // Get the Favorites list
        var blFavorites = $('blFavorites');

        // Loop through and try to find the matching site ID
        if (blFavorites === null) {
            return;
        }
            
        // Still here?  Find matching node
        var blListItems = blFavorites.getElementsByTagName('li');
        for (var i = 0; i < blListItems.length; i++) {

            FavoriteSiteID = blListItems[i].getAttribute('SiteID');
            
            if (SiteID === FavoriteSiteID) {
                blFavorites.removeChild(blListItems[i]);
                var MatchFound = true;
                break;
            }
        }
    }
}

function deleteFavorite() {

    if (confirm('Are you sure you want to delete this favorite?'))   {
        if (Page.MouseTarget !== null) {
            
            // Delete the favorite
            PageMethods.PM_DeleteFavorite(onSuccessDeleteFavorite);
        }
    }
}


function makeControlFinish(ControlType, ArticleID) {
    
    // Create the new control
    var newDiv = document.createElement('div');
    newDiv.setAttribute('id', 'newDiv');
    newDiv.setAttribute('ControlType', ControlType);
    newDiv.setAttribute('olpSubType', Page.MouseTarget.getAttribute('olpSubType'));

    // Set the number of rows if RSS
    if (ControlType === gjb.e.ControlType.RssSimple) {
        newDiv.setAttribute('rows', '5');
    }
    
    // Set the article ID if this is an Editor
    if (ControlType === gjb.e.ControlType.Editor) {
    
        // Did we get an ArticleID?
        if (ArticleID.length !== 0) {
            newDiv.setAttribute('ArticleID', ArticleID);
        }
        else {
            // Did not get an ArticleID.  Exit so a blank article does not get added.
            return;
        }
    }
    
    newDiv.setAttribute('DragGroup', gjb.e.DragGroup.ContentBox);
    newDiv.setAttribute('class', 'dragContentBoxNew');
    newDiv.setAttribute('className', 'dragContentBoxNew');
    
    // Add line feeds to give it height
    newDiv.innerHTML = '<br />' + '<br />' + '<br />';
    
    // Get the left column content
    var LeftColumnContent = $('1_divDragColumn');
    var ControlAdded = false;
    
    // Get the first child of the left column
    var FirstChild = getLastChildElement(gjb.e.DragGroup.ContentBox, LeftColumnContent, true);
    
    // Get all the children of the right panel and append them to the middle panel.
    var ColumnControls = Page.ColumnControls;
    
    // Go through each column control.  Append it to the last column.
    for (var i = 0; i < ColumnControls.length; i++) {

        // Get the control and its ID
        var ColumnControl = ColumnControls[i];
        var ColumnControlID = ColumnControl.Obj.id;
        DragGroup = extractNumber($(ColumnControlID).getAttribute('DragGroup'));
        
        // Is this a content box?
        if (DragGroup === gjb.e.DragGroup.ContentBox && ColumnControl.ColumnIndex === 1) {
        
            // Did we get a first child?
            if (FirstChild !== null) {
                // Append before the first child
                LeftColumnContent.insertBefore(newDiv, FirstChild);
                ControlAdded = true;
                break;
            }
        }
    }
    
    // Did a control get added?
    if (ControlAdded === false) {
        // No controls in this column.  Append to the column.
        LeftColumnContent.appendChild(newDiv);
    }
    
    // Reload the page objects and save;
    Page.Read();
    SaveRequired = true;
    
    // Refresh contents
    Page.Save(gjb.e.RefreshOption.Content);
    //Page.Save(gjb.e.RefreshOption.Page);
}

function browseArticles(isFirstTime) {

    var width = 900;
    var height = 600;
    var iLeft = 190;
    var iTop = 140;
    var url;

    var sOptions = 'toolbar=no,status=no,resizable=yes,dependent=yes,scrollbars=yes';
    sOptions += ',width=' + width;
    sOptions += ',height=' + height;
    sOptions += ',left=' + iLeft;
    sOptions += ',top=' + iTop;

    // If this is first time, just get the ArticleID
    if (isFirstTime) {

        url = 'frmArticlesPopup.aspx';
        window.open(url, 'BrowseArticles', sOptions);

    }
    else {
    
        // The ID of the 'Close' button is stored in the import link.
        var CloseEditLinkID= Page.MouseTarget.getAttribute('CloseEditLinkID');
        url = 'frmArticlesPopup.aspx?CloseEditLinkID=' + CloseEditLinkID;
        window.open(url, 'BrowseArticles', sOptions);
    }
}

function makeControlStart() {

    // See if this is an Aricle
    var ControlType = Page.MouseTarget.ControlType;
    
    if (ControlType === gjb.e.ControlType.Editor) {
    
        // It's an editor.  Ask which article to import.
        browseArticles(true);
    
    }
    else {
    
        // Not an editor.  Finish making the control.
        makeControlFinish(ControlType, '');
    }
    
}
function navigateToSubdomain() {

    // Get the subdomain from the attribute
    var Subdomain = Page.MouseTarget.getAttribute('Subdomain');
    var NewLocation = Subdomain;
    window.location = (NewLocation);
}

function publishDraft() {    

    // Make sure the user really wants to delete
    if (confirm('Are you sure you want to publish this version?'))
    {
        // Use the page method to publish the draft
        PageMethods.PM_PublishDraft(gjb.e.RefreshOption.Page, OnSuccess, OnFailed);

        // Set the IsDraft to false
        $('hfIsDraft').value = '0';
    }
}

function renamePage()
{
    // Get the ParentID from the mouse target (stored in configure menu)
    var ParentID = Page.MouseTarget.getAttribute('ParentID');
    
    var MessageText = 'Enter the name of the page';
    var PromptText = Page.Controls(ParentID).Text;
    var UserResponse = prompt(MessageText, PromptText);

    // Store the text in the control. Page is Saved in setText() method.
    Page.Controls(ParentID).setText(UserResponse);
}

function renameSection()
{
    // Get the ParentID from the mouse target (stored in configure menu)
    var ParentID = Page.MouseTarget.getAttribute('ParentID');
    
    var MessageText = 'Enter the name of the section';
    var PromptText = Page.Controls(ParentID).Text;
    var UserResponse = prompt(MessageText, PromptText);

    // Store the text in the control. Page is Saved in setText() method.
    Page.Controls(ParentID).setText(UserResponse);
}

function selectColumns() {
    moveMenu(true, 'pnlColumns', 'lbColumns', 0, 20);
}

function toggleHiddenPageLabel(IsHidden) {

    // Get the ID of the actual input control (not this label)
    var chkHiddenPageID = Page.MouseTarget.getAttribute('InputHiddenPageID');

    // Check the input control or not
    $(chkHiddenPageID).checked = IsHidden;

    // Call the webservice to update the IsHiddenFlag
    PageMethods.PM_UpdatePageIsHidden(IsHidden, gjb.e.RefreshOption.None, OnSuccess, OnFailed);

}

function toggleHiddenPageInput(IsHidden) {

    // Toggle the check box
    Page.MouseTarget.checked = IsHidden;

    // Call the webservice to update the IsHiddenFlag
    PageMethods.PM_UpdatePageIsHidden(IsHidden, gjb.e.RefreshOption.None, OnSuccess, OnFailed);
}

function selectRSS() {
    moveMenu(true, 'pnlRSS', 'lbRSS', 0, 20);
}

function selectThemes() {
    moveMenu(true, 'pnlThemes', 'lbThemes', 0, 20);
}    

function selectTools() {
    moveMenu(true, 'pnlElements', 'lbElements', 0, 20);
}

function importDraft(UserAction) {
    // Get the reference ID from the newly-selected item
    if (confirm('Are you sure?  This will OVER-WRITE this version with the one you are importing.  Continue?')) {
        var SavedRefID = Page.MouseTarget.getAttribute('RefID');
        refreshPage(UserAction, SavedRefID);
    }
}

function editorCancel(UserAction) {

    // Make sure the user wants to cancel
    if (confirm('Quit without saving?') === false) {
        return;
    }
    
    var HoldDesignID = Page.MouseTarget.getAttribute('HoldDesignID');
    var HoldPreviewID = Page.MouseTarget.getAttribute('HoldPreviewID');

    // Copy the text from the designer to the preview
    var EditorDesignID = Page.MouseTarget.getAttribute('EditorDesignID');
    var EditorPreviewID = Page.MouseTarget.getAttribute('EditorPreviewID');

    // Get the instance of the editor object to retrieve text
    var oEditor = FCKeditorAPI.GetInstance(EditorDesignID);

    // Copy the text FROM the preview div TO the FckEditor instance
    var SaveText = $(EditorPreviewID).innerHTML;
    oEditor.SetHTML(SaveText);
    
    // Show the preview, hide the designer    
    $(HoldDesignID).style.display = 'none';
    $(HoldPreviewID).style.display = 'block';

    var CloseEditLinkID = Page.MouseTarget.getAttribute('CloseEditLinkID');
    var EditLinkID = Page.MouseTarget.getAttribute('EditLinkID');
    
    $(CloseEditLinkID).style.display = 'none';
    $(EditLinkID).style.display = 'block';
}

function refocusEditor(EditorDesignID) {
   
    var oEditor = FCKeditorAPI.GetInstance(EditorDesignID);
    oEditor.Focus();
    
}

function editorToggleToolbar(UserAction) {

    // Get the checked status of the mousetarget (it lags, so flip value)
    var Checked = !Page.MouseTarget.checked;

    // If checked, show toolbar.  If not, collapse toolbar
    var EditorDesignID = Page.MouseTarget.getAttribute('EditorDesignID');
    var oEditor = FCKeditorAPI.GetInstance(EditorDesignID);

    if (Checked) {
        oEditor.ToolbarSet.Expand();
    }
    else {
        oEditor.ToolbarSet.Collapse();

        // Hide the collapse handle
        oEditor.EditorWindow.parent.document.getElementById('xCollapseHandle').style.display = 'none';
        oEditor.EditorWindow.parent.document.getElementById('xExpandHandle').style.display = 'none';
    }

    // Set the focus (forces resize of height)
    var DQ = String.fromCharCode(34);
    setTimeout('refocusEditor(' + dq + EditorDesignID +DQ  + ');', 250);
    
}

function editorToggleSummary(UserAction) {

    // Get the checked status of the mousetarget (it lags, so flip value)
    var Checked = !Page.MouseTarget.checked;

    // If checked, show toolbar.  If not, collapse toolbar
    var SummaryDivID = Page.MouseTarget.getAttribute('SummaryDivID');
    var divSummary = $(SummaryDivID);

    if (divSummary.style.display === 'block') {
        divSummary.style.display = 'none';
    }
    else {
        divSummary.style.display = 'block';
    }
}
function getImageAttr(ImageTag, Attr) {

    // Look for the tag inside
    var DQ = String.fromCharCode(34);
    var ExpandedAttr = Attr + '=' + DQ;
    var StartAttrPos = ImageTag.indexOf(ExpandedAttr);

    // Did we find the attribute?
    if (StartAttrPos === -1) {
        return '';
    }

    // Get the rest of string after the start of the attribute
    var ImageTagPlusRest = ImageTag.substring(StartAttrPos + ExpandedAttr.length, ImageTag.length);

    // Look for the closing quote
    var EndAttrPos = ImageTagPlusRest.indexOf(DQ);

    // If we couldn't find a closing quote, exit
    if (EndAttrPos === -1) {
        return '';
    }

    // We've got the beginning and the end... return the attribute
    var strImageAttr = ImageTagPlusRest.substr(0, EndAttrPos);
    return strImageAttr;
}

function createImageTag(OriginalImageTag, ImageHeight, ImageWidth, ImageSrc, ScalePercent) {

    // Exit if no scale percent
    if (ScalePercent === 0) {
        return OriginalImageTag;
    }

    // Exit if retrieved height or width is zero
    if (parseInt(ImageHeight, 10) === 0 || parseInt(ImageWidth, 10) === 0) {
        return OriginalImageTag;
    }

    // Exit if retrieved src has no length
    if (ImageSrc.length === 0) {
        return OriginalImageTag;
    }

    // Concatenate to create the new image tag
    var DQ = String.fromCharCode(34);
    var SP = ' ';
    var NewHeight = parseInt((ImageHeight * ScalePercent) / 100, 10);
    var NewWidth = parseInt((ImageWidth * ScalePercent) / 100, 10);

    var NewImageTag = '<img height=' + DQ + NewHeight + DQ + SP +
                              'width=' + DQ + NewWidth + DQ + SP +
                              'alt=' + DQ + SP +
                              'src=' + DQ + ImageSrc + DQ + SP +
                              '/>';
    return NewImageTag;
}

function getDivSummaryHTML(ScaledImageTag, SummaryText) {

    var DQ = String.fromCharCode(34);
    var divHTML = '<div class=' + DQ + 'divArticleImage' + DQ + '>' +
                          ScaledImageTag +
                          '</div>' +
                          '<div class=' + DQ + 'divArticleSummary' + DQ + '>' +
                          SummaryText +
                          '</div>';

    return divHTML;
}

function getImageTag(HTMLText) {

    // Look for an image tag in the HTML
    var StartTagPos = HTMLText.indexOf('<img');

    // If we didn't get a position, return an empty string
    if (StartTagPos === -1) {
        return '';
    }

    // Get the rest of the string after the image tag
    var strImageTagPlusRest = HTMLText.substring(StartTagPos, HTMLText.length);

    // Find the closing tag of the after image tag
    var EndTagPos = strImageTagPlusRest.indexOf('/>');

    // If we couldn't find a closing tag, exit
    if (EndTagPos === -1) {
        return '';
    }

    // Get just the image tag itself
    var strImageTag = strImageTagPlusRest.substr(0, EndTagPos + 2);

    // Still here?
    return strImageTag;
}

function getLinkHTML(ArticleID) {

    var DQ = String.fromCharCode(34);
    var LinkHTML = '<a href=' + DQ + 'Default.aspx?ArticleID=' +
                   ArticleID + DQ + '>More</a>';

    return LinkHTML;
}

function getSummaryHTML(HTMLText, SummaryText, ScalePercent, ArticleID) {

    // Get the image tag
    var ImageTag = getImageTag(HTMLText);

    // Get the height from the image tag
    var ImageHeight = getImageAttr(ImageTag, 'height');
    var ImageWidth = getImageAttr(ImageTag, 'width');
    var ImageSrc = getImageAttr(ImageTag, 'src');

    // Get the image tab with scale
    var ScaledImageTag = createImageTag(ImageTag, ImageHeight, ImageWidth, ImageSrc, ScalePercent);

    // Create the link
    var MoreLinkHTML = getLinkHTML(ArticleID);

    // Create the Summary HTML (Text + Link)
    var SummaryHTML = SummaryText + '&nbsp;' + MoreLinkHTML;

    // Create the 'div' text
    return getDivSummaryHTML(ScaledImageTag, SummaryHTML);

}

function SetUserValues(UserID, FullName) {

    // Get the controls to store the UserID and the User's FullName
    var hfUserID = $('hfUserID');
    var hfAuthor = $('hfAuthor');
    var txtAuthor = $('txtAuthor');

    // Replace the values with the imported data
    hfUserID.value = UserID;
    hfAuthor.value = FullName;
    txtAuthor.value = FullName;
}

function SetArticleValues(ArticleID, Headline) {
    
    // This was called because MakeControlStart asked for an Editor to be
    // created, which launched browseArticles(), which called here after
    // .frmArticlesPopup was close.
    
    // Returning with the ArticleID
    makeControlFinish(gjb.e.ControlType.Editor, ArticleID);
}

function SetImportArticleValues(ArticleID, Headline, Summary, Author, HTMLText, IsHidden, CloseEditLinkID) {

    // Make sure the user really wants to import the article
    // if (confirm('Are you sure you want to import this article?') === false) {
    //     return;
    // }

    var eCloseEditLink = $(CloseEditLinkID);

    // Get the IDs of the field elements to replace
    var EditorHeadlineID = eCloseEditLink.getAttribute('EditorHeadlineID');
    var EditorSummaryID = eCloseEditLink.getAttribute('EditorSummaryID');
    var EditorAuthorID = eCloseEditLink.getAttribute('EditorAuthorID');
    var EditorDesignID = eCloseEditLink.getAttribute('EditorDesignID');
    var EditorIsHiddenID = eCloseEditLink.getAttribute('EditorIsHiddenID');    
    var ControlID = eCloseEditLink.getAttribute('ControlID');

    // Replace the values with the imported data
    $(EditorHeadlineID).value = Headline;
    $(EditorSummaryID).value = Summary;
    $(EditorAuthorID).value = Author;
    $(EditorIsHiddenID).checked = strToBool(IsHidden);

    // Get the instance of the editor object
    var oEditor = FCKeditorAPI.GetInstance(EditorDesignID);
    
    // Set the new text
    oEditor.SetHTML(HTMLText);

    // Get the old article ID to delete if it's blank
    var OldArticleID = Page.Controls(ControlID).ArticleID;

    // Store the Article ID into the control
    Page.Controls(ControlID).setArticleID(ArticleID);

    // Store the Article ID into the close edit link
    eCloseEditLink.setAttribute('ArticleID', ArticleID);

    // Delete the old article if it was blank
    PageMethods.PM_DeleteBlankArticle(OldArticleID, gjb.e.RefreshOption.None, OnSuccess, OnFailed);
}

function browseUsers() {

    // The ID of the 'Close' button is stored in the import link.
    var CloseEditLinkID = Page.MouseTarget.getAttribute('CloseEditLinkID');

    var width = 900;
    var height = 600;
    var iLeft = 190;
    var iTop = 140;

    var sOptions = 'toolbar=no,status=no,resizable=yes,dependent=yes,scrollbars=yes';
    sOptions += ',width=' + width;
    sOptions += ',height=' + height;
    sOptions += ',left=' + iLeft;
    sOptions += ',top=' + iTop;

    //var url = '../../../frmArticlesPopup.aspx';
    var url = 'frmUsersPopup.aspx?CloseEditLinkID=' + CloseEditLinkID;
    window.open(url, 'BrowseUsers', sOptions);
}

function editorSelectPreview(UserAction) {

    var HoldDesignID = Page.MouseTarget.getAttribute('HoldDesignID');
    var HoldPreviewID = Page.MouseTarget.getAttribute('HoldPreviewID');

    // Copy the text from the designer to the preview
    var EditorDesignID = Page.MouseTarget.getAttribute('EditorDesignID');
    var EditorPreviewID = Page.MouseTarget.getAttribute('EditorPreviewID');
    var EditorHeadlineID = Page.MouseTarget.getAttribute('EditorHeadlineID');
    var EditorIsHiddenID = Page.MouseTarget.getAttribute('EditorIsHiddenID');
    var EditorSummaryID = Page.MouseTarget.getAttribute('EditorSummaryID');
    var EditorAuthorID = Page.MouseTarget.getAttribute('EditorAuthorID');
    var EditorUseSummaryID = Page.MouseTarget.getAttribute('EditorUseSummaryID');
    var EditorUseImageID = Page.MouseTarget.getAttribute('EditorUseImageID');
    var EditorImageScaleID = Page.MouseTarget.getAttribute('EditorImageScaleID');
    var EditorUseCommentsID = Page.MouseTarget.getAttribute('EditorUseCommentsID');

    var ControlID = Page.MouseTarget.getAttribute('ControlID');

    // Get the instance of the editor object to retrieve text
    var oEditor = FCKeditorAPI.GetInstance(EditorDesignID);

    // Copy the text to the preview div from the FckEditor instance
    var HeadlineText = $(EditorHeadlineID).value;
    var SummaryText = $(EditorSummaryID).value;
    var AuthorText = $(EditorAuthorID).value;

    var IsHidden = $(EditorIsHiddenID).checked;
    var UseSummary = $(EditorUseSummaryID).checked;
    var UseImage = $(EditorUseImageID).checked;
    var ImageScale = $(EditorImageScaleID).value;
    var UseComments = $(EditorUseCommentsID).checked;
    
    var SaveText = oEditor.GetXHTML(true);
    var ArticleID = Page.MouseTarget.getAttribute('ArticleID');

    // Generate the Summary HTML
    var SummaryHTML = getSummaryHTML(SaveText, SummaryText, ImageScale, ArticleID);

    // Set the .innerHTML of the preview window
    if (UseSummary) {
        $(EditorPreviewID).innerHTML = SummaryHTML;
    }
    else {
        $(EditorPreviewID).innerHTML = SaveText;
    }


    // Show the preview, hide the designer    
    $(HoldDesignID).style.display = 'none';
    $(HoldPreviewID).style.display = 'block';

    // Show the 'Edit' link, hide the 'Close Edit' link
    var MyID = Page.MouseTarget.id;
    var EditLinkID = Page.MouseTarget.getAttribute('EditLinkID');
    $(MyID).style.display = 'none';
    $(EditLinkID).style.display = 'block';

    // Call the page method to save the article text if is changed
    // if (oEditor.IsDirty()) {
    PageMethods.PM_EditorSave(ArticleID, SaveText, HeadlineText, SummaryText, AuthorText,IsHidden, gjb.e.RefreshOption.None, OnSuccess, OnFailed);
    oEditor.ResetIsDirty();
    //}


    // Set the headline and other control-related properties
    Page.Controls(ControlID).setText(HeadlineText);
    Page.Controls(ControlID).setArticleUseSummary(UseSummary);
    Page.Controls(ControlID).setArticleUseImage(UseImage);
    Page.Controls(ControlID).setArticleImageScale(ImageScale);
    Page.Controls(ControlID).setArticleUseComments(UseComments);

    // Save the control-related values
    SaveRequired = true;
    Page.Save(gjb.e.RefreshOption.None);
}

function resetEditorDirectory(WithAlert, ArticleID) {

    // Set the refresh option depending on whether 'WithAlert' was passed
    var ThisRefreshOption;
    if (WithAlert === true) {
        ThisRefreshOption = gjb.e.RefreshOption.Alert;
    }
    else {
        ThisRefreshOption = gjb.e.RefreshOption.None;
    }

    // Reset the editor directory
    PageMethods.PM_ResetEditorDirectory(ThisRefreshOption, ArticleID, OnSuccess, OnFailed);

}

function isAnyEditorOpen(DisplayMessage) {

    // Go through the bulleted list
    var LinkButtons = document.getElementsByTagName('a');

    // Is this 'close editor' link
    for (var i = 0; i < LinkButtons.length; i++) {

        var LinkButton = LinkButtons[i];

        // Is this the 'Close' link on the editor?
        if ((parseInt(LinkButton.getAttribute('UserAction'), 10) === gjb.e.UserAction.EditorSelectPreview ||
              parseInt(LinkButton.getAttribute('UserAction'), 10) === gjb.e.UserAction.ArticleListClose ||
              parseInt(LinkButton.getAttribute('UserAction'), 10) === gjb.e.UserAction.TaskListClose ||
              parseInt(LinkButton.getAttribute('UserAction'), 10) === gjb.e.UserAction.EventListClose) &&
              LinkButton.style.display === 'block') {

            if (DisplayMessage) {
                alert('You have an editor open already.  Please close that editor before opening this one.');
            }
            return true;
        }
    }
    return false;
}

function keepSessionAlive(ArticleID) {
    
    var DQ = String.fromCharCode(34);
    
    if (isArticleEditorOpen()) {

        // Wait and check again
        var strRepeat = 'keepSessionAlive(' + DQ + ArticleID + DQ + ');';
        setTimeout(strRepeat, 2000);
        showStatus('Polling server at ... ' + getTime() + strRepeat);

        // Set the userfiles directory for FckEditor using webservice
        resetEditorDirectory(false, ArticleID);
    }
    else {
        showStatus('Editor closed at ...' + getTime());
        setTimeout('showStatus(' + DQ + DQ + ')', 3000);
        return;
    }
}

function editorSelectDesign(UserAction) {

    // Only one editor can be open at once
    if (isAnyEditorOpen(true)) {
        return;
    }

    // Get the article ID from the link
    var ArticleID = Page.MouseTarget.getAttribute('ArticleID');

    // Reset the editor directory (since session variable may get lost)
    resetEditorDirectory(false, ArticleID);

    // Show the designer, hide the preview
    var HoldDesignID = Page.MouseTarget.getAttribute('HoldDesignID');
    var HoldPreviewID = Page.MouseTarget.getAttribute('HoldPreviewID');

    // Show the 'Close Edit' link, hide the 'Edit' link
    var MyID = Page.MouseTarget.id;
    var CloseEditLinkID = Page.MouseTarget.getAttribute('CloseEditLinkID');
    $(MyID).style.display = 'none';
    $(CloseEditLinkID).style.display = 'block';
    
    // Get the instance of the editor object and set its fcus
    var EditorDesignID = Page.MouseTarget.getAttribute('EditorDesignID');
    var oEditor = FCKeditorAPI.GetInstance(EditorDesignID);

    // Swap windows relatively late ... or cursor gets lost on design window
    $(HoldPreviewID).style.display = 'none';
    $(HoldDesignID).style.display = 'block';

    oEditor.Focus();

    // Call the web service to keep the session active so it doesn't time out.
    keepSessionAlive(ArticleID);

}

function articleListClose() {

    // Hide the 'design' panel
    var pnlArticleListDesignID = Page.MouseTarget.getAttribute('pnlArticleListDesignID');
    var hfFilterID_ID = Page.MouseTarget.getAttribute('hfFilterID_ID');
    var hfRowsID = Page.MouseTarget.getAttribute('hfRowsID');
    var HeadlineID = Page.MouseTarget.getAttribute('HeadlineID');
    var RowsID = Page.MouseTarget.getAttribute('RowsID');
    var UseSummaryID = Page.MouseTarget.getAttribute('UseSummaryID');
    var UseTopStoryID = Page.MouseTarget.getAttribute('UseTopStoryID');
    
    $(pnlArticleListDesignID).style.display = 'none';

    // Copy the text from the designer to the preview
    var ddlArticleListFiltersID = Page.MouseTarget.getAttribute('ddlArticleListFiltersID');
    var ControlID = Page.MouseTarget.getAttribute('ControlID');

    // Get the values for the headline, rows, and use summary
    var Headline = $(HeadlineID).value;
    var UseSummary = $(UseSummaryID).checked;
    var UseTopStory = $(UseTopStoryID).checked;
    var Rows = $(RowsID).value;

    // Get the FilterID from the control
    var FilterID = $(ddlArticleListFiltersID).value;

    // Show the 'Edit' link, hide the 'Close Edit' link
    var MyID = Page.MouseTarget.id;
    var EditLinkID = Page.MouseTarget.getAttribute('EditLinkID');
    $(MyID).style.display = 'none';
    $(EditLinkID).style.display = 'block';

    // Store the Filter ID into the control
    Page.Controls(ControlID).setFilterID(FilterID);

    // Store the other values to the control
    Page.Controls(ControlID).setText(Headline);
    Page.Controls(ControlID).setArticleUseSummary(UseSummary);
    Page.Controls(ControlID).setArticleUseTopStory(UseTopStory);
    Page.Controls(ControlID).setRows(Rows);

    // Store the value the control's hidden field
    $(hfFilterID_ID).value = FilterID;
    $(hfRowsID).value = Rows;

    // Save the page
    SavedControlID = ControlID;
    SaveRequired = true;
    Page.Save(gjb.e.RefreshOption.Control);
}

function articleListEdit() {

    // Only one editor can be open at once
    if (isAnyEditorOpen(true)) {
        return;
    }

    // Show the 'design' panel which holds the filter list
    var pnlArticleListDesignID = Page.MouseTarget.getAttribute('pnlArticleListDesignID');
    $(pnlArticleListDesignID).style.display = 'block';

    // Show the 'Close Edit' link, hide the 'Edit' link
    var MyID = Page.MouseTarget.id;
    var CloseEditLinkID = Page.MouseTarget.getAttribute('CloseEditLinkID');
    $(MyID).style.display = 'none';
    $(CloseEditLinkID).style.display = 'block';
}

function taskListEdit() {

    // Only one editor can be open at once
    if (isAnyEditorOpen(true)) {
        return;
    }

    // Show the 'design' panel which holds the filter list
    var pnlTaskListDesignID = Page.MouseTarget.getAttribute('pnlTaskListDesignID');
    $(pnlTaskListDesignID).style.display = 'block';

    // Show the 'Close Edit' link, hide the 'Edit' link
    var MyID = Page.MouseTarget.id;
    var CloseEditLinkID = Page.MouseTarget.getAttribute('CloseEditLinkID');
    $(MyID).style.display = 'none';
    $(CloseEditLinkID).style.display = 'block';
}

function taskListClose() {

    // Hide the 'design' panel
    var pnlTaskListDesignID = Page.MouseTarget.getAttribute('pnlTaskListDesignID');
    var hfFilterID_ID = Page.MouseTarget.getAttribute('hfFilterID_ID');
    var hfRowsID = Page.MouseTarget.getAttribute('hfRowsID');
    var TaskTitleID = Page.MouseTarget.getAttribute('TaskTitleID');
    var RowsID = Page.MouseTarget.getAttribute('RowsID');
    var UseSummaryID = Page.MouseTarget.getAttribute('UseSummaryID');
    var UseTopStoryID = Page.MouseTarget.getAttribute('UseTopStoryID');
    
    $(pnlTaskListDesignID).style.display = 'none';

    // Copy the text from the designer to the preview
    var ddlTaskListFiltersID = Page.MouseTarget.getAttribute('ddlTaskListFiltersID');
    var ControlID = Page.MouseTarget.getAttribute('ControlID');

    // Get the values for the TaskTitle, rows, and use summary
    var TaskTitle = $(TaskTitleID).value;
    var UseSummary = $(UseSummaryID).checked;
    var UseTopStory = $(UseTopStoryID).checked;
    var Rows = $(RowsID).value;

    // Get the FilterID from the control
    var FilterID = $(ddlTaskListFiltersID).value;

    // Show the 'Edit' link, hide the 'Close Edit' link
    var MyID = Page.MouseTarget.id;
    var EditLinkID = Page.MouseTarget.getAttribute('EditLinkID');
    $(MyID).style.display = 'none';
    $(EditLinkID).style.display = 'block';

    // Store the Filter ID into the control
    Page.Controls(ControlID).setFilterID(FilterID);

    // Store the other values to the control
    Page.Controls(ControlID).setText(TaskTitle);
    Page.Controls(ControlID).setArticleUseSummary(UseSummary);
    Page.Controls(ControlID).setArticleUseTopStory(UseTopStory);
    Page.Controls(ControlID).setRows(Rows);

    // Store the value the control's hidden field
    $(hfFilterID_ID).value = FilterID;
    $(hfRowsID).value = Rows;

    // Save the page
    SavedControlID = ControlID;
    SaveRequired = true;
    Page.Save(gjb.e.RefreshOption.Control);
}

function eventListClose() {

    // Hide the 'design' panel
    var pnlEventListDesignID = Page.MouseTarget.getAttribute('pnlEventListDesignID');
    var hfFilterID_ID = Page.MouseTarget.getAttribute('hfFilterID_ID');
    var hfRowsID = Page.MouseTarget.getAttribute('hfRowsID');
    var HeadlineID = Page.MouseTarget.getAttribute('HeadlineID');
    var RowsID = Page.MouseTarget.getAttribute('RowsID');
    var UseSummaryID = Page.MouseTarget.getAttribute('UseSummaryID');
    
    $(pnlEventListDesignID).style.display = 'none';

    // Copy the text from the designer to the preview
    var ddlEventListFiltersID = Page.MouseTarget.getAttribute('ddlEventListFiltersID');
    var ControlID = Page.MouseTarget.getAttribute('ControlID');

    // Get the values for the headline, rows, and use summary
    var Headline = $(HeadlineID).value;
    var UseSummary = $(UseSummaryID).checked;
    var Rows = $(RowsID).value;

    // Get the FilterID from the control
    var FilterID = $(ddlEventListFiltersID).value;

    // Show the 'Edit' link, hide the 'Close Edit' link
    var MyID = Page.MouseTarget.id;
    var EditLinkID = Page.MouseTarget.getAttribute('EditLinkID');
    $(MyID).style.display = 'none';
    $(EditLinkID).style.display = 'block';

    // Store the Event ID into the control
    Page.Controls(ControlID).setFilterID(FilterID);

    // Store the other values to the control
    Page.Controls(ControlID).setText(Headline);
    Page.Controls(ControlID).setArticleUseSummary(UseSummary);
    Page.Controls(ControlID).setRows(Rows);

    // Store the value the control's hidden field
    $(hfFilterID_ID).value = FilterID;
    $(hfRowsID).value = Rows;

    // Save the page
    SaveRequired = true;
    Page.Save(gjb.e.RefreshOption.None);

}

function eventListEdit() {

    // Only one editor can be open at once
    if (isAnyEditorOpen(true)) {
        return;
    }

    // Show the 'design' panel which holds the filter list
    var pnlEventListDesignID = Page.MouseTarget.getAttribute('pnlEventListDesignID');
    $(pnlEventListDesignID).style.display = 'block';

    // Show the 'Close Edit' link, hide the 'Edit' link
    var MyID = Page.MouseTarget.id;
    var CloseEditLinkID = Page.MouseTarget.getAttribute('CloseEditLinkID');
    $(MyID).style.display = 'none';
    $(CloseEditLinkID).style.display = 'block';
}

function userListEdit() {

    // Only one editor can be open at once
    if (isAnyEditorOpen(true)) {
        return;
    }

    // Show the 'design' panel which holds the filter list
    var pnlUserListDesignID = Page.MouseTarget.getAttribute('pnlUserListDesignID');
    $(pnlUserListDesignID).style.display = 'block';

    // Show the 'Close Edit' link, hide the 'Edit' link
    var MyID = Page.MouseTarget.id;
    var CloseEditLinkID = Page.MouseTarget.getAttribute('CloseEditLinkID');
    $(MyID).style.display = 'none';
    $(CloseEditLinkID).style.display = 'block';
}

function userListClose() {

    // Hide the 'design' panel
    var pnlUserListDesignID = Page.MouseTarget.getAttribute('pnlUserListDesignID');
    var hfFilterID_ID = Page.MouseTarget.getAttribute('hfFilterID_ID');
    var hfRowsID = Page.MouseTarget.getAttribute('hfRowsID');
    var HeadlineID = Page.MouseTarget.getAttribute('HeadlineID');
    var RowsID = Page.MouseTarget.getAttribute('RowsID');
    
    $(pnlUserListDesignID).style.display = 'none';

    // Copy the text from the designer to the preview
    var ddlUserListFiltersID = Page.MouseTarget.getAttribute('ddlUserListFiltersID');
    var ControlID = Page.MouseTarget.getAttribute('ControlID');

    // Get the values for the headline, rows
    var Headline = $(HeadlineID).value;
    var Rows = $(RowsID).value;

    // Get the FilterID from the control
    var FilterID = $(ddlUserListFiltersID).value;

    // Show the 'Edit' link, hide the 'Close Edit' link
    var MyID = Page.MouseTarget.id;
    var EditLinkID = Page.MouseTarget.getAttribute('EditLinkID');
    $(MyID).style.display = 'none';
    $(EditLinkID).style.display = 'block';

    // Store the Filter ID into the control
    Page.Controls(ControlID).setFilterID(FilterID);

    // Store the other values to the control
    Page.Controls(ControlID).setText(Headline);
    Page.Controls(ControlID).setRows(Rows);

    // Store the value the control's hidden field
    $(hfFilterID_ID).value = FilterID;
    $(hfRowsID).value = Rows;

    // Save the page
    SavedControlID = ControlID;
    SaveRequired = true;
    Page.Save(gjb.e.RefreshOption.Control);
}


function showMenu(e, MenuID, xOffset, yOffset) {

    // Get the menu
    var divMenu = $(MenuID);

    // Don't reshow the menu if it's already on
    if (divMenu.style.display === 'block') {
        return;
    }
    
    // document.body.scrollTop does not work in IE
    var scrollTop = document.body.scrollTop ? document.body.scrollTop :
        document.documentElement.scrollTop;
    var scrollLeft = document.body.scrollLeft ? document.body.scrollLeft :
        document.documentElement.scrollLeft;
        
    // Hide and then show the menu to avoid 'up and over'
    divMenu.style.display = 'none';
    divMenu.style.left = e.clientX + scrollLeft + xOffset + 'px';
    divMenu.style.top = e.clientY + scrollTop + yOffset + 'px';
    divMenu.style.display = 'block';
 
    // Store the ref ID (for deletion, renaming, etc.)
    SavedRefID = Page.MouseTarget.getAttribute('RefID');
    return false;
}

function configureSectionMenu() {

    // Store the ParentIDs in each item
    $('lblRenameSection').setAttribute('ParentID', Page.MouseTarget.getAttribute('ParentID'));
    $('lblDeleteSection').setAttribute('ParentID', Page.MouseTarget.getAttribute('ParentID'));
}

function configurePageMenu() {

    // Store the ParentIDs in each item
    $('lblRenamePage').setAttribute('ParentID', Page.MouseTarget.getAttribute('ParentID'));
    $('lblDeletePage').setAttribute('ParentID', Page.MouseTarget.getAttribute('ParentID'));
}

function getTime() {

    var curtime = new Date();
    var curhour = curtime.getHours();
    var curmin = curtime.getMinutes();
    var cursec = curtime.getSeconds();
    var time = '';

    if (curhour === 0) {
        curhour = 12;
    }
    
    time = (curhour > 12 ? curhour - 12 : curhour) + ':' +
     (curmin < 10 ? '0' : '') + curmin + ':' +
     (cursec < 10 ? '0' : '') + cursec + ' ' +
     (curhour > 12 ? 'PM' : 'AM');

    return time;
}

function isArticleEditorOpen() {

    // Go through the bulleted list
    var LinkButtons = document.getElementsByTagName('a');

    // Is this 'close editor' link
    for (var i = 0; i < LinkButtons.length; i++) {

        var LinkButton = LinkButtons[i];

        // Is this the 'Close' link on the editor?
        if (LinkButton.getAttribute('UserAction') === '44' && LinkButton.style.display === 'block') {
            return true;
        }
    }
    return false;
}

function rssAddTo(UserAction) {

    // Find all of the matching anchors for this list
    //var ListID = Page.MouseTarget.getAttribute('AssociatedListUID');
    var ControlID = Page.MouseTarget.getAttribute('ControlID');
    var Anchors = document.getElementsByTagName('a');
    var j = 0;
    var MatchFound = false;

    // Go through all the anchors
    for (var i = 0; i < Anchors.length; i++) {

        var Anchor = Anchors[i];
        var AnchorControlID = Anchor.getAttribute('ControlID');
        var RssIndex = extractNumber(Anchor.getAttribute('RssIndex'));

        // Does this match our list?
        if ( AnchorControlID === ControlID && RssIndex > 0) {

            j = j + 1;

            // Is this a hidden anchor?
            if (Anchor.style.display === 'none') {
                Anchor.style.display = 'block';
                MatchFound = true;
                break;
            }
        }
    }

    // Did we find a match?
    if (MatchFound === true) {

        // Call the web service to save the new ordinal values
        PageMethods.PM_UpdateRssRowCount(ControlID, j, gjb.e.RefreshOption.None, OnSuccess, OnFailed);
    }
}

function rssSubtractFrom(UserAction) {
   
    // Find all of the matching anchors for this list
    var ControlID = Page.MouseTarget.getAttribute('ControlID');
    var Anchors = document.getElementsByTagName('a');
    var LastVisibleAnchor = null;
    var MatchFound = false;
    var j = 0;

    // Go through all the anchors
    for (var i = 0; i < Anchors.length; i++) {

        var Anchor = Anchors[i];
        var AnchorControlID = Anchor.getAttribute('ControlID');
        var RssIndex = extractNumber(Anchor.getAttribute('RssIndex'));

        // Does this match our list?
        if (AnchorControlID === ControlID && RssIndex > 0) {
        
            // Is this a hidden anchor?
            if (Anchor.style.display === 'block') {
                j = j + 1;
                LastVisibleAnchor = Anchor;
                MatchFound = true;
            }
        }
    }
    
    // Did he have a list visible anchor?  If so, hide it.
    if (LastVisibleAnchor !== null) {
        LastVisibleAnchor.style.display = 'none';
    }

    // Save
    if (MatchFound === true) {

        var SaveCount = j - 1;
        
        // Call the web service to save the new ordinal values
        PageMethods.PM_UpdateRssRowCount(ControlID, SaveCount, gjb.e.RefreshOption.None, OnSuccess, OnFailed);
    }
}

// xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
// During Mouse Up
// xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
function finishContentDrop() {

    // Append the MouseTarget before drag rectangle
    DragRectangle.parentNode.insertBefore(Page.MouseTarget, DragRectangle);
    
    // Reset the properties of the drag object
	if (Page.MouseTarget) {
		// Page.MouseTarget.style.cursor = 'move';
		Page.MouseTarget.style.position = 'static';
		Page.MouseTarget.style.width = '';
		Page.MouseTarget.style.left = '';
		Page.MouseTarget.style.top = '';
	}
    
    
    // Hide the drag rectangle 
	DragRectangle.style.display = 'none';
	Page.RepositionColumnControls();
	return;
	
}

function finishSectionDrop() {

    // Insert dragged section before the drag rectangle
    if (CurDestinationObj !== undefined) {
        CurDestinationObj.Obj.parentNode.insertBefore(Page.MouseTarget, DragRectangle);
    }
	
	// Reset the properties of the drag object
	if (Page.MouseTarget) {
		// Page.MouseTarget.style.cursor = 'move';
		Page.MouseTarget.style.position = 'static';
		Page.MouseTarget.style.width = '';
		Page.MouseTarget.style.left = '';
		Page.MouseTarget.style.top = '';
	}

	// Hide the drag rectangle 
	DragRectangle.style.display = 'none';
	Page.RepositionSections();
}

function finishPageDrop() {

    // Insert dragged section before the drag rectangle
    if (CurDestinationObj !== undefined) {
        CurDestinationObj.Obj.parentNode.insertBefore(Page.MouseTarget, DragRectangle);
    }
	
	// Reset the properties of the drag object
	if (Page.MouseTarget) {
		// Page.MouseTarget.style.cursor = 'move';
		Page.MouseTarget.style.position = 'static';
		Page.MouseTarget.style.width = '';
		Page.MouseTarget.style.left = '';
		Page.MouseTarget.style.top = '';
	}

	// Hide the drag rectangle 
	DragRectangle.style.display = 'none';
	Page.RepositionSections();
}

function getFormName() {

    var PathName = window.location.pathname;
    var SlashPos = PathName.lastIndexOf('/');
    var FrmName = PathName.substr(SlashPos + 1, PathName.length - SlashPos - 1);

    return FrmName;

}

function processFunction(e) {

    if (Page.MouseTarget === undefined) {
        return;
    }
    
    var UserAction = extractNumber(Page.MouseTarget.getAttribute('UserAction'));

    switch (UserAction) {
    case gjb.e.UserAction.AddControl: 
        makeControlStart();
        break;
    
    case gjb.e.UserAction.AddSection:
        addSection(UserAction);
        break;
    case gjb.e.UserAction.AddPage:
        addPage(UserAction);
        break;
        
    case gjb.e.UserAction.AddFavorite:
        addFavorite();
        break;
    case gjb.e.UserAction.AddSite:
        addSite();
        break;
        
    case gjb.e.UserAction.ArticleListEdit:
        articleListEdit();
        break;
    case gjb.e.UserAction.ArticleListClose:
        articleListClose();
        break;
        
    case gjb.e.UserAction.TaskListEdit:
        taskListEdit();
        break;
    case gjb.e.UserAction.TaskListClose:
        taskListClose();
        break;
        
    case gjb.e.UserAction.UserListEdit:
        userListEdit();
        break;
    case gjb.e.UserAction.UserListClose:
        userListClose();
        break;

    case gjb.e.UserAction.EditSiteProfile:
        editSiteProfile();
        break;
    case gjb.e.UserAction.EventListEdit:
        eventListEdit();
        break;

    case gjb.e.UserAction.EventListClose:
        eventListClose();
        break;
        
    case gjb.e.UserAction.BrowseArticles:
        browseArticles(false);
        break;

    case gjb.e.UserAction.BrowseUsers:
        browseUsers();
        break;

    case gjb.e.UserAction.DeleteControl:
        deleteControl();
        break;
        
    case gjb.e.UserAction.DeleteFavorite:
        deleteFavorite();
        break;
        
    case gjb.e.UserAction.DeletePage:
        deletePage(UserAction);
        break;
    
    case gjb.e.UserAction.DeleteSection:
        deleteSection(UserAction);
        break;
    
    case gjb.e.UserAction.DontSave:
        dontSave();
        break;

    case gjb.e.UserAction.FinishLater:
        finishLater();
        break;

    case gjb.e.UserAction.ImportDraft:
        importDraft(UserAction);
        break;

    case gjb.e.UserAction.NavigateToSubdomain:
        navigateToSubdomain();
        break;
        
    case gjb.e.UserAction.RenamePage:
        renamePage();
        break;
        
    case gjb.e.UserAction.RenameSection:
        renameSection();
        break;
        
    case gjb.e.UserAction.ShowPageMenu:
        configurePageMenu();
        showMenu(e, 'pnlPageMenu', -70, 10);
        break;

    case gjb.e.UserAction.ShowSectionMenu:
        configureSectionMenu();
        showMenu(e, 'pnlSectionMenu', -70, 0);
        break;
        
    case gjb.e.UserAction.ResetEditorDirectory:
       // resetEditorDirectory(true);
        break;

    case gjb.e.UserAction.RssAddTo:
        rssAddTo(UserAction);
        break;

    case gjb.e.UserAction.RssSubtractFrom:
        rssSubtractFrom(UserAction);
        break;

    case gjb.e.UserAction.SelectColumns:
        selectColumns();
        break;

    case gjb.e.UserAction.SelectRSS:
        selectRSS();
        break;
        
    case gjb.e.UserAction.SelectThemes:
        selectThemes();
        break;
    case gjb.e.UserAction.SelectTools:
        selectTools();
        break;
    
    case gjb.e.UserAction.ShowTaskMenu:
        showMenu(e, 'pnlTasks', -150, 0);
        break;

    case gjb.e.UserAction.ChangeTheme:
        changeTheme();
        break;
    
    case gjb.e.UserAction.PublishDraft:
        publishDraft();
        break;

    case gjb.e.UserAction.EditorToggleSummary:
        editorToggleSummary(UserAction);
        break;

    case gjb.e.UserAction.EditorToggleToolbar:
        editorToggleToolbar(UserAction);
        break;
    
    case gjb.e.UserAction.EditorCancel:
        editorCancel(UserAction);
        break;

    case gjb.e.UserAction.EditorSelectPreview:
        editorSelectPreview(UserAction);
        break;
    case gjb.e.UserAction.EditorSelectDesign:
        editorSelectDesign(UserAction);
        break;

    case gjb.e.UserAction.ToggleHiddenPageLabel:
        toggleHiddenPageLabel(!$('chkHiddenPage').checked);
        break;

    case gjb.e.UserAction.ToggleHiddenPageInput:
        toggleHiddenPageInput(!$('chkHiddenPage').checked);
        break;
    }
}

function OnMouseUp(e) {

    // IE may not pass the event object
    if (e === null || e === undefined) {
        e = window.event;
    }
        
    // Turn move off
    IsCancelled = true;
    
    // Turn off scrolling
    stopScrolling();
    
    // Turn on text selection
    enableTextSelection();
    
    // If this is a move, not a click
    if (IsMove === true)
    {
        // Turn off the handlers
        document.onmousemove = null;
        Page.MouseTarget.ondragstart = null;
        
        if (Page.MouseTarget.DragGroup === gjb.e.DragGroup.ContentBox) {
        
            // Move content or DragHandles
            finishContentDrop();
            
            // Save the page without redrawing
            SaveRequired = true;
            Page.Save(gjb.e.RefreshOption.None);
            
        }
        else if (Page.MouseTarget.DragGroup === gjb.e.DragGroup.Section) {
        
            // Move content or DragHandles
            finishSectionDrop();
            
            // Reorder the sections
            reorderSections();
            
            // Save the page without redrawing
            //SaveRequired = true;
            //Page.Save(gjb.e.RefreshOption.None);
        }
        
        else if (Page.MouseTarget.DragGroup === gjb.e.DragGroup.Page) {
        
            // Move content or DragHandles
            finishPageDrop();
            
            // Reorder the pages
            reorderPages();
            
            // Save the page without redrawing
            //SaveRequired = true;
            //Page.Save(gjb.e.RefreshOption.None);
        }
        
        else if (Page.MouseTarget.DragGroup === gjb.e.DragGroup.ContentColumn) {
        
            // Set the background color the the dragged column
            Page.MouseTarget.className = 'colSlider';
            
            // Clear the drag image
            Page.MouseTarget.style.backgroundImage = 'none';
            
            // Re-read the page to reset the column offset widths
            Page.Read();
        
            // Resize columns.  Force a save.
            SaveRequired = true;
            Page.Save(gjb.e.RefreshOption.None);
        }
    }
    else {
        // Not a move
        processFunction(e);    
    }
}

// xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
// Start
// xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
function OnLoad() {

    // Read the page
    Page.Read();
}

function initDragDrop() {
    document.onmousedown = OnMouseDown;
    document.onmouseup = OnMouseUp;
}

// This is the STARTING function
initDragDrop();        
